mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* fix(tests): root-cause two master test-infra flakes
gateway.test.ts: add afterAll(resetGateway) hook. The file's tests use
beforeEach(resetGateway) for per-test isolation, but the FINAL test was
leaving configureGateway({env: {OPENAI_API_KEY: 'openai-fake'}}) in the
gateway module state. Sibling files in the same bun shard (e.g.
test/ingestion/ingest-capture.test.ts) then triggered embed() against
the real OpenAI endpoint with the leaked fake key, wedging the shard
with 'Incorrect API key provided: openai-fake'.
header-transport.test.ts → .serial.test.ts: the file mutates RECIPES
(gateway's module-scoped recipe map) plus configureGateway, then asserts
fakeChatFetch was invoked. Under bun's intra-shard parallelism, sibling
files like test/ai/rerank.test.ts race the same state — chat would see
result.text === '[]' instead of 'ok' because another test called
resetGateway between this test's configureGateway and chat. Quarantining
as .serial.test.ts moves the file into the post-parallel serial pass
at --max-concurrency=1 per repo convention.
* refactor(doctor): extract buildChecks seam + behavioral coverage
src/commands/doctor.ts: extract buildChecks(engine, args, dbSource):
Promise<Check[]> from runDoctor. The check-building logic moves into
the new exported function; existing exported computeDoctorReport(checks)
at line 78 stays untouched. runDoctor becomes a thin wrapper:
buildChecks → computeDoctorReport → render + process.exit. All 10
process.exit sites stay in place. The two early-return paths drop
their inline outputResults+process.exit calls and return the partial
check list; the wrapper still produces identical observable output.
test/doctor-behavioral.test.ts (13 cases): pure pure-aggregation cases
pin computeDoctorReport math (3 fails → -60 points, score clamped at 0,
mixed outcome → unhealthy with fail dominating). Orchestrator cases
assert --fast flag honors the skip set, --json doesn't alter the list,
no-engine path returns partial without process.exit, and the snapshot
of load-bearing check names catches accidental drop-outs during
future refactors.
test/doctor-cli-smoke.serial.test.ts (1 case): subprocess smoke spawning
'bun run src/cli.ts doctor --json' against a fresh PGLite tempdir brain.
Catches render-path bugs that buildChecks-only tests miss — the class
the v0.38.2.0 partial-scan wave exposed. Quarantined as .serial because
PGLite write-locks don't play well with parallel runners; skippable via
GBRAIN_SKIP_SUBPROCESS_TESTS=1.
* feat(operations): trust-boundary contract test + filter-bypass shell guard
test/operations-trust-boundary.test.ts (14 cases): hybrid design per
plan D7. Pure assertions over all 74 ops cover the drift-detection
win (every op has a scope; every mutating op has a non-read scope;
hasScope(['read'], op.scope) correctly rejects 'admin' or 'write').
Plus the canonical filter contract: every localOnly: true op is
excluded from operations.filter(op => !op.localOnly). Plus targeted
handler-invocation cases for the two historically-broken HTTP-callable
classes: submit_job(name='shell', ctx.remote=true) MUST reject (F7b
HTTP MCP shell-job RCE class), and search_by_image(image_path,
ctx.remote=true) MUST reject (D18 P0 image-leak class). file_upload
and sync_brain are deliberately omitted from handler-invocation tests
because they're localOnly — calling their handlers directly tests an
impossible production path (codex CMT-3). All 7 localOnly ops are
snapshot-pinned by name to catch future flag-flips.
scripts/check-operations-filter-bypass.sh: greps src/ for any module
that imports the 'operations' value from core/operations.ts outside
the canonical filter site. Three import shapes detected: destructured,
aliased ('as ops'), namespace ('import * as'). Explicit allow-list of
10 known-safe importers with one-line rationale per entry. Plus a
filter-presence check on serve-http.ts that fails if the canonical
filter expression is refactored out. Codex /ship adversarial review
caught the original narrow regex missed aliased + namespace bypasses;
the expanded regex closes that class. Type-only imports of sibling
exports (sourceScopeOpts, OperationContext) are not flagged.
package.json: wires check:operations-filter-bypass into the verify
chain alongside check:jsonb and check:progress.
* refactor(cycle): export runPhaseLint+runPhaseBacklinks; add wrapper tests
src/core/cycle.ts: adds 'export' keyword to two existing phase
functions so behavioral tests can drive them without going through
runCycle's full setup cost. No body changes; no behavior change.
Documented as internal helpers exposed for test-only consumption —
downstream code should NOT take a dependency on them; existing
plan-eng-review D9 explicitly accepted the API-widening tax for
testability.
test/cycle-legacy-phases.test.ts (11 cases): combined file with two
describe blocks per plan D5 (DRY — shared setup, future phase
wrappers land as additional describes). Narrowed to result-mapping
+ error envelope per codex CMT-1 (legacy phases don't extend
BaseCyclePhase and don't take a progress reporter or AbortSignal
directly, so the contract surface is counter → status enum + try/catch
envelope). Cases: clean run → status='ok', partial fix → status='warn'
with dryRun in details, dry-run path doesn't write, throw-from-lib
→ status='fail' with envelope populated (no exception escape).
Verified runLintCore and runBacklinksCore both throw on missing dir,
so the throw-from-lib cases are deterministic.
* chore: bump version and changelog (v0.40.4.1)
E2E + unit test gap coverage wave. Closes 4 audit gaps with new
behavioral coverage (doctor orchestrator + subprocess smoke, operations
trust-boundary contract + filter-bypass guard, cycle phase wrapper
result-mapping). Verifies 3 audit gaps were already covered (ingestion
dedup/daemon/skillpack-load, phantom-redirect, ingestion test-harness).
Root-causes 2 pre-existing master flakes (gateway state leak, header-
transport cross-shard race). Files 5 follow-up TODOs from codex
adversarial-review findings.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: note v0.40.4.1 doctor.buildChecks + cycle phase exports in CLAUDE.md
Adds three Key-files entries pinning the v0.40.4.1 test-wave additions:
- doctor.ts extension: buildChecks seam + behavioral tests (13+1 cases)
- cycle.ts extension: runPhaseLint + runPhaseBacklinks exports (11 cases)
- operations-trust-boundary contract + check-operations-filter-bypass.sh
Regenerates llms-full.txt to match (CLAUDE.md edits require build:llms per
project rule, otherwise test/build-llms.test.ts fails in CI shard 1).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(tests): reset gateway in put_page write-through tests to skip embed in CI
CI failure mode: 9 tests in test/ingestion/put-page-write-through.test.ts
failed with `AIConfigError: [embed(zeroentropyai:zembed-1)] Unauthorized`
because put_page's handler at src/core/operations.ts:622 computes
`noEmbed = !isAvailable('embedding')`. When the gateway state has been
configured by a sibling test (or by the cli.ts module-load path reading
.env.testing) with a fake/stale ZEROENTROPY_API_KEY, isAvailable returns
true → put_page tries to embed → the real ZeroEntropy API returns 401.
Local dev passes because real ZE keys are present; CI doesn't have them.
Fix: call resetGateway() in beforeEach so isAvailable('embedding')
returns false → put_page's noEmbed path activates → no network call.
Also reset in afterAll to avoid leaking the cleared state to sibling
files in the same bun shard (the v0.40.4.1 gateway state-leak class
that motivated the earlier gateway.test.ts fix).
The test exercises write-through behavior, not embedding. No need for
a real or fake embed transport — bypass entirely.
* fix(tests): widen brain-writer partial-scan deadlines to absorb CI timing variance
CI failure: scanBrainSources partial-scan state > "hanging COUNT does not
exceed deadline — Promise.race timeout fires" failed once on a GitHub
Actions runner. The test asserted a 100ms deadline budget with a 500ms
bound; observed test duration was 187ms on CI (passes locally 20/20
runs at the original budget).
Root cause: Node.js timer drift under shard parallelism. The deadline
check at src/core/brain-writer.ts:503 uses strict `Date.now() > deadline`,
so when the setTimeout in Promise.race fires exactly at the boundary
(e.g. start+100ms when deadline is start+100ms), the post-await check
sees equality and skips the markRemainingSkipped branch. The test
also asserts elapsed < 500ms; CI overhead can push elapsed past that
bound when setTimeout drifts.
Fix: widen the deadline budget on both deadline-race tests proportionally
(keeps the same 2x ratio that proves "query exceeds deadline"). No
src/ changes — this is purely a test robustness widening.
- "hanging COUNT" test: 100ms → 500ms deadline, 500ms → 2500ms bound
- "slow COUNT" test: 50ms → 250ms deadline, 100ms → 500ms query delay
Verified locally: 20/20 stress runs at the widened budgets, no fails.
* fix(brain-writer): deadline check is >= not > (closes CI flake at boundary)
CI failure recurred: same "hanging COUNT does not exceed deadline" test
failed again at 588ms (past my previous 500ms deadline + 2500ms bound
widening). The root cause isn't test timing — it's an off-by-one in
the source.
src/core/brain-writer.ts had two deadline checks using strict `>`:
- line 445 (between-source abort)
- line 503 (post-COUNT-await re-check)
The Promise.race setTimeout resolves null at exactly `remainingMs` from
now, so post-await Date.now() OFTEN equals the deadline within
integer-ms precision. With `>`, the check skipped → scanOneSource ran
on the source whose budget had just been eaten → that source got
status='scanned' instead of 'skipped'. The test's `expect(firstSource
.status).toBe('skipped')` failed.
Fix: both checks now use `>=`. When Date.now() equals deadline exactly,
the budget IS exhausted — proceeding would let the next source eat its
own budget on top of what's already spent. Matches the boundary the
Promise.race's remainingMs <= 0 immediate-null path uses (line 481).
This is the real fix for the v0.40.x CI flakes; my earlier test-budget
widening papered over the symptom without closing the boundary. Kept
the wider 500ms deadline for headroom but added a comment pointing at
the operator fix as the load-bearing change.
Verified: 20/20 stress runs green locally after the operator fix.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
228 lines
9.3 KiB
TypeScript
228 lines
9.3 KiB
TypeScript
/**
|
|
* v0.39 behavioral coverage for `gbrain doctor`'s check orchestrator.
|
|
*
|
|
* Drives the exported `buildChecks(engine, args, dbSource): Promise<Check[]>`
|
|
* seam directly (added in v0.39 — extracted from runDoctor's body so the
|
|
* orchestrator is unit-testable without process.exit). Pairs with the
|
|
* subprocess smoke at test/doctor-cli-smoke.test.ts which covers the
|
|
* runDoctor render + exit-code path the seam can't reach in-process.
|
|
*
|
|
* Coverage strategy (D2 — "outcome-shaped + snapshot pin"):
|
|
* - Snapshot pin the check-name list against a fresh PGLite brain so
|
|
* accidental check drop-outs during refactors fail loudly with a
|
|
* reviewable diff at PR time.
|
|
* - Exercise computeDoctorReport math (3 fails → 60 pts lost, etc.) with
|
|
* synthesized inputs so the aggregation contract is pinned.
|
|
* - Honor the --fast flag's skip-set (DB checks absent).
|
|
* - --json arg is wrapper-only; buildChecks output unaffected.
|
|
*
|
|
* Per-check leaf coverage is deferred to a TODO (see plan): doctor.ts
|
|
* exports 20+ check helpers (whoknowsHealthCheck, takesWeightGridCheck, …)
|
|
* that warrant their own parameterized test file.
|
|
*/
|
|
import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
|
import {
|
|
buildChecks,
|
|
computeDoctorReport,
|
|
type Check,
|
|
} from '../src/commands/doctor.ts';
|
|
|
|
let engine: PGLiteEngine;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({});
|
|
await engine.initSchema();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await engine.disconnect();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
await resetPgliteState(engine);
|
|
});
|
|
|
|
describe('computeDoctorReport — pure score aggregation', () => {
|
|
test('empty checks → healthy, score 100', () => {
|
|
const r = computeDoctorReport([]);
|
|
expect(r.schema_version).toBe(2);
|
|
expect(r.status).toBe('healthy');
|
|
expect(r.health_score).toBe(100);
|
|
expect(r.checks).toEqual([]);
|
|
});
|
|
|
|
test('all ok → healthy, score 100', () => {
|
|
const checks: Check[] = [
|
|
{ name: 'a', status: 'ok', message: '' },
|
|
{ name: 'b', status: 'ok', message: '' },
|
|
{ name: 'c', status: 'ok', message: '' },
|
|
];
|
|
const r = computeDoctorReport(checks);
|
|
expect(r.status).toBe('healthy');
|
|
expect(r.health_score).toBe(100);
|
|
});
|
|
|
|
test('one warn → warnings, -5 points', () => {
|
|
const checks: Check[] = [
|
|
{ name: 'a', status: 'ok', message: '' },
|
|
{ name: 'b', status: 'warn', message: '' },
|
|
];
|
|
const r = computeDoctorReport(checks);
|
|
expect(r.status).toBe('warnings');
|
|
expect(r.health_score).toBe(95);
|
|
});
|
|
|
|
test('one fail → unhealthy, -20 points', () => {
|
|
const r = computeDoctorReport([{ name: 'a', status: 'fail', message: '' }]);
|
|
expect(r.status).toBe('unhealthy');
|
|
expect(r.health_score).toBe(80);
|
|
});
|
|
|
|
test('3 fails → unhealthy, -60 points (audit-driver math)', () => {
|
|
const checks: Check[] = [
|
|
{ name: 'a', status: 'fail', message: '' },
|
|
{ name: 'b', status: 'fail', message: '' },
|
|
{ name: 'c', status: 'fail', message: '' },
|
|
];
|
|
const r = computeDoctorReport(checks);
|
|
expect(r.status).toBe('unhealthy');
|
|
expect(r.health_score).toBe(40);
|
|
});
|
|
|
|
test('mixed ok + warn + fail → unhealthy (fail dominates)', () => {
|
|
const r = computeDoctorReport([
|
|
{ name: 'a', status: 'ok', message: '' },
|
|
{ name: 'b', status: 'warn', message: '' },
|
|
{ name: 'c', status: 'fail', message: '' },
|
|
]);
|
|
// 1 fail (-20) + 1 warn (-5) = 75; fail status dominates ranking.
|
|
expect(r.status).toBe('unhealthy');
|
|
expect(r.health_score).toBe(75);
|
|
});
|
|
|
|
test('score is clamped at 0 (never negative)', () => {
|
|
const many: Check[] = Array.from({ length: 10 }, (_, i) => ({
|
|
name: `f${i}`,
|
|
status: 'fail' as const,
|
|
message: '',
|
|
}));
|
|
const r = computeDoctorReport(many);
|
|
expect(r.health_score).toBe(0);
|
|
expect(r.status).toBe('unhealthy');
|
|
});
|
|
});
|
|
|
|
describe('buildChecks — orchestrator against PGLite', () => {
|
|
test('returns a non-empty Check[] against a fresh brain', async () => {
|
|
const checks = await buildChecks(engine, []);
|
|
expect(Array.isArray(checks)).toBe(true);
|
|
expect(checks.length).toBeGreaterThan(10);
|
|
// Every check has the contracted shape.
|
|
for (const c of checks) {
|
|
expect(typeof c.name).toBe('string');
|
|
expect(['ok', 'warn', 'fail']).toContain(c.status);
|
|
expect(typeof c.message).toBe('string');
|
|
}
|
|
});
|
|
|
|
test('snapshot: load-bearing check names always run against a fresh brain', async () => {
|
|
// Behavior-preservation snapshot (D6 lock). Pinning a CURATED subset of
|
|
// load-bearing checks rather than the full list so this test stays stable
|
|
// when new checks land deliberately — but breaks loudly if a known
|
|
// load-bearing check accidentally drops out during a refactor.
|
|
//
|
|
// Deliberately tight set: only checks whose code path is unconditional
|
|
// given an engine + has no env / config dependencies that vary between
|
|
// test processes. Adding more sensitive checks here (e.g. ones that
|
|
// read process.env) caused cross-shard flakes under the parallel runner.
|
|
// Per-check leaf coverage is the TODO that targets the broader surface.
|
|
const checks = await buildChecks(engine, []);
|
|
const names = new Set(checks.map(c => c.name));
|
|
const loadBearing = [
|
|
'connection',
|
|
'schema_version',
|
|
'brain_score',
|
|
'sync_freshness',
|
|
'search_mode',
|
|
'eval_drift',
|
|
'reranker_health',
|
|
'embedding_width_consistency',
|
|
'autopilot_lock_scope',
|
|
];
|
|
// NOTE: sync_failures and slug_fallback_audit are deliberately NOT in
|
|
// the load-bearing set — they're only pushed when the corresponding
|
|
// JSONL file exists. Tests run on isolated tmpdir GBRAIN_HOMEs where
|
|
// those files may or may not exist depending on which sibling tests
|
|
// already wrote audit lines.
|
|
const missing = loadBearing.filter(n => !names.has(n));
|
|
expect(missing, `load-bearing checks missing from buildChecks result: ${missing.join(', ')}`).toEqual([]);
|
|
// Plus a minimum total count — drops below ~30 means something
|
|
// bigger went wrong than the snapshot can name.
|
|
expect(checks.length).toBeGreaterThan(30);
|
|
});
|
|
|
|
test('--fast skips DB-dependent checks; filesystem checks still run', async () => {
|
|
// Fast-mode bails out of the DB section entirely. When an engine is
|
|
// available, the early-return skips pushing a connection check (no
|
|
// probe happened); when engine is null AND --fast, a warn-status
|
|
// synthesized connection check is added. Filesystem checks above
|
|
// the DB phase always run.
|
|
const checks = await buildChecks(engine, ['--fast']);
|
|
const names = new Set(checks.map(c => c.name));
|
|
// DB-dependent checks should NOT be present.
|
|
expect(names.has('schema_version')).toBe(false);
|
|
expect(names.has('brain_score')).toBe(false);
|
|
expect(names.has('sync_freshness')).toBe(false);
|
|
// Filesystem checks above the DB phase still ran.
|
|
expect(names.has('resolver_health')).toBe(true);
|
|
|
|
// The null-engine + --fast path DOES synthesize a connection warn.
|
|
const fsOnlyChecks = await buildChecks(null, ['--fast'], 'env:DATABASE_URL');
|
|
const fsOnlyNames = new Set(fsOnlyChecks.map(c => c.name));
|
|
expect(fsOnlyNames.has('connection')).toBe(true);
|
|
const conn = fsOnlyChecks.find(c => c.name === 'connection')!;
|
|
expect(conn.status).toBe('warn');
|
|
expect(conn.message.toLowerCase()).toContain('fast');
|
|
});
|
|
|
|
test('--json arg does NOT alter the returned check list', async () => {
|
|
// --json is a wrapper-level concern (controls outputResults render mode);
|
|
// the buildChecks seam should return the same checks regardless.
|
|
const without = await buildChecks(engine, []);
|
|
const withJson = await buildChecks(engine, ['--json']);
|
|
expect(withJson.map(c => c.name)).toEqual(without.map(c => c.name));
|
|
});
|
|
|
|
test('returns partial check list when engine is null (no early process.exit)', async () => {
|
|
// Pre-v0.39 the no-engine path called outputResults + process.exit
|
|
// directly. Post-extract it returns the partial list so the wrapper
|
|
// decides exit code. This is the load-bearing assertion that proves
|
|
// the early-exit refactor preserved observable behavior.
|
|
const checks = await buildChecks(null, []);
|
|
expect(Array.isArray(checks)).toBe(true);
|
|
const connection = checks.find(c => c.name === 'connection');
|
|
expect(connection).toBeDefined();
|
|
expect(connection!.status).toBe('warn');
|
|
});
|
|
|
|
test('mixed-outcome render path: synthesized checks aggregate as expected', () => {
|
|
// The orchestrator's render path (outputResults in the wrapper) reads
|
|
// the same DoctorReport.status enum we compute here. Pin the
|
|
// ok+warn+fail aggregation so the wrapper's render of a real mixed
|
|
// brain state is reproducible.
|
|
const mixed: Check[] = [
|
|
{ name: 'resolver_health', status: 'ok', message: '50 skills' },
|
|
{ name: 'sync_failures', status: 'warn', message: '2 unacked' },
|
|
{ name: 'schema_version', status: 'fail', message: 'mid-upgrade' },
|
|
];
|
|
const r = computeDoctorReport(mixed);
|
|
expect(r.status).toBe('unhealthy');
|
|
expect(r.health_score).toBe(75);
|
|
expect(r.checks).toHaveLength(3);
|
|
expect(r.checks.map(c => c.status)).toEqual(['ok', 'warn', 'fail']);
|
|
});
|
|
});
|