Commit Graph
4 Commits
Author SHA1 Message Date
552ff4ed82 v0.41.11.1 ci: cut CI wallclock from 9min to 4.5min (#1457)
* feat(eval-longmemeval): RunOpts.engine seam for shared benchmark brain

Adds optional `engine?: PGLiteEngine` field to RunOpts. When set,
runEvalLongMemEval uses the caller-provided engine and skips the
withBenchmarkBrain wrapper (no fresh PGLite create, no disconnect on
exit). When unset, the production CLI path is unchanged: withBenchmarkBrain
creates and disposes a fresh engine per invocation.

Designed for the test seam that's about to land: one beforeAll-created
brain shared across all 13 runEvalLongMemEval calls in
test/eval-longmemeval-e2e.slow.test.ts, amortizing the ~1-3s PGLite
cold-create cost. runOneQuestion already calls resetTables() as its first
line so per-test isolation is preserved across the shared engine.

Pure additive seam — every existing caller (CLI, current tests that
already create engines via withBenchmarkBrain implicitly) keeps its
current behavior because opts.engine defaults to undefined.

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

* refactor(test): split eval-longmemeval slow tests + share engine across e2e half

The 884-line test/eval-longmemeval.slow.test.ts was the heaviest single
file in CI at ~359s on the matrix. Split by runEvalLongMemEval usage:

- test/eval-longmemeval.slow.test.ts (trimmed): 8 pure describes, 15 tests.
  Harness lifecycle, resetTables, schema-migration robustness, warm-create
  speed gate, adapter haystackToPages, source-boost guard, loadResumeSet,
  buildByTypeSummary. Local wall: 1.985s, projected CI ~42s.

- test/eval-longmemeval-e2e.slow.test.ts (NEW): 8 e2e describes, 11 tests.
  Every describe that calls runEvalLongMemEval — 13 call sites total.
  Threads a single beforeAll-created PGLite via the v0.41.10 RunOpts.engine
  seam. Local wall: 9.33s (was 15.09s without sharing); projected CI ~196s
  (was ~317s).

- test/helpers/longmemeval-stub.ts (NEW): shared makeStubClient + StubCall.
  Matches the existing test/helpers/ convention (with-env.ts,
  reset-pglite.ts). Single source of truth across the two split files.

- scripts/test-weights.json: replaced 359087ms entry with TWO entries
  (42000ms pure, 196000ms e2e). Projected linearly from local wall-clock
  × 21 CI scaling factor. First post-merge CI run will refine via
  scripts/mine-shard-weights.ts.

Test count is preserved: 15 pure + 11 e2e = 26, matches original file.
No production code changes in this commit — only test reorganization +
opt-in to the RunOpts.engine seam from the previous commit.

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

* ci(test): bump matrix 6→10, dedicate two slow files, cache bun-install

CI matrix wallclock: ~9 min → ~4.5 min. Three coordinated changes.

1. .github/workflows/test.yml matrix bumped from 6 → 10 shards. Per-shard
   total drops from 532s → 272s. Honest concurrency-budget call: total
   gated jobs go 13 → 18, so 2 concurrent PRs ≈ 36 queued, past the
   GH free-tier ~20 ceiling — single-PR runs unaffected, multi-PR days
   see queue pressure. Worth it for the 4-min CI saving.

2. Two slow files pulled out of the matrix and into their own dedicated
   jobs (sibling to verify, serial-tests):

   - slow-eval-longmemeval runs test/eval-longmemeval-e2e.slow.test.ts
     (~196s after the engine-sharing seam from the previous two commits).
   - slow-entity-resolve-perf runs test/entity-resolve-perf.slow.test.ts
     (~159s, single non-subdivisible perf test). The 60s default bun
     timeout is too tight for this file — bumped to 300000ms.

   scripts/test-shard.sh excludes both via -not -name clauses so the
   matrix sweep doesn't double-run them. Both new jobs wire into
   cache-write.needs and test-status.needs so CI gates on them.

3. actions/cache for ~/.bun/install/cache added to every job that runs
   bun install (test matrix, verify, serial-tests, slow-eval-longmemeval,
   slow-entity-resolve-perf). Keyed on bun.lock hash. Saves ~15s per job
   on cache hit; first-PR push pays full cost, subsequent runs hit cache.

Total CI wallclock now bounded by max(matrix ~4.5min, slow-eval ~3.3min,
slow-entity-resolve-perf ~2.6min) = ~4.5 min. The matrix is back to
being the floor; no single test file dominates a shard.

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

* chore: v0.41.10.0 — CI wallclock 9min → 4.5min

VERSION + package.json + CHANGELOG entry for the three preceding commits:

  feat(eval-longmemeval): RunOpts.engine seam for shared benchmark brain
  refactor(test): split eval-longmemeval slow tests + share engine across e2e half
  ci(test): bump matrix 6→10, dedicate two slow files, cache bun-install

Net user-visible: CI 'Test' check finishes in ~4.5 min instead of ~9 min.
Net contributor-visible: new RunOpts.engine seam on runEvalLongMemEval for
benchmark suites that want to amortize PGLite cold-create across many calls.

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

* fix(test): quarantine hybrid-meta + schema-pack-load-active to serial

The 6→10 matrix shard bump in this branch re-shuffled file distribution
across shard processes. Two pre-existing tests with hidden cross-file
state dependencies surfaced as failures in CI run #77779498812/13:

- test/hybrid-meta.test.ts shard 7: gateway state (configured by some
  other test in the same shard process) survived past the test's
  `delete process.env.OPENAI_API_KEY` call, so the early-return for
  expansion didn't fire and `expansion_applied` stayed true.
- test/schema-pack-load-active.test.ts shard 8: the schema-pack module's
  test-injected locator state was left behind by an earlier file, so
  `loadActivePack` with the default config didn't fall through to the
  bundled gbrain-base path.

Both files pass cleanly solo (verified). The pollution sources are
unidentified — bun's reporter only printed 14 of 71 file headers per
shard log, hiding the polluters. Rather than spelunk for the source,
rename both files to *.serial.test.ts. The serial pass runs them at
--max-concurrency=1 in a process that doesn't share state with the
parallel matrix shards.

Same-wave bookkeeping:
- scripts/check-test-isolation.allowlist: drop test/hybrid-meta.test.ts
  entry (file is now serial, no longer R1-eligible).
- scripts/test-weights.json: rename both weight entries to match the
  new filenames so future matrix LPT runs don't fall back to median.

Companion to a7d029d0/2e1c269e/5a749acb of this branch.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 15:46:25 -07:00
27b0e14af7 v0.41.8.0 fix(pglite): search/query/get exit cleanly + #1340 hint + #1342 breadcrumbs (#1405)
* fix(pglite): drain fire-and-forget last_retrieved_at writes before disconnect

Closes the structural bug class behind #1247, #1269, #1290: PGLite CLI
search/query/get_page commands printed results then hung at ~95-98% CPU
until SIGKILL. Root cause: bumpLastRetrievedAt's IIFE races
engine.disconnect() — PGLite's WASM runtime keeps Bun's event loop alive
while the dangling UPDATE settles.

Mirrors the existing awaitPendingSearchCacheWrites precedent landed in
v0.36.1.x for #1090. Tracks every IIFE promise in a module-scoped Set,
exposes awaitPendingLastRetrievedWrites(timeoutMs) that resolves once
all settle. Bounded with a 5s default timeout via Promise.race so a
future fire-and-forget that hangs forever can't recreate the bug class
at this layer — instead, the drain stderr-warns with a pending count
and returns timeout outcome so the caller can decide its fallback.

Test coverage: 6 unit cases covering empty drain, single + multi-pending
settle, throw-in-IIFE still settles, permanently-pending hits timeout
within bound, empty pageIds does not track.

This commit ships the helper + tracking + tests with NO consumer.
The cli.ts wiring lands in a follow-up commit (atomic bisect units).

Co-Authored-By: Park Je Hoon <jehoon@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pglite): snapshot+early-null disconnect + try/finally lock-leak guard

Refactor PGLiteEngine.disconnect() with two structural fixes:

(1) Snapshot + early-null pattern: capture db/lock refs and null the
    instance fields BEFORE any await. A concurrent connect() can no
    longer observe `_db` pointing at a handle that's mid-close. This
    is PR #1337's load-bearing contribution that we DID take.

(2) Wrap close + release in try/finally. Without this guard, a thrown
    db.close() would leak the file lock and wedge every next gbrain
    invocation on the stale lock. Codex outside-voice review (eng
    review finding #7) caught this gap when reviewing the snapshot
    refactor.

KEEP the original close-then-release order. PR #1337's diff swapped
this to release-then-close, which we explicitly REJECTED — releasing
the lock before close lets a sibling process try to connect to a
still-closing brain. The new lifecycle test file pins this ordering
so a future maintainer reading PR #1337's diff cannot accidentally
flip it.

Test coverage in test/pglite-engine-disconnect.serial.test.ts: 5
cases — close-before-release ordering, early-null observable inside
close, lock-still-releases on close-throw, double-disconnect
idempotency, reconnect-after-disconnect clean state. `.serial`
because each test creates a fresh PGLite engine (WASM cold-start
cost) — running in parallel shards would starve other tests.

Existing test/pglite-engine.test.ts: 100/100 still green.

Co-Authored-By: Matt Dean <matt-dean-git@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pglite): classify WASM init errors so #1340 gets the right hint (#1340)

Closes the user-facing half of #1340: on macOS 12.7.6 + Bun 1.3.14, the
PGLite connect() catch block hardcoded the macOS 26.3 hint (#223). The
actual root cause for #1340 is Bun's vfs: `/$$bunfs/root` is read-only
on older macOS, so PGLite cannot extract its pglite.data WASM payload.

Adds two exported helpers in pglite-engine.ts:

  classifyPgliteInitError(message): 'bunfs' | 'macos-26-3' | 'unknown'
  buildPgliteInitErrorMessage(verdict, original): string

Connect catch block now routes the hint by verdict. The bunfs hint
names `bun upgrade` + Node fallback. The macOS 26.3 hint keeps the
existing #223 link. Unknown falls through to a generic doctor + #223
fallback.

Per Codex eng-review finding #9, the bunfs regex is tightened to match
either the literal `$$bunfs` marker OR ENOENT+pglite.data
co-occurrence — NOT generic `pglite.data` substring (would fire on
unrelated errors). Negative test pinned.

Root fix is upstream Bun; this PR just stops misclassifying the
failure class so support traffic doesn't conflate two unrelated bugs.

Test coverage: 12 pure-function unit cases including the #1340
reporter's exact error string round-trip, the negative case Codex
caught, and all three verdicts × all three message contents.

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

* fix(cli): await last-retrieved drain + narrow timeout-only force-exit (#1247, #1269, #1290)

Wires the v0.40.10.0 drain helper into cli.ts and adds the IRON-RULE
behavioral regression test for the search-hang class. The drain is
called unconditionally for every op (not per-op-name gated — that was
the original PR #1259 mistake that left search and get_page exposed).

The narrow force-exit synthesis (decision D7 from the eng review,
informed by Codex outside-voice findings #1+#2+#8): when the drain
returns outcome:'timeout', AFTER engine.disconnect() resolves AND
the command is NOT a daemon, fire process.exit(0). The drain helper
already stderr-warned with the pending count, so the diagnostic
signal is preserved. Without this guard, a hung underlying promise
could still keep Bun's event loop alive past disconnect.

CRITICALLY narrower than PR #1337's blanket force-exit: the timeout
path is the only trigger. In the common case (drain settles cleanly
under 5s), no force-exit fires and the behavioral subprocess test
still catches future regressions. The shouldForceExitAfterMain guard
excludes 'serve' so the stdio + HTTP daemons stay alive past main().

e2e/pglite-cli-exit.serial.test.ts (NEW, IRON RULE):
  - gbrain search "foxtrot" → exits 0 within 15s
  - gbrain get alpha → exits 0 within 15s with foxtrot in stdout
  - gbrain query "foxtrot" --no-expand → exits within 15s (no-API-key
    graceful)
  - gbrain serve --http → stays alive 3+ seconds (daemon-survival
    regression guard)

fix-wave-structural.test.ts:
  - import assertion for awaitPendingLastRetrievedWrites
  - last-retrieved.ts exports + Set tracking + Promise.race + timeout
  - BEHAVIORAL positioning assertion: drain `await` appears textually
    BEFORE engine.disconnect `await` in the op-dispatch local-engine
    path. Survives variable-rename refactors; catches any new
    disconnect path that bypasses the drain.
  - shouldForceExitAfterMain excludes 'serve' AND the gate is
    conditioned on drainResult.outcome==='timeout'

Per D8 (Codex finding #5), explicitly do NOT add a drift-guard
counting bumpLastRetrievedAt callers — would block harmless
refactors and miss aliases.

Co-Authored-By: Park Je Hoon <jehoon@users.noreply.github.com>
Co-Authored-By: Matt Dean <matt-dean-git@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sync): add phase breadcrumbs to performSyncInner for #1342 triage

The #1342 reporter saw ZERO stderr output before their PGLite sync
hang, which made the bug impossible to triage from a community report
alone. Mirrors the pre-existing `[gbrain phase] sync.git_pull start/done`
pattern at the major pre-pull phase boundaries so the next #1342-shaped
report names WHICH phase spun.

Four new breadcrumbs at:
  - sync.resolve_repo (top of performSyncInner)
  - sync.load_active_pack (before the v0.39 T1.5 pack load)
  - sync.validate_repo_state (only when opts.sourceId is set —
    the re-clone branch)
  - sync.detect_head (before the isDetachedHead probe)

No behavior change — pure stderr instrumentation. Doesn't fix #1342
(which still needs investigation per the TODOS entry filed in this
wave), but converts "hung with no output" into actionable diagnostic
data the next time the bug shape is reported.

Per D9 in the eng review + Codex outside-voice finding #14.

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

* docs: annotate v0.40.10.0 PGLite hang wave in CLAUDE.md + regen llms

Key Files entries updated:

- src/core/pglite-engine.ts: documents the v0.40.10.0 disconnect
  refactor (snapshot+early-null + try/finally lock-leak guard, KEEPS
  close-then-release order), and the new classifyPgliteInitError /
  buildPgliteInitErrorMessage helpers for #1340 hint routing. Pins
  PR #1337's accepted-but-narrowed contribution and the rejected
  release-then-close ordering swap.

- src/core/last-retrieved.ts (within the brainstorm entry): documents
  the new awaitPendingLastRetrievedWrites drain, the Set tracking
  pattern, the 5s bounded timeout, the cli.ts narrow timeout-only
  force-exit synthesis with the serve-daemon guard, and the three
  community-validated reports (#1247/#1269/#1290) the fix closes.
  Credits PR #1259 (drain pattern) and PR #1337 (snapshot pattern +
  force-exit guard idea).

Regenerated llms.txt + llms-full.txt — build-llms.test.ts gates the
drift, all 7 cases green.

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

* docs(todos): file v0.40.10.0 PGLite hang follow-ups

Three deferred items from the v0.40.10.0 fix wave:

1. #1342 sync-hang investigation. Single-reporter, JS-tight-loop
   shape, needs reproducer before any fix. Documents the ruled-out
   hypotheses (lock-refresh heartbeat, v91 trigger, while-true loops)
   and three concrete diagnostic next steps. The v0.40.10.0 sync
   phase breadcrumbs make the next report actionable.

2. awaitPendingSearchCacheWrites timeout-symmetry retrofit. The #1090
   drain shipped without a timeout; the v0.40.10.0 #1247 drain ships
   with one. Apply the same Promise.race + stderr warn pattern for
   symmetry.

3. Drain-helper extraction. Per D4 in the eng review: two surfaces is
   the threshold for noticing, three for extracting. Pair with the
   symmetry retrofit above as one focused refactor when a third
   fire-and-forget surface appears.

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

* v0.40.10.0 fix(pglite): search/query/get exit cleanly + #1340 hint + #1342 breadcrumbs

Closes #1247, #1269, #1290 (PGLite CLI search/query/get hang at ~95-98%
CPU after printing results — three community-validated reports). Also
fixes #1340 (WASM init misroutes to macOS 26.3 hint when real cause is
Bun vfs read-only mount) and adds diagnostic phase breadcrumbs for the
single-reporter #1342 sync-hang investigation.

Core fix: track every fire-and-forget bumpLastRetrievedAt IIFE in a
module-scoped Set; cli.ts awaits the drain before engine.disconnect()
in the op-dispatch finally block; narrow process.exit(0) fires ONLY
when the drain times out AND the command isn't a daemon. Snapshot+
early-null disconnect pattern + try/finally lock-leak guard close the
partial-state race PR #1337 originally surfaced.

Co-Authored-By: Park Je Hoon <jehoon@users.noreply.github.com>
Co-Authored-By: Matt Dean <matt-dean-git@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: extract shouldForceExitAfterMain to its own module + add unit cases

Gap-audit follow-up: cli.ts is a script entrypoint (top-level main()
side effect), so importing it from a test fires the help output as a
side effect. Move shouldForceExitAfterMain into src/core/cli-force-exit.ts
so it can be unit-tested in isolation without the cli.ts script tail
running.

Adds test/cli-should-force-exit.test.ts (9 cases): bare serve, serve
with flags after, global flags BEFORE the command (the load-bearing
case for `gbrain --quiet serve`), op commands return true, non-daemon
CLI commands return true, empty argv defaults to true, flag-only argv,
default-arg fallback to process.argv.slice(2), substring-match
avoidance (`serves` is NOT `serve` — strict equality via Set, not
startsWith/includes).

The daemon command set is now an explicit ReadonlySet — future
daemons (a hypothetical `gbrain watch` or `gbrain daemon`) just add
their name to DAEMON_COMMANDS rather than chaining ||.

Updates fix-wave-structural.test.ts to look for the import + the
new DAEMON_COMMANDS shape.

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

* chore(version): rebase v0.40.10.0 → v0.41.6.0 (slot collision after v0.41.0.0+ landed)

origin/master moved from v0.40.8.1 → v0.41.0.0 while this wave was in
flight (PR #1367 minions cathedral). v0.41.1-v0.41.5 are claimed by
other in-flight branches, so v0.41.6.0 is the next available slot.

Bulk-renamed v0.40.10.0 → v0.41.6.0 across:
- VERSION + package.json (trio audit clean: 0.41.6.0 / 0.41.6.0 / 0.41.6.0)
- CHANGELOG.md (header + 3 prose references)
- CLAUDE.md (Key Files annotations)
- TODOS.md (follow-up entry header)
- src/cli.ts + src/core/cli-force-exit.ts + src/core/last-retrieved.ts
  + src/core/pglite-engine.ts + src/commands/sync.ts (inline comments)
- test/* (describe blocks + test file headers)
- llms-full.txt (regenerated via `bun run build:llms`)

bun.lock unchanged (version-only bump, no dep churn) per Codex #12.

Verify: 52/52 wave tests pass after rename, typecheck clean.

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

* test: quarantine seed-pglite to .serial.test.ts (parallel WASM cold-start flake)

The full-suite run during the v0.41.6.0 fix wave ship hit a 30s timeout
in test/seed-pglite.test.ts under heavy 4-shard parallel contention
(4972/4973 passed before SIGKILL). The test passes 11/11 in isolation.

Root cause: each test instantiates a fresh PGLiteEngine (5 instances
across the file, one per test) because each case writes to a different
mkdtemp-ed dbPath. Under parallel shard load, multiple shards each
cold-starting PGLite WASM simultaneously stretches the per-instance
init from ~5s to 30s+. The shared-engine pattern (canonical PGLite
block in CLAUDE.md R3+R4) doesn't apply here — different dbPaths
require different engines.

Fix per CLAUDE.md test-isolation quarantine rules: rename to
`.serial.test.ts` so the file runs in the post-parallel serial pass
with full WASM init capacity. Same pattern as
test/pglite-engine-disconnect.serial.test.ts (added in this wave) and
test/brain-registry.serial.test.ts (pre-existing).

Removes test/seed-pglite.test.ts from check-test-isolation.allowlist
since the .serial.test.ts rename auto-exempts it from the R3+R4 lint
(scan skips *.serial.test.ts). 641 non-serial unit files scanned,
lint clean.

Verify:
- bun test test/seed-pglite.serial.test.ts → 11/11 pass in 4.19s
- scripts/check-test-isolation.sh → OK
- bun run verify → all gates pass

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

* fix: pre-landing review fixes (C13 disconnect-hang, C1 set leak, C9 catch drain, M1 type drift)

Adversarial review + maintainability specialist surfaced four real
issues in the v0.41.8.0 wave. All four fixed in this commit; one
deferred to TODOS.md as a v0.41+ follow-up (unusual caller pattern).

**C13 [load-bearing, defense-in-depth for the wave's stated goal]:**
`await engine.disconnect()` inside the op-dispatch finally can ITSELF
hang on PGLite (db.close() racing OS-level FS state). When that
happens, the entire wave's force-exit guard never runs — we recreate
the original hang at a new layer. Fix: install an unref'd setTimeout
hard-exit fallback BEFORE entering the try/catch/finally. The timer
fires after DISCONNECT_HARD_DEADLINE_MS=10s with a stderr warn and
process.exit(0). unref ensures it doesn't keep the loop alive on a
healthy exit. Daemons (`serve`) are excluded by reusing the
shouldForceExitAfterMain guard.

**C9 [data freshness gap, narrow but real]:**
The drain ran ONLY in the success branch of try. If
`bumpLastRetrievedAt` fired (handler succeeded) but
`JSON.parse(JSON.stringify(...))` or `formatResult` then threw,
process.exit(1) killed the process and the in-flight UPDATE was
discarded. Fix: drain in the catch path too before process.exit(1)
(best-effort, bounded by the drain's own 5s timeout).

**C1 [daemon leak]:**
A timed-out IIFE used to stay in the pending-writes Set forever
because its `.finally` never fires. Long-lived `gbrain serve` would
accumulate references without bound across repeated timeouts. Fix:
explicitly `delete` the snapshot's tracked promises from the Set
after a timeout outcome. The IIFEs keep running (orphaned), but the
Set no longer leaks references. Pinned by a new unit test that
asserts the second drain after a timeout returns immediately with
empty pending count.

**M1 [silent type drift]:**
`cli.ts` duplicated the `{outcome, pending}` literal shape instead of
importing the `DrainOutcome` type that `last-retrieved.ts` exports
exactly for this purpose. Two-line fix: add `type DrainOutcome` to
the import and use it for `let drainResult`. Future changes to the
return shape now propagate through TypeScript.

**Deferred to TODOS.md (C6 — unusual caller pattern):**
Concurrent connect/disconnect on the same `PGLiteEngine` instance can
strand: disconnect snapshots+nulls the lock while connect is still
in-flight, leaving the resolved engine with no file lock held. Fix
requires an instance-level mutex; not worth the complexity for a
caller pattern that doesn't appear in production (single instance per
process, sequential lifecycle).

Also broadened `test/fix-wave-structural.test.ts` regex to accept
additional type-imports from `last-retrieved.ts` (e.g. the new
`type DrainOutcome` import that M1 added).

Test coverage: 53/53 wave tests pass (added C1-followup case to
last-retrieved.test.ts). The C1 fix is also pinned by tightening the
existing permanent-pending test's post-timeout assertion to expect
empty pending count rather than the prior (stale) "stays in set" note.

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

* docs: post-ship documentation sync for v0.41.8.0

Consolidate the duplicate 'take advantage of v0.41.8.0' sections in
the CHANGELOG entry into a single canonical block per the CLAUDE.md
template. The wave originally landed with both '### How to take
advantage' (line 13) and '### To take advantage' (line 57) as h3
headings. CLAUDE.md mandates one '## To take advantage of v[version]'
h2 block per release entry, with verify steps + an issue-filing
fallback for users hitting upgrade failures.

Promoted the second block to h2, added the issue-filing step, and
removed the redundant first block (the upgrade command is already
covered in the verify steps). Itemized changes section was unchanged.

llms.txt + llms-full.txt regenerated; structurally identical so no
content changes shipped.

* fix(test): find-experts-op queries schema dim instead of hardcoding 1536 (CI shard 1)

CI shard 1 failed on this branch with: \"expected 1280 dimensions, not 1536\"
from pgvector's CheckExpectedDim. Root cause: master's v0.36.0 changed
DEFAULT_EMBEDDING_DIMENSIONS from OpenAI's 1536d to ZeroEntropy's 1280d
(src/core/ai/defaults.ts:21). The test's basisEmbedding helper hardcoded
dim=1536, so beforeAll's upsertChunks failed when the schema column was
created at 1280d.

Latent on master: the weight-aware LPT bin-packing in
scripts/sharding.ts assigns files to shards deterministically based on
the COMPLETE file set. My branch adds 5 new test files, which shifted
find-experts-op.test.ts into shard 1. Master's shard 1 doesn't run this
file (it lands in a different shard there), so the bug never surfaced
in master's CI.

Fix: query the actual column dim via
SELECT atttypmod FROM pg_attribute after initSchema, then seed the
embedding at that width. This handles both paths (no-env CI → 1280;
env-configured local → 1536) without hardcoding either default.

Verify:
- bun test test/find-experts-op.test.ts → 11/11 pass with provider env
- env -i bun test test/find-experts-op.test.ts → 11/11 pass without
- bun run verify → all 21 parallel checks clean
- bun run typecheck → clean

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

* fix(lint): robust pure-bash allowlist match in check-test-isolation (CI verify)

CI verify failed on PR #1405 with check:test-isolation flagging
test/scripts/check-test-isolation.test.ts even though that file is
on line 22 of the allowlist (and has been since v0.26.7 as a permanent
exemption — its body contains process.env mutation fixtures that the
lint legitimately matches).

Could not reproduce locally on macOS bash 3.2 + BSD grep across any
locale (C, C.UTF-8, POSIX). Suspect a subtle interaction between the
prior `echo "$ALLOWLIST" | grep -qxF "$f"` form and one of:
Ubuntu 24.04's bash 5 set-e/pipefail semantics, GNU grep edge case on
the first-line entry, or `bun run` + GNU timeout subshell interaction.
Diagnostic value of chasing further is low — the fix is to drop the
grep+pipe form entirely.

Switch is_allowlisted() to pure-bash `case $'\n'"$ALLOWLIST"$'\n' in
*$'\n'"$f"$'\n'*) return 0 ;; esac` whole-line matching:
- Locale-free (no character-class interaction)
- Pipe-free (no pipefail / SIGPIPE / buffering)
- Subshell-free (no env or exit-code propagation gotchas)
- set-e-quirk-free (no left-side compound failure)
- ~100x faster (no fork+exec per call across 689 files)

Verified locally: lint OK (689 files), case-match returns true for the
allowlisted file and false for a non-allowlisted file. bun run verify
clean (21/21 parallel checks pass).

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

---------

Co-authored-by: Park Je Hoon <jehoon@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Matt Dean <matt-dean-git@users.noreply.github.com>
2026-05-25 14:20:19 -07:00
87840341ea v0.31.7 fix-wave: doctor stops crying wolf — 5 community PRs (#798 + #788 + #536 + #376 + #128 adapted) (#804)
* fix: merge resolver entries from all files (RESOLVER.md + AGENTS.md)

OpenClaw deployments typically have AGENTS.md at the workspace root as the
real skill dispatcher (200+ entries), while gbrain skillpacks install a
thin skills/RESOLVER.md (~40 entries). The previous first-match-wins policy
meant check-resolvable only saw the thin RESOLVER.md, reporting 187 skills
as 'unreachable' when they were fully routed in AGENTS.md.

Now: check-resolvable collects entries from ALL resolver files across both
the skills directory and its parent. Entries are deduped by skillPath
(first occurrence wins). The combined content is also passed to the
routing-eval (Check 5) so routing fixtures see the full trigger index.

New function findAllResolverFiles() in resolver-filenames.ts returns all
matching files instead of just the first. findResolverFile() is unchanged
(backward-compatible for callers that need a single path).

Before: 37/224 reachable (our deployment)
After:  200/224 reachable (remaining 24 are genuine gaps)

Tests: 8 new (findAllResolverFiles + checkResolvable merge behavior)

* fix: graph_coverage skipped when brain has 0 entity pages

Closes #530.

`graph_coverage` measures `link_coverage` (fraction of entity pages with
inbound links) and `timeline_coverage` (fraction with timeline entries).
Both formulas divide by entity-page count.

For markdown-only brains (journals, wikis, notes — Karpathy's original
LLM Wiki use case) the entity count is 0, so coverage is structurally
undefined. The check still reported 'warn: 0%' under that condition,
which:
1. Brain owners cannot satisfy without indexing code/entities
2. Doctor's hint references stale commands (`link-extract` /
   `timeline-extract` were renamed to `extract` in v0.22)
3. Adds noise to compliance/health automation gating on doctor exit

Fix: detect entity-page count via SQL. If 0, mark check 'ok' with explanation.
Otherwise keep existing logic but update hint to current `gbrain extract all`.

Tested on Nous AGaaS production wiki: 2533 markdown pages, 100% embedded,
6086 wikilinks, 1964 timeline entries — 0 entity pages — graph_coverage
correctly clears.

* fix(doctor): deprecate stale link-extract / timeline-extract verb names

The graph_coverage hint and the link-extraction.ts header comment
still referenced `gbrain link-extract` / `gbrain timeline-extract`,
which were consolidated into `gbrain extract <links|timeline|all>` in
v0.16. Following the consolidation in #536's resolution (which fixed
the doctor hint to `gbrain extract all`), this commit removes the last
stale reference in `src/core/link-extraction.ts`'s header comment.

Originally PR #376 by @FUSED-ID. The doctor.ts portion of #376 is
absorbed by #536's richer warn message; this commit lands #376's
`link-extraction.ts` portion only.

Co-Authored-By: Leon-Gerard Vandenberg <FUSED-ID@users.noreply.github.com>

* test(doctor): pin canonical `gbrain extract all` hint, ban stale verbs

IRON-RULE regression guard for PR #376 + #536's graph_coverage hint
fix (locked in v0.31.7 eng-review). The removed verbs `gbrain
link-extract` and `gbrain timeline-extract` were consolidated into
`gbrain extract <links|timeline|all>` in v0.16 but the hint kept
suggesting them for ~30 releases. Pin the user-facing copy at the
source-string level so a future edit can't silently re-regress.

Structural assertion in the existing `doctor command` describe block,
matching the file's existing `frontmatter_integrity` / `rls_event_trigger`
pattern. No DB-fixture infrastructure needed.

* fix: sync RESOLVER.md triggers with v0.25.1 skill frontmatter

`gbrain doctor` reported 36 routing-miss/ambiguous warnings against the
v0.25.1 wave skills (book-mirror, article-enrichment, strategic-reading,
concept-synthesis, perplexity-research, archive-crawler, academic-verify,
brain-pdf, voice-note-ingest). Each skill's frontmatter declared 4-5
triggers, but only the first ever made it into RESOLVER.md's hand-curated
rows. The structural matcher couldn't find any specific phrase for
realistic user intents, so requests fell through to broader parents
(`ingest`, `enrich`, `data-research`).

Pulled the missing triggers from each skill's `triggers:` frontmatter
into the matching RESOLVER.md row. Converted media-ingest's prose row
to quoted triggers so the matcher actually sees them. Added
`"summarize this book"` to media-ingest (covers a book-mirror
disambiguation fixture). Marked article-enrichment + perplexity-research
fixtures with `ambiguous_with` for the parent skills they intentionally
chain with — RESOLVER.md's preamble explicitly documents that skills are
designed to chain, so this is acknowledging the truth, not papering over
a bug.

Result: 36 routing warnings → 0. resolver-test/check-resolvable/
routing-eval suite: 140/0.

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

* fix(doctor): find skills/ on every deployment shape (read-path-only)

Adapts the install-path resolution from PR #128 (TheAndersMadsen) into
the existing 5-tier autoDetectSkillsDir architecture. Two new code paths,
read-path-only by design:

1. Tier-0 $GBRAIN_SKILLS_DIR explicit operator override on the SHARED
   autoDetectSkillsDir. Safe for both read and write paths because the
   operator explicitly set the var — opt-in retargeting is fine.

2. New autoDetectSkillsDirReadOnly() function for READ-ONLY callers
   (gbrain doctor, check-resolvable, routing-eval). Wraps the shared
   detect; on null, walks up from fileURLToPath(import.meta.url) gated
   by isGbrainRepoRoot() so unrelated repos along the install path
   can't false-positive.

The split is the architectural fix for a write-path regression risk
codex outside-voice review surfaced (eng-review D5): adding the
install-path fallback to the SHARED resolver would let `gbrain skillpack
install` from `~` silently target the bundled gbrain repo's skills/
instead of the user's actual workspace. Three write-path call sites stay
on the original autoDetectSkillsDir; three read-path call sites switch
to the new readOnly variant.

Closes the install-path footgun for hosted-CLI installs:
`bun install -g github:garrytan/gbrain && cd ~ && gbrain doctor` now
finds the bundled skills/ instead of warning "Could not find skills
directory."

Test surface: 8 new cases in test/repo-root.test.ts covering tier-0
valid/invalid/precedence, install-path walk, isGbrainRepoRoot gate
(via primary-success-no-drift assertion), AUTO_DETECT_HINT updates,
and the D5 regression guard that pins the read-path/write-path split.

Co-Authored-By: Anders Madsen <TheAndersMadsen@users.noreply.github.com>

* docs(changelog): expand v0.31.7 entry for full 5-PR doctor wave

Promotes headline from "doctor stops crying wolf about unreachable
skills on OpenClaw" to the assembled wave's narrative: every doctor
false-positive class on disk today, plus the install-path footgun
that bit every hosted-CLI user.

Numbers-that-matter table expanded to 6 rows covering all 5 PRs.
Itemized-changes section grouped by sub-wave: resolver merge,
RESOLVER.md trigger sync, graph_coverage zero-entity, stale verb
hint fix, install-path resolver. Contributors named explicitly:
@mayazbay, @psperera, @FUSED-ID, @TheAndersMadsen. "For contributors"
section flags the new SkillsDirSource variants and the read-path /
write-path split as the canonical pattern for future fallback
additions.

* chore(v0.31.7): bump version + regenerate llms + fix CLI regression-gate

Wraps up the v0.31.7 doctor-fix wave:

- VERSION + package.json: 0.31.1.1-fixwave -> 0.31.7
- llms-full.txt: regenerated against the expanded v0.31.7 CHANGELOG
  entry (committed bundle drift caught by test/build-llms.test.ts)
- test/check-resolvable-cli.test.ts: update the REGRESSION-GATE for
  empty-cwd no_skills_dir error to reflect v0.31.7's intentional
  behavior change. The install-path fallback in autoDetectSkillsDirReadOnly
  now finds the bundled skills/ from any cwd inside the gbrain repo,
  so the test asserts source: 'install_path' instead of error: 'no_skills_dir'.
  This is the wave's headline capability ("doctor finds itself on every
  deployment shape") rather than a regression.

Pre-existing flake unrelated to this wave: BrainRegistry — lazy init >
empty/null/undefined id routes to host fails on machines that have
~/.gbrain/config.json present (the test assumes test env has none).
Reproduces on master before this wave landed; not a v0.31.7 regression.
Filed for follow-up in next maintainer hygiene sweep.

* fix(doctor): close write-path leak in --fix + sync routing-eval merge

Codex adversarial review of v0.31.7 caught a HIGH that the eng review
missed (D6 lock during /ship): the read-path-only architecture for the
install-path fallback is leaky because TWO of the three "read-only"
callers (doctor, check-resolvable) actually have write modes via --fix
that call autoFixDryViolations() and writeFileSync to SKILL.md files.
A user running `cd ~ && gbrain doctor --fix` with no skills/RESOLVER.md
up the cwd tree would resolve via the install-path fallback to the
bundled gbrain repo and silently rewrite the install-tree skills —
exactly the regression D5's split was supposed to prevent.

Fix: when --fix is requested and the resolved skills dir came from the
install-path source, refuse with a clear error pointing at GBRAIN_SKILLS_DIR
/ OPENCLAW_WORKSPACE / --skills-dir as explicit overrides. The read parts
of doctor and check-resolvable continue to benefit from the install-path
fallback (the v0.31.7 capability headline); only --fix is gated.

Plus a MEDIUM consistency fix codex flagged: routing-eval was still
single-file-only while check-resolvable does multi-file merge across
skills/RESOLVER.md + ../AGENTS.md. On OpenClaw layouts this caused
routing-eval and check-resolvable to disagree on what's routable.
routing-eval now uses the same findAllResolverFiles + content-merge
pattern as check-resolvable, so all three commands see the same
trigger index.

Test coverage: D6 regression guard in test/check-resolvable-cli.test.ts
spawning a real subprocess from an empty tempdir (no env, no cwd
fallback) and asserting --fix refuses with the correct stderr message.

Co-Authored-By: Codex (outside-voice review) <noreply@openai.com>

* docs(changelog): note D6 --fix gate + routing-eval merge in v0.31.7 entry

* docs: post-ship sync for v0.31.7

CLAUDE.md updates only. CHANGELOG.md was already authored by /ship and was left untouched.

- src/core/repo-root.ts annotation: read-path/write-path split, tier-0 GBRAIN_SKILLS_DIR override, autoDetectSkillsDirReadOnly install-path fallback, D6 --fix safety gate.
- src/commands/check-resolvable.ts annotation: multi-file resolver merge across skills dir + parent (37/224 -> 200/224 reachable on the reference OpenClaw layout), install-path read-only fallback, D6 --fix gate.
- src/commands/routing-eval.ts annotation: same multi-file merge as check-resolvable; v0.25.1 RESOLVER.md trigger sync.
- src/commands/doctor.ts annotation: switched to autoDetectSkillsDirReadOnly so 'cd ~ && gbrain doctor' finds bundled skills via install-path fallback; --fix D6 install-path refuse-write gate; graph_coverage zero-entity short-circuit + canonical 'gbrain extract all' hint with regression-test pin.
- Test inventory: replaced bare regression-v0_16_4 line with explicit test/repo-root.test.ts entry (20 cases - 12 existing + 8 new D3/D5) and new test/resolver-merge.test.ts entry (8 cases).

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

* docs(llms): regenerate after CLAUDE.md sync for v0.31.7

* ci(test): quarantine *.serial.test.ts files from test-shard

CI's test-shard.sh was including *.serial.test.ts files in the parallel
shard runs, which broke voyage-multimodal.test.ts: 18 of its 22 tests
failed in CI shard 2 because eval-takes-quality-runner.serial.test.ts
ran before it in the same bun-test process and leaked its mock.module()
substitution of src/core/ai/gateway.ts. The leaked mock omitted
embedMultimodal and resetGateway, so voyage-multimodal saw `undefined
is not a function` everywhere it touched the gateway.

Locally `bun run test` (run-unit-parallel.sh → run-unit-shard.sh)
already excludes *.serial.test.ts and runs them via `bun run test:serial`
in their own pass with --max-concurrency=1. Master ran green there;
only CI's matrix shards exposed the leak. The runner.serial test file's
own header comment explicitly calls out this exact cross-file mock
leak — the quarantine was the design, CI just wasn't honoring it.

Three changes:

1. scripts/test-shard.sh — exclude *.serial.test.ts and *.slow.test.ts
   from the find expression, mirroring scripts/run-unit-shard.sh.

2. .github/workflows/test.yml — add a `test-serial` sibling job that
   runs `bun run test:serial`. Keeps serial tests gating CI without
   merging them back into the parallel shards.

3. test/scripts/test-shard.test.ts — regression test pinning the three
   exclusion clauses (serial, slow, e2e) so a future refactor that
   drops one of them fails loud rather than silently re-introducing
   the cross-file mock leak.

Verified locally:
- shard 2 reproduction: 18 voyage-multimodal failures → 0 (1 unrelated
  env-dependent perf flake remains, won't fail on CI)
- bun run test:serial: 189/190 pass (1 unrelated env-dependent
  BrainRegistry flake from ~/.gbrain/config.json presence)
- typecheck + check:test-isolation clean

* ci(test): rephrase mock-module comment to satisfy R2 lint

The verify gate's check:test-isolation flagged test/scripts/test-shard.test.ts
because the JSDoc comment contained the literal string 'mock.module()'
which matches R2's grep regex 'mock\.module[[:space:]]*\('. The file
itself doesn't use mock.module — it just describes why the linter rule
exists in human-readable prose.

Rephrased to avoid the trailing parens. The regex requires the open
paren, so 'bun's module-mocking primitive' instead of 'mock.module()'
is invisible to the linter while preserving meaning for the next
maintainer who reads the test.

* docs(claude): tighten version-consistency rules + add merge recovery procedure

After several merges from master where VERSION + package.json +
CHANGELOG.md drifted out of sync (each merge hit conflicts on those
three files; auto-merge sometimes resolved silently in the wrong
direction), CLAUDE.md gets an explicit drift-recovery checklist + a
3-line paste-ready audit command anyone can run.

Three additions to the existing "Version locations" section:

1. **Mandatory audit command** — three echo lines that print VERSION,
   package.json version, and the top CHANGELOG header. All three MUST
   match the wave's `MAJOR.MINOR.PATCH.MICRO`. Designed for paste-after-
   every-merge use.

2. **Merge-conflict recovery procedure** — exact sed/echo patterns for
   resolving VERSION + package.json + CHANGELOG conflicts, in the order
   to apply them. Names the anti-pattern (mixing `git checkout --ours`
   on the trio) that's bitten us before.

3. **Pre-push gate** — re-run the audit before `git push` of any merge
   commit. /ship Step 12 catches drift but only if you actually run
   /ship; manual pushes skip the check.

Confirmed consistent at d361482a, 7e8f6960, 65a5994a (every merge
commit on this branch). The doc gap was the rules being too loose,
not the rules being wrong — this beefs up the procedural side so the
next merge can't silently desync.

* docs(llms): regenerate after CLAUDE.md edit + tighten the rule

CI failed on the build-llms generator test because CLAUDE.md edited
in fe050ae0 (version-consistency procedure) shipped without a
matching `bun run build:llms` regen. The committed llms-full.txt was
77 lines short of fresh generator output, and test/build-llms.test.ts
caught the drift in CI shard 1.

Two changes:

1. llms.txt + llms-full.txt — regenerated to match current CLAUDE.md.

2. CLAUDE.md — strengthened the "Auto-derived" entry for llms.txt /
   llms-full.txt with explicit "every CLAUDE.md edit chases with
   `bun run build:llms` in the same commit" wording. Notes that
   `verify` doesn't run the build-llms test, only the full unit
   suite does, so a clean typecheck is NOT enough to know you can
   push after touching CLAUDE.md.

This is now the third time this has bitten the wave. The previous
"Auto-derived" entry said the right thing but was buried in a list;
elevating it to imperative voice with a count of past regressions
should make the next CLAUDE.md edit hard to land without the chaser.

---------

Co-authored-by: garrytan-agents <garrytan-agents@users.noreply.github.com>
Co-authored-by: Madi Ayazbay <madia@Mac.localdomain>
Co-authored-by: Leon-Gerard Vandenberg <FUSED-ID@users.noreply.github.com>
Co-authored-by: psperera <pperera@mac.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Anders Madsen <TheAndersMadsen@users.noreply.github.com>
Co-authored-by: Codex (outside-voice review) <noreply@openai.com>
2026-05-10 13:20:07 -07:00
058fe69575 v0.26.7 test: isolation foundation (helpers + lint + quarantine) (#613)
* test: add withEnv helper + canonical PGLite block JSDoc

withEnv(overrides, fn) saves prior values, runs the callback, restores
via try/finally — including on throw. Handles delete via undefined
override. Nested calls compose. Cross-test safe; explicitly NOT
intra-file concurrent-safe (process.env is process-global).

7 unit cases covering sync, async, delete-key, delete-when-prior-unset,
restore-on-throw, nested compose, multi-key atomic restore.

reset-pglite.ts JSDoc extended with the canonical 4-line PGLite block
(beforeAll create + afterAll disconnect + beforeEach reset). The lint
script in the next commit enforces this exact shape.

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

* test: add check-test-isolation lint script + wire into verify

Grep-based lint enforcing 4 rules on non-serial unit test files:
  R1: no process.env mutations (use withEnv() or rename to *.serial.test.ts)
  R2: no mock.module() (rename to *.serial.test.ts)
  R3: new PGLiteEngine( only inside beforeAll() context
  R4: PGLiteEngine creators must pair with afterAll{disconnect}

Wired into 'bun run verify' and 'bun run check:all' (NOT 'bun run test'
which is the parallel runner script with no pre-check chain). Matches
the existing scripts/check-*.sh family shape (jsonb, progress, etc).

51 baseline violators captured in scripts/check-test-isolation.allowlist.
List MUST shrink over time — entries removed by v0.26.8 (env sweep) and
v0.26.9 (PGLite sweep). New files cannot be added.

CLAUDE.md ## Testing section extended with R1-R4 rules table, the
canonical 4-line PGLite block, withEnv pattern, and when-to-quarantine
guidance.

16 fixture-driven test cases for the lint: clean, R1 (5 patterns + 1
negative), R2, R3 (top-level vs in-beforeAll), R4 (missing disconnect),
*.serial.test.ts skip, test/e2e/ skip, allowlist (3 cases).

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

* test: quarantine cycle and embed mock.module test files

Both files use mock.module(...) at top level — leaks across files in
the same shard process. The check-test-isolation lint (R2) bans this
pattern in non-serial files; quarantine is the escape hatch.

Per v0.26.7 plan D5: prefer quarantine over DI on runCycle/runEmbed.
Production signatures stay frozen; tests run at --max-concurrency=1
in the serial post-pass (the existing pattern shipped in v0.26.4 for
brain-registry and reconcile-links).

Quarantine count: 2 → 4. Cap raised to 10 informational per D15.

Renames:
  test/core/cycle.test.ts → test/core/cycle.serial.test.ts
  test/embed.test.ts      → test/embed.serial.test.ts

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

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

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

* docs: post-ship documentation sync for v0.26.7

- README.md "Contributing" line: point to bun run test + bun run verify (parallel fast loop)
- CONTRIBUTING.md "Running tests": rewrite for the v0.26.4/v0.26.7 test surface (parallel runner, verify, slow/serial/e2e tiers)
- CONTRIBUTING.md adds "Writing tests that survive the parallel loop" section: R1-R4 lint, canonical PGLite block, withEnv pattern, when to quarantine
- llms-full.txt regenerated to pick up the README + CONTRIBUTING changes

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 12:59:52 -07:00