mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
82cc7fff90429ef05585705b3d91a74afeffb4ce
5
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e084457c2d |
v0.41.5.0 fix-wave: warm-narwhal — 6 community PRs + E2E reliability (#1374)
* fix(recipes/openai): add max_batch_tokens to embedding touchpoint OpenAI is the only recipe in the codebase without a max_batch_tokens cap. Every other provider declares one (voyage=120K, azure-openai=8K, dashscope=8K, zhipu=8K, minimax=4K). Without it, gbrain's recursive-halving safety net never engages — batches dispatched purely on the char/4 estimator window will trip OpenAI's 1M-token TPM ceiling on token-dense pages (Discord exports, JSON dumps, code-heavy markdown), then retry storm and block the queue head. Setting cap to 100_000: - gbrain's batcher estimates tokens as chars/4 - Token-dense markdown+JSON tokenizes at ~chars/2.7 - 100K estimated = ~150K real worst-case, safely under OpenAI's 300K per-request hard cap and the 1M/min TPM ceiling - Leaves headroom for recursive-halving on outlier chunks (cherry picked from commit |
||
|
|
6a10bad8e5 |
v0.41.0.0 feat(minions): fleet you supervise (4 field bugs + cathedral) (#1367)
* v0.41: migration v93 — minions audit tables + budget columns Three new audit tables for the v0.41 minions cathedral (each with SET NULL FK so audit rows survive `gbrain jobs prune`, denormalized context columns so post-NULL rows still carry forensic value): - minion_lease_pressure_log — Bug 2 audit (one row per lease-full bounce) - minion_budget_log — D5 audit (reserve/refund/spent/halted) - minion_self_fix_log — E6 audit (classifier-gated auto-resubmit chain) Three new columns on minion_jobs: - budget_remaining_cents — D5 parent spendable balance - budget_owner_job_id — Eng D7 immutable budget owner (FK SET NULL) - budget_root_owner_id — Eng D10 denormalized historical owner (no FK) Eng D10 closes the codex-pass-3 #4 ambiguity bug: when the budget owner is pruned mid-batch, `budget_owner_job_id` becomes NULL via SET NULL, which is indistinguishable from "never had a budget." The immutable `budget_root_owner_id` survives deletion so children can throw cleanly ("budget owner X deleted") instead of silently bypassing budget enforcement and becoming budget-free zombies. Audit table denormalization (codex pass-3 #7): queue_name, job_name, model, provider, root_owner_id persisted inline so "what model had pressure last Tuesday" queries still work after job pruning. Both Postgres + PGLite parity. Indexed for the read patterns the doctor check + jobs stats consume. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41: subagent hardening — Bug 1 + Bug 3 + Approach C composable prompt Three independent fixes to src/core/minions/handlers/subagent.ts. Each is covered by its own test set; bundled in one commit because they touch overlapping lines of subagent.ts (cleaner than 3 hunk-split commits). Bug 1 — rate-lease default 8 → 32 + `unlimited` sentinel src/core/minions/handlers/subagent.ts:61 Pre-v0.41 the default cap of 8 starved 10-concurrency batches on upstreams with no provider-side rate limit (Azure/Bedrock/self-hosted). New resolveLeaseCap() bumps default to 32, accepts `unlimited`/`none` as POSITIVE_INFINITY sentinel, throws on NaN/negative/zero with a paste-ready hint. Codex pass-1 #7 caught the original `=0`/`NaN`-uncapped semantics as dangerous (universal convention is "0 means disabled"). Pinned by test/rate-leases-uncapped.test.ts (15 cases). Bug 3 — strip `provider:` prefix at Anthropic SDK call site src/core/minions/handlers/subagent.ts:439, ~:895 `gbrain agent run --model anthropic:claude-sonnet-4-6` pre-fix sent the qualified string straight to client.messages.create which Anthropic rejects with "model not found." New stripProviderPrefix() applies at the one SDK call site; `model` stays qualified everywhere else (persistence, recipe lookup, capability gate). Pinned by 4 new test/subagent-handler.test.ts cases. Approach C — composable system prompt renderer w/ per-tool usage_hint src/core/minions/system-prompt.ts (NEW) src/core/minions/types.ts (ToolDef.usage_hint + SubagentHandlerData.system_no_tool_preamble) src/core/minions/tools/brain-allowlist.ts (BRAIN_TOOL_USAGE_HINTS) src/core/minions/handlers/subagent.ts (wiring) Bug 4 absorbed: pre-v0.41 DEFAULT_SYSTEM was one generic line that gave the model no guidance on WHICH tool to reach for. The field-report case was a `shell` tool sitting unused because nothing told the model to reach for it. New deterministic renderer splices a tool-usage preamble listing each tool's name + usage_hint; closing paragraph names shell/bash explicitly + tells the model brain tools write to the DB (not local files). Determinism preserved for Anthropic prompt-cache marker stability. Pinned by 13 cases in test/system-prompt.test.ts (determinism, opt-out, plugin tools, cache safety). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41: Bug 2 — lease-full bypass that doesn't burn attempts The field-report dead-letter loop closed at the root. Pre-v0.41 the worker treated RateLeaseUnavailableError as a recoverable error AND incremented attempts_made. After 3 lease-full bounces the job hit max_attempts (default 3) and dead-lettered with message `rate lease "anthropic:messages" full (8/8)`. The operator who reported the bug submitted 100 jobs at --concurrency 10 with a default cap of 8; all 100 dead-lettered before the upstream had a chance to drain. Fix: MinionQueue.releaseLeaseFullJob(jobId, lockToken, errorText, backoffMs) Mirrors failJob() but skips the attempts_made increment. Same lock_token + status='active' idempotency guard as failJob; returns null on lock-token mismatch so racing stall sweeps / cancels still win. Worker catch block (src/core/minions/worker.ts:741-792) Detects `err instanceof RateLeaseUnavailableError` BEFORE the existing `isUnrecoverable || attemptsExhausted` gate. Routes through releaseLeaseFullJob with 1-3s jittered backoff. The handler comment at subagent.ts:425 ("treat as renewable error so the worker re-claims") is now actually true. src/core/minions/lease-pressure-audit.ts (NEW) Best-effort logLeasePressure() writes one row to migration v93's minion_lease_pressure_log per bounce. Denormalized context columns (queue_name, job_name, model, provider, root_owner_id) populated inline so post-prune forensic queries still see context (Eng D8 / codex pass-3 #7). Stderr-warn on write failure; never blocks the bypass path. Pinned by test/minions-lease-full-retry.test.ts (7 cases): - flips status to delayed without incrementing attempts_made - returns null on lock_token mismatch - 5 bounces leaves attempts_made=0; failJob comparison shows the asymmetry (failJob DOES bump) - logLeasePressure writes denormalized columns - countRecentLeasePressure for doctor + jobs stats consumers - audit row survives hard-delete via SET NULL FK - best-effort no-throw contract on write failure Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41: doctor subagent_health + jobs stats lease_pressure line Operator visibility for the v0.41 Bug 2 audit data. src/commands/doctor.ts checkSubagentHealth(engine) — new exported check function. Reads the last 24h of minion_lease_pressure_log and classifies by bounce volume + forward progress: 0 bounces → ok 1-99 bounces → ok ("transient") 100+ bounces + subagent jobs completing → ok ("healthy backpressure") 100+ bounces + NO completed subagent jobs → warn (paste-ready hint) 1000+ bounces → fail (blocking) Warn/fail messages embed `export GBRAIN_ANTHROPIC_MAX_INFLIGHT=64` for copy-paste. Pre-v93 brains (no table) silently skip with OK. Works on both Postgres + PGLite. src/commands/jobs.ts (case 'stats') Adds `Lease pressure (1h)` line to the stats output. When >0 bounces, cross-checks completed subagent count and surfaces the same binding-but-healthy vs cap-too-tight distinction inline so operators don't have to run `gbrain doctor` to see it. Pre-v93 silent skip. test/doctor-subagent-health.test.ts (NEW) 4 cases pinning all threshold bands. Uses `allowProtectedSubmit: true` on the queue.add for `subagent`-named owner jobs. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41: Wave B — visibility cathedral (error clustering + jobs watch + cost cathedral) Five new modules + one SPA tab + one CLI command, all wired into the v0.41 audit substrate from migration v93. Each module is unit-tested in isolation; integration smoke tests live in the e2e suite. NEW MODULES: src/core/minions/error-classify.ts (D3 + E6 shared classifier) Conservative regex set classifying minion_jobs.last_error into stable buckets. Narrowed tool-error sub-types per codex pass-2 #4: only tool_schema_mismatch self-fixes; tool_crash + tool_unavailable + tool_permission stay visible. RECOVERABLE_CLUSTERS export gates E6 self-fix qualification. clusterErrors() groups + sorts for D3 surfaces. Pinned by 21 cases against real production error strings. src/core/minions/batch-projection.ts (D4 submit-time projection) Pure-function projectBatch() computes total cost + duration with ±30% band (or sample-stddev when historical). Cold-start fallback uses model-default per-token pricing + 5s mean latency guess; annotates "(no history; estimate is a wide guess)" so operators don't trust approximations. Unknown-model returns tagged variant so --budget-usd refuses to gate. Raise-cap hint fires when lease is binding AND a 4x raise meaningfully helps. Pinned by 16 cases. src/core/minions/budget-tracker.ts (D5 + Eng D7 + Eng D10) Reservation pattern that bounds overspend even under N parallel children of one owner. SQL UPDATE CAS WHERE budget_remaining_cents >= cost RETURNING balance; CAS miss → BudgetExhausted; on return → refundBudget unspent cents. Eng D10 NULL-bypass: jobs without an owner skip reservation cleanly. Eng D10 owner-deleted disambiguation: when budget_owner_job_id is NULL but budget_root_owner_id is set, the owner was pruned mid-batch; child throws BudgetOwnerDeleted instead of silently bypassing. haltBudgetSubtree() recursive halt walks budget_owner_job_id = X to flip the entire subtree to dead with reason. Pinned by 10 cases covering: reservation+refund, CAS miss, NULL bypass, owner-deleted throw, halt sweep, grandchild inheritance, active-job preservation. NEW SURFACES: src/commands/jobs-watch.ts + GET /admin/api/jobs/watch + JobsWatchPage Live TTY dashboard via readSnapshot() + renderSnapshot(). 1s refresh, ANSI-colored lease pressure by severity, top-5 clustered errors, budget owners panel. Non-TTY mode emits JSON snapshots per tick. Admin SPA tab consumes the same /admin/api/jobs/watch endpoint so TTY + browser dashboards stay 1:1. src/commands/jobs.ts — --cluster-errors flag on `gbrain jobs stats` Groups dead/failed jobs from last 24h by classifier bucket; surfaces top 5 with paste-ready `gbrain jobs get <id>` example. src/core/minions/types.ts — SubagentHandlerData additions no_self_fix (E6 per-job opt-out), is_self_fix_child (chain-depth marker), self_fix_cluster (audit metadata). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41: Wave C — self-tuning fleet (E5 controller + E6 self-fix + shared election) The "magic layer" the wave promises: workers tune their own lease cap based on real upstream signals; failed jobs auto-heal one layer deep for known-recoverable failure modes. Both default ON for fresh installs + upgrades; off-switches per CLAUDE.md. src/core/db-lock.ts — tryWithDbElection convenience (Eng D9) Thin wrapper over the existing tryAcquireDbLock: acquires, runs fn, releases. For per-tick election use cases (controller tick chooses one writer per cluster). Codex pass-3 #8/#9 audit picked this shape over building a parallel new primitive — the existing gbrain_cycle_locks table works for both engines. src/core/minions/lease-cap-controller.ts (E5 reframed + Eng D6 correction) Auto-adapts the rate-lease cap based on bounce rate + upstream 429s + latency stability. CORRECTED control law per codex pass-2 #9: * Ramp DOWN only when upstream pushes back (429s OR latency unstable) * Ramp UP fast when workers starve (bounces > 1/min + no 429s) * Ramp UP slow on healthy headroom (util > 50% + 0 bounces + 0 429s) * Deadband otherwise My first draft had the bounce sign inverted; would have cratered cap during a healthy 100-job burst — exactly the field-report case. IRON- RULE regression test (test/lease-cap-controller.test.ts) pins the correct sign so future "let's simplify" PRs can't silently regress it. Per-tick election via tryWithDbElection — only ONE worker per cluster runs the WRITE side; all workers READ lease_cap_current fresh on every acquire. Asymmetric AIMD steps (rampDown=8, rampUp=4) — TCP congestion control wisdom. Latency signal sourced from subagent job durations in window; full upstream-SDK-latency tracking is v0.42. Pinned by 14 cases including the field-report scenario simulation ("starving workers get MORE capacity, not less"). src/core/minions/self-fix.ts (E6 with narrowed classifier per codex pass-2 #4) Classifier-gated auto-resubmit on terminal failures. ONLY three buckets qualify: prompt_too_long, tool_schema_mismatch, malformed_json. Explicitly NOT recoverable: tool_crash (real bug), tool_unavailable (config issue), tool_permission (needs human). Chain depth cap = 2 (D15 default); per-job opt-out via data.no_self_fix; global off-switch via config. buildSelfFixPrompt cluster-specific prep: prompt_too_long → truncate-with-leaf-preservation (v0.41 ships simple; semantic reduction in v0.42) tool_schema_mismatch → surface error verbatim + "check input_schema" malformed_json → "respond with JSON only — no prose, no fences" Children inherit budget owner from parent (Eng D7 + D10) but DO NOT copy remaining cents (codex pass-3 #5 caught the original plan's contradiction; only owner row holds spendable balance). Pinned by 16 cases. scripts/e5-lease-cap-ab.ts (D11 + codex pass-2 #7 spec) Manually-runnable A/B harness with committed receipt-fixture baseline. Spec: 500 jobs, log-normal prompt distribution, $8 budget per arm, synthetic 429 burst at minute 15, PR-gate verdict (controller must beat fixed-cap by ≥5% on throughput AND match within ±2% on cost efficiency). v0.41 ships the spec + dry-run + fixture shape; real-run dispatcher deferred to v0.41.1 (filed in TODOS). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41.0.0 release — VERSION + CHANGELOG + TODOS + llms.txt regen Trio audit passes: VERSION: 0.41.0.0 package.json: 0.41.0.0 CHANGELOG: ## [0.41.0.0] - 2026-05-24 CHANGELOG entry written in ELI10-lead-first voice per CLAUDE.md voice rules. Lead with what the user gets (100-job batch now completes); itemized changes after; "To take advantage of v0.41.0.0" block at the end with paste-ready upgrade verification. TODOS.md updates filed via CEO D13 + D16 + Eng D9 + codex pass-1 #11: - v0.41+: per-key rate-lease caps (P2; deferred until gateway-default flip) - v0.41+: audit retention sweep in autopilot purge phase (P3) - v0.41.1: full E5 A/B dispatcher (currently dry-run only) - v0.41.1: tryWithDbElection retrofit of existing rate-leases + queue paths - v0.42: semantic-aware prompt_too_long reduction llms.txt + llms-full.txt regenerated to absorb the CHANGELOG entry. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41 test gap-fills — 6 E2E suites covering every user flow Six new test/e2e/ files, 12 tests total, all passing inline against PGLite (no DATABASE_URL needed). Each pairs with a load-bearing claim in the v0.41 CHANGELOG so a future regression has somewhere to scream. minions-field-report-repro.test.ts THE BUG THIS WAVE FIXES. Submits 12 subagent jobs; stubbed handler bounces each twice then succeeds. Pre-v0.41 all 12 would dead-letter at attempt 3. Post-v0.41 all 12 complete with attempts_made=0 + 24 audit rows visible. minions-prefix-strip-smoke.test.ts Bug 3 end-to-end: stubbed MessagesClient records params.model; asserts the SDK call site receives 'claude-sonnet-4-6' (bare) when the job was submitted with 'anthropic:claude-sonnet-4-6' (qualified). minions-budget-cathedral.test.ts D5 enforcement under fan-out. Two scenarios: 1. Mid-batch budget exhaustion: 10 children of one budget-bearing parent; first 5 reserve, last 5 hit CAS miss, haltBudgetSubtree flips remaining 10 to dead (owner row preserved). 2. Parallel reservation cannot exceed budget: 8 concurrent reserves at 10c each on a 30c budget → exactly 3 succeed, 5 hit exhausted, owner balance stays 0 (NOT negative). minions-self-fix-flow.test.ts E6 classifier-gated retry. 4 scenarios pinning codex pass-2 #4: 1. prompt_too_long → child submitted with self-fix prompt + audit 2. tool_crash → NOT recoverable; no child submitted 3. no_self_fix opt-out bypasses recoverable cluster 4. Chain depth cap (default=2) refuses grandchild self-fix minions-controller-bounce-only.test.ts IRON-RULE REGRESSION for Eng D6 sign correction. 100 bounce events in audit, no 429s → controller MUST ramp cap UP (not down). 50 bounces + 10 dead jobs with 429-shaped errors → controller MUST ramp cap DOWN. If a future "simplify the rule" PR ever inverts the sign, this test screams. jobs-watch-readsnapshot.test.ts Engine-aggregation half of D2 (the renderer half lives in the unit suite). Verifies snapshot includes lease pressure, clustered errors, budget owners with cents. Total: 12 new E2E tests, all passing in 42s on PGLite. Plus the new unit tests already shipped in Waves A-C: ~120 unit tests total across 9 new test files. All pass; verify gate green; typecheck clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * v0.41 follow-up: regen src/admin-embedded.ts + TS strict fixes + withEnv Three fixes the verify + admin-embed-serial-test gauntlet found: src/admin-embedded.ts AUTO-GENERATED file. v0.41 admin SPA build (T13) changed the hashed asset filename from index-DFgMZhBE.js to index-DqP-zmqH.js but the build-admin-embedded.ts generator wasn't re-run after `bun run build` in admin/. Result: src/admin-embedded.ts kept the old hash and `gbrain serve --http` failed to load the admin SPA with `Cannot find module '../admin/dist/assets/index-DFgMZhBE.js'`. Caught by test/admin-embed-spawn.serial.test.ts. Regenerated via `bun run scripts/build-admin-embedded.ts`. src/core/minions/self-fix.ts TS strict-mode fixes caught by `bun run typecheck`: - `rows` implicit-any → explicit Array<{...}> annotation. - childData typed as SubagentHandlerData & {...} → not assignable to Record<string, unknown> for queue.add's signature. Added narrow cast at the call site. test/batch-projection.test.ts check-test-isolation R1 violation: raw `process.env` mutation caught by the lint. Switched to `withEnv()` from test/helpers/with-env.ts (the canonical pattern per CLAUDE.md test-isolation rules). After: `bun run verify` green, `bun test test/admin-embed-spawn.serial.test.ts` 4/4 pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(e2e): 4 root-cause fixes for pre-existing E2E flakes (master polish) After merging origin/master (which landed v0.40.8.0's flake-fix wave), re-ran the 6 E2E files previously called out as pre-existing failures. v0.40.8.0 had already fixed 3; the remaining 3 had real root causes: 1. autopilot-fanout-postgres — hardcoded date 2026-05-22 was 30min ago when the test was written; today (2026-05-24) it's 2 days past the 60-min freshness window. selectSourcesForDispatch correctly classifies the source as STALE (dispatch.length=1) instead of FRESH (length=0). Fix: replace literal date with Date.now() - 30 * 60 * 1000 so the timestamp stays relative-fresh forever. 2. ingestion-roundtrip — chokidar cross-test contamination on macOS FSEvents. Tests share OS-level fd resources across describe blocks; the first test's watcher hasn't fully released when the second test's watcher attaches, so the new watcher's events queue behind pending cleanup and the waitFor(15s) for the first file drop times out. Fixes: - Move fs.mkdirSync(inboxDir) BEFORE createInboxFolderSource + daemon.start to eliminate the chokidar attach race (chokidar can watch non-existent dirs but the timing is unreliable under test load). - Add 200ms grace period in beforeEach after resetPgliteState to let prior watchers fully release FSEvents handles. - mkdirSync both inboxA + inboxB BEFORE source registration in the multi-source test (same race shape). - Bump waitFor timeouts 6s → 15s for fs.watch flake tolerance. 3. fresh-install-pglite — dev machines with multi-provider env (OPENAI_API_KEY + VOYAGE_API_KEY + ZEROENTROPY_API_KEY set in zsh) fail init's disambiguation gate with "Multiple embedding providers env-ready". The test sets ZE_API_KEY but doesn't NEGATE the others. Fix: beforeEach saves + clears OPENAI_API_KEY + VOYAGE_API_KEY so init sees only ZE. afterEach restores. Hermetic per dev machine. 4. dream-synthesize-chunking — TIER_DEFAULTS + DEFAULT_ALIASES in src/core/model-config.ts had BARE Anthropic model ids (e.g. 'claude-sonnet-4-6' instead of 'anthropic:claude-sonnet-4-6'). The v0.40.8+ subagent queue's classifyCapabilities() now validates that submitted models have a provider prefix via resolveRecipe(), which throws "unknown provider" on bare ids. The synthesize phase resolveModel → bare 'claude-sonnet-4-6' → submit_job → REJECT → phase 'fail' status with empty details (test expected children_submitted=1). Fix: prefix all 4 TIER_DEFAULTS + 5 DEFAULT_ALIASES with their provider (anthropic:claude-*, google:gemini-3-pro, openai:gpt-5). Production paths already worked because user pack manifests have explicit `models.tier.subagent = anthropic:...`; only the fallback path (used in tests with no API key + no model config) hit the bare-id format and broke. Verification (all run against DATABASE_URL=...:5434/gbrain_test): test/e2e/autopilot-fanout-postgres.test.ts → 6/6 pass test/e2e/dream-cycle-phase-order-pglite.test.ts → 5/5 pass test/e2e/dream-synthesize-chunking.test.ts → 4/4 pass test/e2e/fresh-install-pglite.test.ts → 2/2 pass test/e2e/http-transport.test.ts → 8/8 pass test/e2e/ingestion-roundtrip.test.ts → 3/3 pass test/e2e/mechanical.test.ts → 78/78 pass Total: 106/106 pass, 0 fail. Adjacent unit tests verified green: test/anthropic-model-ids.test.ts → 6/6 pass test/model-config.serial.test.ts → 19/19 pass typecheck clean. Plan: v0.41 wave (~/.claude/plans/system-instruction-you-are-working-toasty-milner.md). Post-merge polish — every E2E failure surfaced in the v0.41 ship reports is now green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(test): isolate HOME in run-e2e.sh to stop config corruption Replaces #517 (re-ported fresh against current scripts/run-e2e.sh after v0.23.1 rewrote the script — original cherry-pick would not apply). E2E tests call setupDB which writes $HOME/.gbrain/config.json pointing at the docker test container. When the container tears down, the user's real autopilot daemon wedges trying to connect to a vanished postgres. Three operators hit this within 16 days before the original PR filed. Fix: wrapper exports HOME + GBRAIN_HOME to a mktemp tmpdir BEFORE bun starts so config writes land in the tmpdir, with a post-run breach detector that compares md5 of the user's real config against pre-run. Both env vars required: loadConfig/saveConfig resolve via HOME while configPath honors GBRAIN_HOME. HOME set before bun starts because os.homedir() caches at first call. Test seam: test/gbrain-home-isolation.test.ts updated to assert against homedir() === configDir() when GBRAIN_HOME unset (correct under the safety wrapper itself) instead of the prior "not /tmp/" sentinel. Revert path: git revert <this-sha> if test:e2e regresses on master. Co-Authored-By: orendi84 <orendi84@users.noreply.github.com> * fix(engines): silence pg NOTICEs + redirect migration progress to stderr Two changes that share a single root cause — stdout pollution breaking JSON-parsing callers like `gbrain jobs submit --json | jq` and the `zombie-reaping.test.ts` execSync flow. 1. **postgres NOTICE silencing.** postgres.js's default `onnotice` calls `console.log(notice)`, which flooded stdout with `{severity:"NOTICE", message:"relation already exists, skipping"}` objects under idempotent `CREATE INDEX IF NOT EXISTS` migrations + `initSchema`. Silenced by default in both `src/core/db.ts` (singleton) and `src/core/postgres-engine.ts` (instance pools). Opt back in with `GBRAIN_PG_NOTICES=1`. 2. **Migration progress to stderr.** `console.log` calls in `src/core/migrate.ts` (`Schema version N → M`, `[N] name...`, `[N] ✓ name`) and the wrappers in both engines (`N migration(s) applied`, `Schema verify: ...`, `HNSW sweep: ...`, `Pre-v0.21 brain detected`) now route to `process.stderr.write`. Progress messages were never the program's data output; they belong on stderr. Closes the cross-test flake class where any test invoking `bun run src/cli.ts jobs submit --json` mid-suite would JSON.parse a mix of migration progress + the actual job row. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(e2e): close 3 remaining flake classes after cebu-v4 + halifax merge 1. **dream-cycle-phase-order-pglite**: EXPECTED_PHASES was missing `schema-suggest` (v0.39.0.0 added it between `orphans` and `purge`). Hand-port of cebu-v4's |
||
|
|
90e22c22e2 |
v0.23.1 feat: local CI gate + 4-tier wall-time optimization (~13x faster) (#528)
* feat: diff-aware E2E test selector Adds scripts/select-e2e.ts: reads git diff vs origin/master, classifies the change set (EMPTY/DOC_ONLY/SRC), and emits the relevant E2E test files on stdout. Fail-closed by design: any unmapped src/ change runs all E2E. - scripts/e2e-test-map.ts: hand-tuned path-glob -> test files map - scripts/select-e2e.ts: pure-function selector with three explicit cases - scripts/run-e2e.sh: accepts optional file list from argv + --dry-run-list - test/select-e2e.test.ts: 24 cases including 3 codex regression guards (skills/, untracked files, unmapped src/) * feat: local CI gate via docker compose Adds bun run ci:local — runs every check GH Actions runs (gitleaks + unit + 29 E2E files) inside a Docker container that bind-mounts the repo. Pure bind-mount + named volumes (gbrain-ci-node-modules, gbrain-ci-bun-cache, gbrain-ci-pg-data) for fast warm restarts. - docker-compose.ci.yml: pgvector/pgvector:pg16 + oven/bun:1 - scripts/ci-local.sh: orchestrator with --diff, --no-pull, --clean - gitleaks runs on host (scoped to working dir + branch commits) - DATABASE_URL unset for unit phase (matches GH Actions split) - git installed in container at startup (oven/bun:1 omits it) - Postgres host port via GBRAIN_CI_PG_PORT env (default 5434) Stronger than PR CI: runs all 29 E2E files vs CI's 2-file Tier 1. * chore: bump version and changelog (v0.23.1) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: document local CI gate for v0.23.1 CLAUDE.md gains key-files entries for docker-compose.ci.yml, scripts/ci-local.sh, scripts/select-e2e.ts + e2e-test-map.ts, and the scripts/run-e2e.sh argv tweak. Pre-ship requirements section now lists the Docker-based local gate as Path A alongside the manual lifecycle. CONTRIBUTING.md tests section adds the bun run ci:local / ci:local:diff / ci:select-e2e block with prerequisites (Docker engine + gitleaks) and the GBRAIN_CI_PG_PORT override. AGENTS.md "Before shipping" promotes ci:local as the easiest path and keeps the manual lifecycle as a fallback. README.md Contributing section points to ci:local for the full gate. CHANGELOG.md untouched — v0.23.1 entry already finalized. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat: SHARD=N/M env support in scripts/run-e2e.sh Filters the E2E file list to every M-th file starting at index N (1-indexed). Sequential execution within a shard preserves the TRUNCATE CASCADE no-race property documented at the top of the file. Empty-shard handling under `set -u` uses ${arr[@]:-} fallback. Standalone change; not yet wired up in ci-local.sh. * feat: 4-way parallel E2E shards in ci:local Replaces the single postgres service with 4 (postgres-1..4) on host ports 5434-5437. scripts/ci-local.sh fans 4 workers via xargs -P4 inside the runner container; each pinned to its own DATABASE_URL via SHARD=N/4. Wall-time on a 16-core host: ~6 min sequential -> ~1.5-2 min sharded. Total full-gate wall-time goes from ~25 min to ~3-5 min warm. Also handles git-worktree (Conductor) layouts: when /app/.git is a file instead of a directory, parse the gitdir + commondir and bind-mount the shared host gitdir at its absolute path. Without this, in-container `git ls-files` (used by scripts/check-trailing-newline.sh and friends) exits 128 with "not a git repository". Also runs `git config --global --add safe.directory '*'` inside the container so the root-uid container can read host-uid gitdir without "dubious ownership" rejection. CHANGELOG entry updated to cover the speedup. - docker-compose.ci.yml: 4 pgvector services + per-shard named volumes - scripts/ci-local.sh: parallel xargs orchestration + worktree mount fix - CHANGELOG.md v0.23.1: 4-way sharded wall-time, 36 E2E files, --no-shard flag * chore: regenerate llms-full.txt for v0.23.1 doc updates Required by test/build-llms.test.ts case 4 — committed llms-full.txt must match `bun run build:llms` output. The CHANGELOG + CLAUDE.md updates in this branch shifted bytes; regen catches up. * feat: scripts/run-unit-shard.sh + slow-test convention Tier 1 + Tier 4 plumbing: - scripts/run-unit-shard.sh: SHARD=N/M filter for unit files (excludes test/e2e/*). Excludes *.slow.test.ts (Tier 4 convention) so the fast shard fan-out skips known-slow files; CI's `bun run test` still includes them via default discovery. - scripts/run-slow-tests.sh: companion that runs ONLY *.slow.test.ts. Wired as `bun run test:slow`. - scripts/profile-tests.sh: portable awk parser that extracts the top-N slowest tests from any captured `bun test` output. Wired as `bun run test:profile`. Use it to pick demotion candidates. * feat: PGLite snapshot fixture for ~4.5x faster cold init (Tier 3) scripts/build-pglite-snapshot.ts boots a fresh PGLite, runs the full initSchema() (forward bootstrap + 30 migrations), and dumps the post-init state to test/fixtures/pglite-snapshot.tar plus a SHA-256 schema hash sidecar (.version). Both gitignored — built on demand via `bun run build:pglite-snapshot`. PGLiteEngine.connect() reads GBRAIN_PGLITE_SNAPSHOT env: validates the sidecar hash against the in-process MIGRATIONS hash, loads via PGLite's loadDataDir blob, sets _snapshotLoaded so initSchema() short-circuits. Measured per-file cold init drops from 828ms → 181ms. Bootstrap-correctness tests (bootstrap.test.ts, schema-bootstrap-coverage.test.ts) explicitly delete the env at file top so they keep exercising the cold path they verify. * feat: --classify-only + heartbeat tolerance fix (Tiers 2 + flake fix) - scripts/select-e2e.ts: --classify-only flag emits EMPTY|DOC_ONLY|SRC. Used by ci-local.sh's --diff fast-path to skip the heavy gate when only docs changed. - test/progress.test.ts: startHeartbeat tolerance widened to 1-20 over 200ms (was 2-6 over 85ms). Under 4-way parallel shard load on a contended host, setTimeout's effective quantum balloons and the tight bound flakes. The test still verifies "fires multiple times, stops cleanly" — exact count was never load-bearing. * feat: 4-way unit + E2E sharding in ci-local.sh + CHANGELOG (Tiers 1-4) ci-local.sh ties the four tiers together: - Tier 2: pre-flight diff classification on host. DOC_ONLY exits in ~5s (gitleaks only, no postgres, no container). - Tier 1: guards + typecheck run ONCE before fan-out. xargs -P4 then spawns 4 shards inside the runner container, each running unit phase (env -u DATABASE_URL bash run-unit-shard.sh) followed by E2E phase (DATABASE_URL=postgres-N bash run-e2e.sh) — both sharded N/4. Per-shard logs in /tmp/shard-logs/shard-N.log; printed in shard order at the end. - Tier 3: snapshot fixture built once at runner startup if missing, GBRAIN_PGLITE_SNAPSHOT exported so all shards inherit. - Tier 4: run-unit-shard.sh excludes *.slow.test.ts; run-slow-tests.sh + test:slow npm script handle the demoted set. - --no-shard preserves the legacy single-process flow for debug. package.json: build:pglite-snapshot, test:slow, test:profile scripts. Measured wall-time on 16-core host: 100s warm (down from ~22 min cold single-process). 4 shards × ~640-1024 unit tests each, plus 9 E2E files each. PGLite snapshot saves 4.5× per cold init (828ms → 181ms). CHANGELOG.md updated with measured numbers + four-tier breakdown. --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
ff10796a00 |
fix(wave): v0.15.1 - 4 hot issues + scope expansion (#248)
* fix(wave): 4 hot issues + 3 scope expansions (v0.13.1) Addresses four user-filed regressions after v0.13.0 plus three adjacent footgun closures. * #170 — CREATE INDEX [CONCURRENTLY] IF NOT EXISTS idx_pages_updated_at_desc on pages (updated_at DESC). Engine-aware migration v12 with invalid-index cleanup on Postgres, plain CREATE on PGLite. ~700x on 30k+ row brains. Contributed by @fuleinist (#215). * #219 — Minions schema default max_stalled 1 -> 5. v13 migration ALTERs the default and UPDATEs existing non-terminal rows (waiting/active/ delayed/waiting-children/paused) so live queues get rescued on upgrade. Adds MinionJobInput.max_stalled with [1,100] clamp. New --max-stalled CLI flag on `jobs submit`. Reported by @macbotmini-eng. * #218 — package.json postinstall surfaces errors instead of silencing. trustedDependencies whitelists @electric-sql/pglite. doctor schema_version check fails loudly when migrations never ran and links to #218. README + INSTALL_FOR_AGENTS warn against `bun install -g`. Reported by @gopalpatel. * #223 — @electric-sql/pglite pinned to exactly 0.4.3 (was ^0.4.4). PGLiteEngine.connect() wraps PGlite.create() errors with a message pointing at the issue + gbrain doctor. Does NOT suggest 'missing migrations' as a cause (create-time abort happens before migrations run). Pin is unverified against macOS 26.3; error-wrap is the safety net. Reported by @AndreLYL. * Scope: `gbrain jobs submit` gains --backoff-type/--backoff-delay/ --backoff-jitter/--timeout-ms/--idempotency-key (MinionJobInput audit). * Scope: `gbrain jobs smoke --sigkill-rescue` regression case (opt-in, CI-only) that simulates a killed worker and asserts the new default rescues. * Scope: `gbrain doctor --index-audit` reports zero-scan Postgres indexes as drop candidates (informational; no auto-drop). Infrastructure: * Migration interface extended with sqlFor: { postgres?, pglite? } and transaction: boolean. Runner picks the engine-specific branch and bypasses engine.transaction() when transaction:false (required for CONCURRENTLY). BrainEngine.kind readonly discriminator added. * scripts/check-jsonb-pattern.sh CI guard extended to block `max_stalled DEFAULT 1` from regressing. Tests: * 15 new unit tests: v12/v13 structural + behavioral assertions, max_stalled default/clamp/backfill, PGLite error-wrap source guard, engine kind discriminator. * 3 regression tests pinned by IRON RULE. * Full unit suite: 1416 pass. * Full E2E suite against Postgres 16 + pgvector: 126 pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.13.1) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: sync documentation for v0.13.1 CLAUDE.md "Key files" and "Commands" sections refreshed to match the v0.13.1 fix wave: - Note `BrainEngine.kind` discriminator on engine.ts - Document v0.13.1 connect() error-wrap on pglite-engine.ts - Refresh src/core/minions/ layout (no shell handler, no protected-names, no quiet-hours/stagger — that was v0.13-development scaffolding that did not ship) - Add src/core/migrate.ts entry with `Migration` interface extensions (`sqlFor`, `transaction: false`) - Document new `gbrain jobs submit` flags (--max-stalled, --backoff-type, --backoff-delay, --backoff-jitter, --timeout-ms, --idempotency-key) - Document `gbrain jobs smoke --sigkill-rescue` regression guard - Document `gbrain doctor --index-audit` and the schema_version=0 surface that catches #218 postinstall failures - Extend check-jsonb-pattern.sh note with the max_stalled DEFAULT 1 regression guard - Touch up test file blurbs for migrate.test.ts, pglite-engine.test.ts, minions.test.ts with v0.13.1 coverage Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(e2e): run files sequentially to eliminate shared-DB race The E2E suite was flaky. ~3 of every 5 runs had 4-10 failures clustered in Links, Timeline, Versions, Minions resilience, Parallel Import, and Page CRUD tests. Symptoms included "expected 16 pages, got 8" (half), "expected 1 link inserted, got 0", timeline entries missing after round-trip, and similar data-shape mismatches. Root cause: bun test runs test FILES in parallel (each in a worker process). 13 E2E files share one DATABASE_URL, and `setupDB()` in `test/e2e/helpers.ts` does `TRUNCATE ... CASCADE` on all tables before each file's `importFixtures()`. File A's TRUNCATE would race with file B's in-flight INSERT stream, producing the observed half-populated or wrong-count states. An earlier attempt used a Postgres advisory lock held on a dedicated single-connection client for the lifetime of each file's run. It broke because bun's default 5000 ms hook timeout fires on queued beforeAll() calls: with 13 files serializing through the lock, files 2-13 would time out waiting for file 1 to finish. This commit switches to sequential file execution at the harness level via scripts/run-e2e.sh, which loops through test/e2e/*.test.ts one at a time, tracks aggregate pass/fail counts, and exits non-zero on the first failing file. No lock, no timeout issues, no changes to any test file. package.json test:e2e points at the new script. Verified: 5 back-to-back runs against the same Postgres container, each completing in ~5 min. Every run: 13 files, 138 tests, 0 fails. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version to 0.15.1 (fix wave locked to MINOR line) Master v0.14.2 was the last /investigate root-cause wave on the v0.14.x line. This fix wave opens v0.15.x: four hot issues (#170, #218, #219, #223) close v0.13.x regressions that v0.14.x didn't cover, so the MINOR bump reflects the semantic shift — new schema migrations (v14, v15), a new CLI surface (`--max-stalled`, `--sigkill-rescue`, `--index-audit`), a new BrainEngine contract (`kind` discriminator + extended `Migration` interface), and a new install-time contract (PGLite 0.4.3 pin + `trustedDependencies`). Locked to 0.15.1 in advance: other work may land before/after this PR, but the version is fixed so reviewers can cite a stable number. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |