master
1071 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d13aa742fd |
v0.51.0.0 feat: make concurrent writes durable and revision-safe (#5149)
Some checks failed
Actionlint / actionlint (push) Failing after 16s
E2E Tests / Tier 2 (LLM Skills) (push) Has been skipped
Release / version (push) Successful in 5s
Test / gitleaks (push) Failing after 59s
Test / security-regressions (1.3.11, ubuntu-latest) (push) Failing after 10m54s
Test / security-regressions (1.3.13, ubuntu-latest) (push) Failing after 10m49s
Test / dependency-audit (push) Successful in 9s
Test / verify (push) Failing after 11s
Test / serial-tests (1) (push) Failing after 1m4s
Test / serial-tests (2) (push) Failing after 14s
Test / serial-tests (3) (push) Failing after 14s
Test / serial-tests (4) (push) Failing after 14s
Test / slow-eval-longmemeval (push) Failing after 11s
Test / slow-brainbench-e2e (push) Failing after 13s
Test / brainbench (push) Failing after 10s
Test / slow-entity-resolve-perf (push) Failing after 12s
Test / test (1) (push) Failing after 28s
Test / test (10) (push) Failing after 27s
Test / test (2) (push) Failing after 26s
Test / test (3) (push) Failing after 34s
Test / test (4) (push) Failing after 39s
Test / test (5) (push) Failing after 36s
Test / test (6) (push) Failing after 36s
Test / test (7) (push) Failing after 22s
Test / test (8) (push) Failing after 42s
Test / test (9) (push) Failing after 23s
Test / native-locks (push) Failing after 23m32s
Test / persistence-validation (push) Failing after 38m54s
Release / build (gbrain-linux-x64, ubuntu-latest, bun-linux-x64) (push) Failing after 11m35s
Test / coverage-report (push) Failing after 27s
Test / Native-only result (full CI not run) (push) Has been skipped
Release / build (gbrain-darwin-arm64, macos-latest, bun-darwin-arm64) (push) Has been cancelled
Test / security-regressions (1.3.11, macos-latest) (push) Has been cancelled
Test / security-regressions (1.3.11, windows-latest) (push) Has been cancelled
Test / security-regressions (1.3.13, macos-latest) (push) Has been cancelled
Test / security-regressions (1.3.13, windows-latest) (push) Has been cancelled
Release / release (push) Has been cancelled
Release / publish-template (push) Has been cancelled
Release / publish-codex-plugin (push) Has been cancelled
Test / ${{ github.event_name == 'workflow_dispatch' && inputs.native_only == true && 'full-suite-not-run' || 'test-status' }} (push) Has been cancelled
OSV-Scanner / osv-scan (push) Failing after 0s
Semgrep / semgrep (push) Failing after 0s
E2E Tests / JSONB parity (#2339 regression guard) (push) Failing after 9s
E2E Tests / prepare-e2e (push) Failing after 11s
E2E Tests / Selected E2E (diff-relevant) ${{ matrix.shard }} (push) Has been skipped
E2E Tests / Tier 1 (Mechanical) (push) Failing after 9s
E2E Tests / coverage-full-unit (1) (push) Failing after 22s
E2E Tests / coverage-full-unit (10) (push) Failing after 21s
E2E Tests / coverage-full-unit (2) (push) Failing after 20s
E2E Tests / coverage-full-unit (3) (push) Failing after 28s
E2E Tests / coverage-full-unit (4) (push) Failing after 31s
E2E Tests / coverage-full-unit (5) (push) Failing after 32s
E2E Tests / coverage-full-unit (6) (push) Failing after 28s
E2E Tests / coverage-full-unit (7) (push) Failing after 16s
E2E Tests / coverage-full-unit (8) (push) Failing after 36s
E2E Tests / coverage-full-unit (9) (push) Failing after 18s
E2E Tests / coverage-full-serial (push) Failing after 7s
E2E Tests / coverage-full-slow (push) Failing after 7s
E2E Tests / coverage-full-e2e (push) Failing after 8s
E2E Tests / coverage-full-report (push) Failing after 12s
E2E Tests / e2e-status (push) Failing after 0s
Heavy Tests / Heavy tests (push) Failing after 10s
Heavy Tests / Real-agent door e2e (skips without authed binaries) (push) Failing after 7s
Heavy Tests / Hermes door e2e (real binary, loud-fail) (push) Failing after 9s
Heavy Tests / Grok door e2e (real binary, keyless-first) (push) Has been skipped
Heavy Tests / Plugin doors (codex + claude, install tier) (push) Failing after 7s
Heavy Tests / opencode door e2e (real binary, keyless SMOKE) (push) Failing after 8s
Heavy Tests / opencode door canary (latest, keyless, non-gating) (push) Failing after 7s
* Add typed mutation receipts and preserve pending write errors * Add canonical page revisions, snapshot reads, and composable transaction guards * fix: add portable native writer locks and runtime gates * Route PGLite operations through bounded local persistence IPC * Add durable mutation admission and recoverable canonical page publication * Prepare CLI mutations before connecting and preserve replay intent * Wire resident writer ingress and fence unmanaged canonical mutation * Fence derived projections by canonical revision and persist withdrawal rebuild work * Expose principal-scoped durable write receipts without widening grants * fix: retain datastore ownership through shutdown and fence lease cleanup * Journal memory verbs and publish semantic fact updates under canonical guards * Coordinate semantic page mutations and seal only current sanitized projections * Administer resident writers through authenticated local CLI IPC * Journal takes mutations and share long-hold budgets across physical pools * Route take mutations through replayable operations before opening PGLite * Compose canonical projections with publication and retry transient database contention * Document concurrent write guarantees and explicit receipt grant migration * test: exercise durable persistence schedules and process crash recovery * Apply shared persistence limits and compact permanent receipts with exact accounting * fix: honor explicit direct routes for generic Postgres poolers * Retain original page visibility ceilings and intentional sandbox persistence * test: verify pooler capacity and owner incarnation fencing * Preserve canonical projection round trips and timeline detail through recovery * Wire persistence distribution guards and refresh public operation documentation * Retry postcommit effects and recover withdrawal mirrors independently * Include outbox schema in snapshot identities and isolate fresh test brains * Fence legacy canonical writers and require revision-safe imports * Activate managed persistence only after explicit quiescence and durable fencing * Require honest median-of-three read latency under public writer load * Require writer progress during read latency samples * Compose graph reconciliation with canonical publication and retain writer ceilings * Exercise source-scoped takes and duplicate fences with durable principals * Preserve transaction receivers when restoring extraction test stubs * Install revision-bound retrieval fixtures and preserve strict projection gates * Keep engine test overrides composable across transaction clones * Assert atomic readback rollback and public failed write receipts * Settle definite publication failures and preserve typed receipts across CLI boundaries * Restore bounded fact extraction receipts and durable postpublication scheduling * Share activation fixtures within explicit engine lifecycles * Model scoped read transactions and publish complete retrieval fixtures * Coordinate resumable owner-scoped Markdown sync through durable page receipts * Exercise page source and privacy boundaries with durable writer fixtures * Publish complete search fixtures and assert composable scoped SQL routing * fix: retain archived alias reads and expose writer ingress diagnostics * Exercise managed writer activation in persistence validation workloads * Publish revision-bound ranker and max-pool retrieval fixtures * test: bind engine fixtures to coherent page projections and durable writes * fix: compare enrichment against its original page snapshot * fix: preserve withdrawal markers across legacy history and projection rebuilds * fix: authenticate resident sync ingress and prevent writer starvation * fix: durably acknowledge recovery and advance missing-file withdrawal effects * Retain mutation identity and revision through internal caller retries * Preserve contextual wrapping for deferred coordinated embeddings * Install coherent retrieval fixtures and inspect raw chunk state explicitly * fix: budget and fairly schedule standalone publication recovery * Keep privacy and image fixtures aligned with projection visibility * Bind embedding provenance to the prepared provider context * Publish complete relational and search regression fixtures * Preserve raw registry write checks and seal deferred embedding fixtures * Retry coordinated imports when source policy cannot be read * Preserve legacy migration data and exercise revision-aware public writers * Coordinate managed source lifecycle and durable clone recovery * fix: bind owner identity to the physical canonical checkout * fix: reserve control capacity during source lifecycle publication * fix: preserve delegated sync recovery and deferred embed ownership * Verify lifecycle staging identity and preserve bounded recovery * fix: account for pending clone requests in shared admission quotas * test: align retrieval and replay fixtures with durable publication * Release clone reservations exactly once and recheck source routing * Require PostgreSQL lifecycle and recovery contracts in CI * test: require physical-root refusal in the deployment matrix * Route source administration through resident ownership and retained identities * fix: retain captured canonical file routing under registered ownership * test: exercise authenticated atomic take publication and retained replay IDs * Retry confirmed admission aborts and preserve direct CLI conflict receipts * Fix revision-safe import revival and preserve identity deduplication * test: publish embedding migration fixtures before re-embedding * Exercise durable publication with the actual release executable * Exercise conditional embedding updates with coherent serial fixtures * Verify clean resident EOF shutdown in the release smoke * Seal search fixtures and assert durable side-effect outcomes * Bound recovery preparation and exercise admission timeout receipts * fix: retain delegated ownership and enforce take receipt holder grants * Restore tombstoned pages consistently and preserve unexpected local files * Preserve deletion state in canonical page versions * Retry withdrawals after releasing the complete transaction * Keep canonical version deletion schema bootstraps consistent * Keep canonical version types beside page state * Filter protected timeline content from remote version history * Require PostgreSQL version history privacy coverage * Require explicit native test timeouts in every CI entry point * Bind Windows native locks to the active runtime API * Test fact authorization with durable source grants * Wait for authenticated persistence readiness in compiled CLI smoke * Seal search fixtures against their canonical page revisions * Refresh managed lifecycle fixtures and reviewed canonical writer inventory * Measure staging bytes in clone metadata quota regression * Preserve canonical write provenance and typed storage failures * Measure durable admission through stable warmed workload instrumentation * Require both engines in durable admission instrumentation regression * Preserve bounded soak failure diagnostics and test fixtures * Exercise timeout preflight in local CI execution fixtures * Verify tombstone restoration values and stable no-op bytes * Keep native workflow coverage checks compatible with explicit timeouts * fix: bind local IPC safely across long paths and concurrent owners * Require IPC ownership and path tests on every native target * fix: preserve inaccessible IPC owners when Bun loses connect errno * Isolate PgBouncer fixtures from test database guards and shard resets * ci: isolate native-only dispatches from full persistence validation * Keep agent seed worktrees outside their coordination state * Seal expert search fixtures at their canonical page revision * test: exercise durable PostgreSQL take publication and replay * fix: retain native ownership across Windows IPC listeners * fix: serve admin SPA from hidden checkout directories * fix: derive Windows pipe claims from NT Unicode upcasing * test: match Unicode IPC aliases to actual Windows pipe equality The four Windows runners in run35037789501 proved dotless-i and I are separate pipe names: kernel_alias=false, CompareStringOrdinal=3, with identical NT and invariant-locale case tables. Keep both independent providers in coverage and require genuine sigma/accent aliases to share one live provider and native claim. Preserve the native API oracle. Restore the exact native source, build recipe, manifest and artifacts from 2a703bb9875f214708d0c23b070fdd188ed3b459; the provisional NT upcase change was unnecessary. All six non-Windows artifacts remain byte-identical. Input SHA256: before b86ba93886091ab6b8dbba48c891966680ed3484b5d815ac31684da401f1ec73 after 4759bdd927c0c0fa29c2d5af30e42972a183f9be006d595144d73b6ca1111636 Windows x64 SHA256: before f5c9d45e261757b510979534b447bb118e95d5699c3dd6e8f1ec31200c6372aa after 0b494ec94896219a3b142b6f216bf12c9ee94d27fa7e7399bcdab707ca60212e Windows ARM64 SHA256: before 74fe0d4e8205738675ba5dcccf55edbf5bb250ec96724b84b3490c30e3e27bf2 after e8315b4453dce3df775eeb76c73e8895c273390e64b16a2c255e10790fa75dd7 * Repair merged fixtures for revision-bound chunk reads * Require local legacy-chunk reads to honor projection seals * Account for reviewed upstream canonical write references * Isolate ambient keyset fixture page clocks from fact writes * fix: settle publication failures beneath blocked file ancestors * Match TTL vector fixture to the initialized fact column * Record coordinated purge in canonical writer census * docs: align concurrent persistence contracts and sync guidance * fix: fence projection replacement to its originating snapshot * fix: bound unit shard processes without dropping coverage * fix: publish embedding vectors and contextual completion atomically * test: isolate thin-client health and write fixtures * test: isolate healthy doctor checks from retained E2E grants * test: isolate each local unit file in its own Bun process * fix: keep persistence parameter schemas free of registry cycles * test: restore thin-client routing exit state * style: consolidate page operation engine imports * fix: isolate purge validator from generic flag scans * test: isolate Postgres bootstrap ownership fixture * test: isolate open-loop engine parity database * chore: bump version and changelog (v0.51.0.0) Document the coordinated concurrent-writer upgrade and synchronize the release manifests, migration guide, generated stamps and skills lock. Co-Authored-By: Codex <noreply@openai.com> * docs: update concurrent-write guide for v0.51.0.0 * fix: resolve concurrency persistence security scan findings --------- Co-authored-by: Codex <noreply@openai.com>v0.51.0.0 |
||
|
|
668b9bac30 |
v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins Closes the critical- and high-severity items from six privately reported advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv, GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a single commit so no intermediate revision carries a test-fixture credential shape through the gitleaks range gate. Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0 owner-approval flow is pinned end to end against a real `serve --http --enable-dcr` process and in-process: anonymous /authorize mints no code, a forged code is rejected at /token, revoked clients are refused at grants.begin, and OAuthGrants.begin() now caps awaiting-decision requests per client_id. Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2). registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only. Remote sources_remove is source-fenced like sources_status. doctor's oauth_client_scope_health flags privileged self-registered clients. Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus bearer and db_url_credentials catch-alls; the transcripts lane opts into the digit-gated high-entropy rule; getRawData follows the page soft-delete on both engines; delete_page --purge (local-CLI only) hard-removes a leaked page. Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_* variables when a working-directory .env assigns them (key-presence, since Bun expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs. Release artifacts: VERSION/package.json/three plugin manifests bumped to 0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md, CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin trees, skills.lock, flag registry and llms bundle regenerated; module-size ceilings adjusted with per-row reasons; TODOS follow-ups filed. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix: pre-landing review fixes (v0.50.2.0 security wave) Review cycle 1 of the ship: 6 specialists + red team + coverage audit. Security / red team: - env-trust: parse .env with Bun's line grammar (bare CR terminates a line; BOM/U+2028 cannot hide an assignment); protect the loader / git / node / proxy / AI-CLI variable families a checkout could plant for the programs gbrain spawns; cli-preflight re-execs gbrain once with the sanitized environment so git, the agent CLI and workers inherit the clean view; cwd == ~/.gbrain no longer quarantines the operator's own .env. - guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths (a package name resolves from the cwd's node_modules). - secret-scan: bounded db_url_credentials quantifiers + per-pattern prechecks (linear on long lines), windowed previews that redact every sibling span, single-pass longest-first replacement. - TODOS: follow-up entries reworded to the functional level. API contract / maintainability: - delete_page purge: remote callers get permission_denied; a purged response always carries write_through; get_raw_data description states the soft-delete follow; includeDeleted narrowed to the getRawData signature; client_credentials gate evaluated before the DCR ceiling; doctor privileged set derived from the scope registry; sources_remove / sources_status share assertSourceInCallerScope; shell-job opt-in reaches --job-isolation process children as --allow-shell-jobs; stale help copy. - transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key order made every healthy re-run rewrite unchanged rows). Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms bundle, flag registry, tool catalog, structural suites regenerated; module-size rows adjusted with reasons. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave) Re-exec redesign (security + red team + adversarial findings): - cli-preflight re-runs gbrain from an empty temporary directory so the sanitized child never reloads the hostile .env: dropped keys are absent, never carried as '' (git and the dynamic loader presence-check GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident). - The re-run marker is JSON {cwd, neutral} honoured only when the process provably started in that empty directory — a marker planted via a cwd .env is ignored (the ppid-keyed marker was forgeable under systemd/docker). - SIGINT is delivered by the tty once (wrapper no longer forwards it); SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime. - Protected families widened: XDG config roots (git reads $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker. - cwd dotenv parsed once per start; jobs start uses the same '1' literal. secret-scan (cycle-2 findings): - db_url_credentials password class only stops at whitespace, '@' and string delimiters again (unescaped / { } < > | ^ ` \ passwords redact); BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts were quadratic); incremental PEM line cursor; redactFindings rebuilds the text by span-splice in one pass (was O(unique values x text)). Contract / docs: - delete_page purge responses carry a residuals hint (git history, exports, compiled context, slug-keyed derived rows); CHANGELOG states a single truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under Changed with a migration note); SECURITY.md / KEY_FILES / docs guides / minion-orchestrator skill describe the new mechanism and the --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source marker on the hook spawn-shape test; new PEM fixtures fragmented. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave) - Compiled binaries: every `bun build --compile` invocation passes `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh` guard (self-tested, in verify CHECKS) keeps it that way. - cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`, OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE join the protected set; the neutral hop dir is realpath'd; signal handlers are installed before the spawn; non-tty wrappers forward SIGINT once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had a value. - secret-scan: PEM header-line cursor is O(text) on newline-free tails; bounded bearer echo pass redacts bare re-occurrences of claimed tokens. - transcripts ingest: raw-metadata probe reads active rows only. - Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT, perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms + skills.lock + plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave) Cross-model adversarial pass (Codex) + Claude verifier findings: - env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH, BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded. - cli-preflight: config-dir exemption refused when the cwd .env assigns GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal listeners so its exit is always the child's; SIGINT forwarded only without a controlling terminal (/dev/tty probe); a dropped planted HOME is restored from the passwd home; script-mode runs warn once when the cwd bunfig.toml declares a top-level preload. - secret-scan: overlapping matches redact the UNION of matched spans; echo pass covers bearer + high-entropy values (64 unique, <=512 chars) via per-value sweeps over unclaimed gaps only; planRedaction/ applyRedaction share a session-wide echo dictionary in transcripts render. - sources_remove keys on write authority (assertSourceInCallerWriteScope); federated read grants confer no removal right. - delete_page --purge retries the tombstone's file removal and fails closed (storage_error) while the file remains. - Docs: SECURITY.md quarantine example no longer uses the one key that refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave) - cli-preflight: hop marker carries the wrapper pid; a verified re-run arms an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the wrapper is force-killed, so supervisor restarts never orphan a worker; relative path-bearing runtime flags (--preload/-r/--require/--import, --config/-c, --env-file, --tsconfig-override) are resolved against the original cwd before the hop. - secret-scan: echo pass is a streaming leftmost-longest merge with O(values) retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now covered wall-to-wall. - Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: update project documentation for v0.50.3.0 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(ci): green the three failing checks on the v0.50.3.0 wave - semgrep: six `nosemgrep` suppressions with justifications for the path-join/resolve and non-literal-RegExp taint heuristics on operator- controlled cwd/flag paths and compile-time pattern sources (no behaviour change). - test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the pty's SIGINT on itself after the child exits (130) instead of relaying the child's 42. The pty command now `exec`s the wrapper so no shell stays in the foreground group; documented in a `ptyCommand` helper. - Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly the self-registration ceiling (`read write`) via `scopesSupportedForDiscovery`, so a connector that copies `scopes_supported` into /register succeeds (master's #5122 pin); without DCR the full operator list minus `agent` is unchanged. Sibling e2e assertions that expected privileged scopes on the DCR-enabled server updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES updated; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
039f2cd52a |
v0.50.4.0 ci: accelerate required checks with isolated test workers (#5131)
* ci: refresh timing weights and share balanced scheduling * ci: freeze selected E2E files across four isolated workers * ci: shard isolated serial pools and verify coverage identity * test: reuse isolated snapshot profiles for BrainBench CLI evals * test: preserve snapshot ownership across normal lock release * test: cover exclusive cancellation and interrupted snapshot publication * v0.50.4.0 ci: shorten required-check feedback and record measurements Co-Authored-By: Codex <noreply@openai.com> * docs: update project documentation for v0.50.4.0 --------- Co-authored-by: Codex <noreply@openai.com> |
||
|
|
7fb6617dbf |
v0.50.2.0 fix: harden persistence, maintenance, sync, and hosted access (#5122)
* fix: preserve unresolved facts and canonical fence rows Keep unresolved targets nullable, resolve unique source-local full basenames, and prevent migration stubs and row collisions. Manually adapts #5096; addresses #5110, #5111, and #5093. * fix: preserve current embeddings and structured lock identity Manually adapts #5056, #5065, and #5073. Keep matching vectors, use structured process arguments and the Windows-aware probe, and observe deletion-race rejections before releasing the test transaction without changing their assertions. * fix: persist canonical pages before optional embedding Reject worktree contention before import, roll back rejected canonical writes, release page-owned locks before optional enrichment, and discard superseded vectors. Incorporates the persistence-first principle from #5100; partially addresses #5105 without a durable queue or caller revision preconditions. * fix: require persisted writes and completed maintenance Reject unsuccessful required writes, leave incomplete or deferred maintenance due, recommend database-backed stale extraction, and keep embedded eval failures from exiting the host. Manually adapts the global freshness guard from #5089; addresses #5098, #5095, and #5112. * fix: normalize Windows sync paths and restore Bash parsing Normalize Git-relative path separators and vendor the checksum-verified official tree-sitter-bash v0.23.3 asset. Uses the grammar-refresh approach from #5109 without its unrelated provider changes; advances the code chunker to version 7. * fix: preserve hosted routing and read-only OAuth bootstrap Manually adapts #5107 and the challenge-hint approach from #5113, narrowed to read-only bootstrap. Preserve granted read scope, refuse local call on thin clients, register schema_pack, and exclude agent delegation from DCR discovery. * v0.50.2.0 chore: document collector fixes and upgrade guidance Ship the approved patch version with synchronized manifests, generated distribution stamps, safe upgrade instructions, and explicit persistence and verification limits. All community contributions were manually adapted; no external PR branch was merged. Co-Authored-By: anshmudgil <anshmudgilselc@gmail.com> Co-Authored-By: harjoth <harjoth.khara@gmail.com> Co-Authored-By: masashiono0611 <masashi.ono.0611@gmail.com> Co-Authored-By: xaviroblessarries <272064662+xaviroblessarries@users.noreply.github.com> Co-Authored-By: Tarush Aggarwal <tarush@teio.ai> Co-Authored-By: lqtdys <tao0101@163.com> Co-Authored-By: Javier Aldape <javieraldape@users.noreply.github.com> Co-Authored-By: Garo Nazarian <garonazarian09@gmail.com> * test: mark synthetic embedding password as a placeholder * v0.50.2.0 docs: sync persistence and migration guidance * docs: qualify release lock ownership and track migration banner debt --------- Co-authored-by: garrytan <19957+garrytan@users.noreply.github.com> Co-authored-by: anshmudgil <anshmudgilselc@gmail.com> Co-authored-by: harjoth <harjoth.khara@gmail.com> Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> Co-authored-by: xaviroblessarries <272064662+xaviroblessarries@users.noreply.github.com> Co-authored-by: Tarush Aggarwal <tarush@teio.ai> Co-authored-by: lqtdys <tao0101@163.com> Co-authored-by: Javier Aldape <javieraldape@users.noreply.github.com> Co-authored-by: Garo Nazarian <garonazarian09@gmail.com> |
||
|
|
f1fbdfba19 |
v0.50.1.0 fix: community fix wave — 21 PR adoptions + 35 verified issue fixes + composite review, rebased on 0.50.0.0 (#5097)
The community fix wave, rebased onto 0.50.0.0: every open community PR triaged and every open issue verified against master. 21 contributor pull requests adopted or reworked with credit, 35 verified open issues fixed directly, and a hostile review pass over the composed branch (composite review of the wave, /ship review army with 8 specialists + Claude adversarial, five Codex structured-review rounds until 0 findings). Every adopted fix carries a regression test proven red before the fix; the composed collector ran the full unit suite, `verify`, and the e2e lane, and CI is green on the merged head. Behavior changes (38, all listed under "Behavior changes" in the CHANGELOG): sync --json emits one JSON document with cost_gate nested; sweep-only sync reports synced/deleted; dream --dry-run skips the take/grade/calibration phases; context_pack/delta honor budget_tokens on the rendered text and delta never budget-drops threads; codex rollouts import one page per thread; config set registers exactly the search.* keys the search path reads; remote search/query report degraded: [safe_index_pending] before reindex; syncEnabled: false sources are no longer auto-synced; new sync.include_hidden key; migrateFactsToCanonical renumbers past the canonical page's max row_num; stall-aborted embed drains fail the phase. No new schema migration. Follow-ups filed in TODOS.md under "Community fix wave follow-ups". Co-Authored-By: IvanPham03 <IvanPham03@users.noreply.github.com> Co-Authored-By: Jey2311 <Jey2311@users.noreply.github.com> Co-Authored-By: LongPV <LongPV@users.noreply.github.com> Co-Authored-By: Masashi-Ono0611 <Masashi-Ono0611@users.noreply.github.com> Co-Authored-By: chris-conte <chris-conte@users.noreply.github.com> Co-Authored-By: dov-kela <dov-kela@users.noreply.github.com> Co-Authored-By: ethanbeard <ethanbeard@users.noreply.github.com> Co-Authored-By: garrytan-agents <garrytan-agents@users.noreply.github.com> Co-Authored-By: howardpark <howardpark@users.noreply.github.com> Co-Authored-By: janusch <janusch@users.noreply.github.com> Co-Authored-By: javieraldape <javieraldape@users.noreply.github.com> Co-Authored-By: jeanpierre121 <jeanpierre121@users.noreply.github.com> Co-Authored-By: markkasdorf <markkasdorf@users.noreply.github.com> Co-Authored-By: morven-ai <morven-ai@users.noreply.github.com> Co-Authored-By: ofroiland <ofroiland@users.noreply.github.com> Co-Authored-By: ozp <ozp@users.noreply.github.com> Co-Authored-By: pavelpp-topia <pavelpp-topia@users.noreply.github.com> Co-Authored-By: proxynico <proxynico@users.noreply.github.com> Co-Authored-By: sheelcheyne <sheelcheyne@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
a6be012a3b |
v0.50.0.0 fix: secure client consent, background jobs, and data handling (#5027)
* chore(security): enforce precise secret-scanning rules * fix(security): enforce consent and durable execution boundaries Use data-only document metadata, owner consent and transactional OAuth grants, source-aware delegated tools, and durable authorization throughout queued work. Confine filesystem effects and guarded outbound requests, preserve active sessions, and document the coordinated worker upgrade and recovery process. Include dependency patches, regression fixtures, admin assets, generated contracts, audits, and isolated CI execution with the runtime changes. Validation: complete manual CI equivalent passes 29,333 tests with zero failures, all 54 structural/type checks, root/admin audits, secret scanning, all 232 E2E files with mandatory PgBouncer, and compiled binary smoke checks. Optional provider-dependent branches remain disabled without credentials. * v0.50.0.0 chore: prepare authorization and worker security release * test: make proxy and scanner fixtures portable * test: remove mapped E2E suites from unmapped baseline |
||
|
|
1fc8b6c2d8 |
v0.49.0.0 feat: add GBrain to existing agents and unify hosted access (#5006) (#5026)
* test: isolate embedding configuration between unit fixtures Reset model-probe gateway state and pin chunk-sanitization fixtures to the shared legacy embedding dimensions. Preserve the original persistence and hash assertions. * feat: add existing-agent memory and unified hosted access (v0.49.0.0) Add isolated in-agent setup and repair, private PGLite backup and relocated restore, shared hosted grants and live delegation enforcement, secure credential handoff and recovery, and capability discovery and verification. Make local and hosted onboarding prominent in dedicated Grok Bot and Muse guides. Preserve explicit native-harness acceptance gates, update generated references and release metadata, and keep withdrawn facts out of active memory after synchronization. Co-Authored-By: OpenAI Codex <noreply@openai.com> * docs: sync harness documentation for v0.49.0.0 * fix: update security dependencies and confine restored configuration Refresh patched dependency versions, traverse only owned configuration properties during restore, and trust the CI checkout before calculating the Semgrep baseline. Add a regression that preserves inherited path objects. --------- Co-authored-by: OpenAI Codex <noreply@openai.com> |
||
|
|
43597b19e5 |
v0.48.5.0 fix: community fix wave — 57 PR adoptions + 42 verified issue fixes + composite review rounds (#4954)
Every open community PR triaged and every open issue verified against master: 57 contributor pull requests adopted or reworked with credit, 42 verified issues fixed directly (17 more closed by the adopted PRs), and a hostile review pass over the composed branch (composite 8-lens review, /ship review army + Claude and Codex adversarial passes, 27-agent review of the CI fixes). Every adopted fix carries a regression test proven red at its base. The #4807 slug-extension chain was reverted and returned to the maintainer. Behavior changes: code sources sync as code (soft-delete window 72h); migration v146 adds the extract-atoms transcript-state tombstone table; serve refuses an unknown GBRAIN_SOURCE at startup; think/graph-query resolve --source; recall composes since with entity/session_id; delta cursors carry microseconds; sync --json is pure JSON; autopilot skips unavailable paths; CJK chunk overlap applies to new pages only; import --source requires a registered source; bootstrap harness validates --source and, under a live PGLite serve, refuses without a token or wires hooks unpinned with --token. See CHANGELOG.md 0.48.5.0 and PR #4954 for the per-theme list and contributor credit. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Co-Authored-By: G0-0000 <G0-0000@users.noreply.github.com> Co-Authored-By: Jey2311 <Jey2311@users.noreply.github.com> Co-Authored-By: LongPV <LongPV@users.noreply.github.com> Co-Authored-By: Masashi-Ono0611 <Masashi-Ono0611@users.noreply.github.com> Co-Authored-By: Natetgmaxwell <Natetgmaxwell@users.noreply.github.com> Co-Authored-By: NothoiMatt <NothoiMatt@users.noreply.github.com> Co-Authored-By: Walliiee <Walliiee@users.noreply.github.com> Co-Authored-By: afshaker <afshaker@users.noreply.github.com> Co-Authored-By: amirelion <amirelion@users.noreply.github.com> Co-Authored-By: arisgysel-design <arisgysel-design@users.noreply.github.com> Co-Authored-By: armandovargash <armandovargash@users.noreply.github.com> Co-Authored-By: awilhite <awilhite@users.noreply.github.com> Co-Authored-By: bhattman-dev <bhattman-dev@users.noreply.github.com> Co-Authored-By: gagecane <gagecane@users.noreply.github.com> Co-Authored-By: hpamike <hpamike@users.noreply.github.com> Co-Authored-By: hyunje-ethan-jang <hyunje-ethan-jang@users.noreply.github.com> Co-Authored-By: javieraldape <javieraldape@users.noreply.github.com> Co-Authored-By: jeanpierre121 <jeanpierre121@users.noreply.github.com> Co-Authored-By: johnerik <johnerik@users.noreply.github.com> Co-Authored-By: malachany <malachany@users.noreply.github.com> Co-Authored-By: mariokarras <mariokarras@users.noreply.github.com> Co-Authored-By: mike-tech-ship-it <mike-tech-ship-it@users.noreply.github.com> Co-Authored-By: morven-ai <morven-ai@users.noreply.github.com> Co-Authored-By: mvanhorn <mvanhorn@users.noreply.github.com> Co-Authored-By: noelboss <noelboss@users.noreply.github.com> Co-Authored-By: paul-0320 <paul-0320@users.noreply.github.com> Co-Authored-By: proxynico <proxynico@users.noreply.github.com> Co-Authored-By: spiky02plateau <spiky02plateau@users.noreply.github.com> Co-Authored-By: tomatkins <tomatkins@users.noreply.github.com> |
||
|
|
2efaaf8f8a |
v0.48.4.0 feat(search,eval): ranker wave — autocut off, relational rerank pin, metadata boost gate; LongMemEval harness with strict recall_all@5 + judged answer accuracy (#4946)
* fix(cli): flag registry attributes compound dispatch blocks to their command The generator's marker regex only matched plain `if (command === 'X')` and `case 'X':` markers, so every compound pre-dispatch bypass in handleCliOnly (`if (command === 'eval' && args[0] === 'longmemeval')`, the `--help` pre-engine branches, the agent-register guard) was attributed to the preceding marker. The documented `gbrain eval longmemeval <f> --retrieval-only --by-type --no-trajectory` exited 1 at the unknown-flag validator because the eval row carried none of its subcommand flags. - segmentDispatchBlocks(): labels the `command === 'X'` head of any `if (` (plain, compound, multi-line) plus `case 'X':`; block-level module scan restricted to ./commands/*.ts so pre-connect helper imports no longer add phantom flags (the agent row lost --delete-brain and friends). - Registry regenerated (idempotent); eval gains its subcommand flags, dream/status/backup lose misattributed ones. - Tests: acceptance + rejection (the eval row stays a union across eval subcommands by design) + a subprocess smoke of the documented command. - The contradictions remediation hint no longer suggests `dream --slug` (dream never parsed it; the registry-gated remediation test caught it). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(search): role-tagged fusion arms + expansion_variant_budget knob (legacy default, byte-identical) One composition point for RRF inputs: hybrid.ts builds `vectorArms` (original | variant | clause | image) via pushVectorList at every assembly site and hands them to composeFusionLists (new src/core/search/fusion-lists.ts), which returns the full weighted list set. rrfFusionWeighted scores weight/(k+rank); weight defaults to 1, so fusion is byte-identical to before. `search.expansion_variant_budget` (ModeBundle, config key, per-call seam) is the pre-registered fix for LLM multi-query expansion diluting small-k recall: a total RRF weight shared equally by the non-empty variant/clause lists (weight_i = b / n_voting_arms). `null` = legacy (every list weight 1) and is the default in all three bundles; the flip waits for the LongMemEval receipt. One range contract (normalizeExpansionVariantBudget) serves the config parser and both hybrid.ts seams. KNOBS_HASH_VERSION 28 -> 29 (`evb=` part; one-time cache miss). queries[0] is enforced to be the caller's query after expandFn. The both-mode fell-open corner no longer mis-tags the last text list as the image branch. onRerankPool fires with the exact pre-autocut returnPool (post alias-hop / exact-lookup / adaptive-return) so an offline autocut replay is faithful. `gbrain search modes` renders a legitimate null as `legacy (null)`. Tests: pure fusion arithmetic (knife edge at budget 1.0), hermetic directional PGLite test, CRITICAL regression on the both-mode demotion gate, six knobs-hash pins + two titles, bundle snapshots, modes report. TSV ceilings raised to exact counts (hybrid.ts 3177, mode.ts 1577, config.ts 1766). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(eval): LongMemEval harness scores the official strict metric and is the receipt producer `gbrain eval longmemeval` now measures what the paper measures and records enough to reproduce it: - Raw-id join through a per-question slug -> raw session-id map (gold ids are compared as the dataset spells them; slug collisions touching gold abort the question with an error row). - recall_all@k (every gold session among the distinct sessions of the top-k chunk rows) as the headline, recall_any@k as the diagnostic; abstention (`_abs`) questions excluded from recall denominators unless --include-abstention; --by-type-floor gates on the strict rate (--by-type-floor-metric recall_any restores the old semantics). - Pins: --reranker on|off, --autocut on|off, --expansion-variant-budget, --mode; --reranker on preflights readiness (exit 2) and any row that fell through un-reranked, or whose vector arm silently degraded, fails the run. - Schema-v2 by_type_summary with run_config (pins, embedder, dataset sha, knobs hash, cache stats, degradation counters); per-row retrieved[] with scores, search_meta, retrieval_config_hash; --capture-pool records the pre-autocut pool for offline floor replay; --expansion records variants and --expansion-replay serves them; --question-ids; --record appends a redacted EvalRunRecord (redaction now lives in persistRunRecord). - Content-addressed embedding cache (src/eval/shared/embed-cache.ts, bun:sqlite, WAL, dims verification, canonical hash) through the gateway transport seam; resume recomputes both metrics and refuses a mixed retrieval_config_hash unless --allow-mixed-run-config. - LME_FLAGS table drives both parseArgs and printHelp (the flag registry scans help text). Help fixed: --mode tokenmax does not imply --expansion. - Metric glossary gains recall_all@k, recall_any@k, qa_accuracy, mean_returned_est_tokens, mean_returned_results (new LongMemEval group). - Receipt tooling: scripts/eval-spend-guard.sh (fail-closed ledger cap), scripts/replay-autocut-floor.ts + src/eval/shared/autocut-replay.ts, seeded dev/decision/half splits in evals/longmemeval/. - Fixture test/fixtures/longmemeval-mixedcase.jsonl (placeholder text, dataset-shaped ids) pins the join, strict/any split, and abstention. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: ranker wave reference docs — fusion arms + expansion budget knob, LongMemEval harness as the reproduction path - KEY_FILES: current-state entries for fusion-lists.ts, the harness modules (metrics/run-config/resume), shared embed cache + autocut replay, the spend guard, the flag-registry generator's compound-marker segmentation, and the seeded splits; mode.ts and eval-longmemeval.ts entries rewritten. - RETRIEVAL.md: the expansion sentence now states the receipted truth (strict recall_all@5 93.19% plain hybrid vs 54.89% equal-weight expansion) and the budget-normalized weighted RRF; pool capture for offline autocut replay; the verify block shows the like-for-like and default-path runs. - search-modes.md: expansion_variant_budget knob row + say-line. - eval-bench.md: in-repo command is the reproduction path (self-check caveats removed), full flags table, schema-v2 summary example, recall_hit deprecated alias, --by-type-floor gates on recall_all, sessdiv rows marked as from the 2026-09-02 run. Measured numbers unchanged. - README: the two self-check sentences updated; no new claims. - CLAUDE.md: three knobs-hash history paragraphs collapsed into one current-state sentence (58,557 -> 58,086 bytes). - TODOS: search.dedup_max_per_page re-pointed to knobs-hash v30. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(eval): LongMemEval judged answer-accuracy lane (--judge) with official prompts and complete-judgment headlines `gbrain eval longmemeval --judge` grades generated answers with a verbatim port of the official evaluate_qa.py per-type yes/no prompts (standard, temporal-reasoning off-by-one tolerance, knowledge-update, preference rubric, abstention), judge gpt-4o at max_tokens 10 / temperature 0, and publishes a qa_accuracy block whose headline scores every question the judge could not grade (timeout, refusal, malformed, budget skip) as INCORRECT, with accuracy_excluding_errors and the judge_errors count alongside. Gold and hypothesis travel inside the #4338 data boundary. - src/eval/shared/judge-runner.ts: prompt-agnostic runner (retry+backoff on timeout/429, closed judge_error vocabulary, cost via canonicalLookup, BudgetLedger soft-stop); src/eval/shared/bootstrap.ts: seeded question bootstrap CI (labelled question-sampling only). - src/eval/longmemeval/{judge,judge-lane,qa-accuracy,reader,emit}.ts: prompts + verdict parse + judge_config_hash, preflight/backfill, the qa_accuracy block, the peeled reader (system text now carries the abstention instruction; reader_prompt_sha and the provider-reported model snapshot are recorded per row), the emitter. - Flags: --judge, --judge-model, --max-usd (judge spend only), --yes, --judge-concurrency, --allow-incomplete-judgments; --judge --resume-from is a judge-only backfill gated by judge_config_hash; a run with judge errors or budget skips is "not publishable" (exit 1). - gateway: ChatOpts.temperature threads to generateText; ChatResult exposes the response model id. - Glossary: qa_accuracy describes the headline rule. - Tests: 32 pure + 9 e2e (stubbed reader/judge) + gateway temperature. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(eval): NamedThingBench reranker on/off paired A/B (rule R1 runner) scripts/r1-namedthing-rerank-ab.ts seeds the NamedThingBench corpus (peeled from the gate test into test/fixtures/retrieval-quality/namedthing/ corpus.ts, byte-identical) into one in-memory brain with real embeddings, runs the 12 questions (optionally the 42 relational ones) under pinned OFF and ON reranker arms, and reports per-query hit@1/hit@3/create_safety with the R1 verdict (PASS iff 0 hit@1 losses and <= 1 hit@3 loss). Exits 2 before spending if the reranker is not ready or any ON row fell through un-reranked. --embed-cache shares query vectors across arms; --stub-embed is the hermetic dry run. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(eval): LongMemEval miss diagnostics (Phase B1) — per-arm gold ranks, miss classes, clause counterfactuals scripts/lme-miss-diagnostics.ts re-creates each strict miss exactly as the harness does (same pages, embed cache, pins) and reports, per missing gold session, vector / keyword / title ranks to depth 200, fused and post-rerank ranks from one hybridSearch under the same pins, and the pre-registered class (absent from every arm; in the vector pool but fused out; reranked out; k ceiling), plus honesty classes when a miss does not reproduce. Hypothesis probes: the second-event starvation signature, the frozen clause splitter (between/and, first…or, before/after, how many … between; guardrails: two content tokens per clause, no split inside quotes or a Capitalized-Bigram, max two) with counterfactual clause embeds served outside the shared cache, and pool-depth vs reranker-depth attribution. Rows carry dev/decision/half-split membership so the fix is chosen on half A and confirmed on half B. Pure core in src/eval/longmemeval/diagnostics.ts; 26 hermetic tests. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(r1): move the seed-contract engine into beforeAll (test-isolation rule R3) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(search): relational-arm rows bypass reranker demotion (search.relational_rerank_pin, default 3) The NamedThingBench reranker A/B (rule R1) showed the shipped `balanced` default collapsing relational queries: "who invested in X" / "who works at X" / "what connects A and B" lost hit@1 on 19 of 39 questions with the cross-encoder on (hit@1 21 -> 3, hit@3 27 -> 5) while the 11 non-relational core questions were unaffected. The reranker scores chunk text and cannot see typed-edge answers, so graph-derived investor and employee pages sink below pages that merely mention the words. Fix: after applyReranker, relational-arm rows are re-pinned in their fused (RRF) order ahead of the reranked text rows, bounded by `search.relational_rerank_pin` (3 in every bundle; 0/off reproduces the old behavior; per-call `relationalRerankPin`), mirroring the alias and exact-lookup tiers that already run after rerank. Pinned rows are stamped `relational_pinned`, preserved through autocut and excluded from its cliff computation (without that, autocut cut them straight back out). Pure no-op for non-relational queries, image modality, and reranker-off paths; `rrp=` folds into the knobs hash under the v29 epoch. Pure module src/core/search/relational-rerank-pin.ts + a hermetic PGLite test on the relational corpus through the real gateway rerank path with an inverted-relevance stub (pin 0 reproduces the loss, pin 3 restores hit@1 on all eight "who invested in" questions; non-relational and reranker-off queries byte-identical). TSV ceilings raised to exact counts. Known limit filed in TODOS (pin only hop-1 rows whose link types match the parsed relation; gate on seed resolution margin). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(r1): --autocut on|off overlay so the ON arm can run in the exact shipped configuration Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(eval): honest eval scaffolds, canary ledger record, ranker-wave TODO filings - Delete the two undispatched scaffolds that returned ok:true for work never run (eval-markdown-greenfield, eval-extract-atoms); eval-schema-authoring keeps its real aggregator/parseArgs and now returns the #4198 not_implemented envelope (exit 1) instead of an inconclusive verdict. - .gbrain-evals/eval-results.jsonl: retrieval canary recorded at this head (recall@10 1.0, first_relevant 1.0, expected_top1 0.857 vs floor 0.85, 14/14 queries). - TODOS: E4 completed; R1 decision recorded (balanced reranker stays ON with the relational pin); expansion + autocut entries marked in progress; six follow-ups filed (LoCoMo/BEAM lanes, run-all wiring, inline judge concurrency, session-diverse arm, named embed-transport hook, per-subcommand registry rows). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: judge lane, miss diagnostics, R1 runner and relational pin in the reference docs; R1 script text + --relational-pin overlay - KEY_FILES: entries for the judge lane modules (judge, judge-lane, qa-accuracy, reader, emit, shared judge-runner + bootstrap), the miss diagnostics tool, the R1 runner and its corpus module; eval-longmemeval entry extended with the reader and judge-lane contracts; gateway entry notes ChatOpts.temperature and ChatResult.responseModel. - eval-bench.md: "Judged answer accuracy (--judge)" subsection with the protocol and every disclosure (official prompts, gpt-4o at temperature 0, data boundary, judge_error class, headline rule, question-sampling CIs, no SOTA claim), flags, say-line, "Diagnosing misses". - RETRIEVAL.md: relational re-pin section verified against the code and carries the paired R1 counts (19/39 and 22/39 losses without the pin; 0 losses with pin 3, autocut on). - FIX_WAVE_BASELINES.md: ranker-wave block with the receipts that exist and refresh commands; pending rows named as pending. - R1 script: usage/header list --autocut and the new --relational-pin N|off overlay (so the no-pin cell reproduces from HEAD); the markdown header reports the arms' actual autocut and pin state. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(search): arm-confidence-weighted fusion knob (search.keyword_arm_confidence_floor, default off) Phase E2 mechanism for the Cat 13 conceptual-recall gap (Voyage space, held-out concepts: bare vector 60.5 nDCG@5 vs gbrain hybrid 53.0; grep-only 52.2 — the keyword arm's noise on paraphrase probes drags fusion below the vector arm). When the keyword arm's top-row margin ratio top/(top+second) is below the floor, the keyword AND title lists fuse at weight 0.5; vector lists untouched; never on relational queries, keyword-only fallbacks, or an empty keyword arm. Statistic and decision live in the pure src/core/search/arm-confidence.ts and compose inside composeFusionLists; hybrid.ts threads the knob and stamps HybridSearchMeta.keyword_arm_confidence {margin_ratio, top_score, downweighted} so the Cat 13 runner can calibrate the floor on the tuning concepts. Default null (off) in all three bundles: the held-out Cat 13 receipt decides the flip. Config key search.keyword_arm_confidence_floor ((0,1] | off); kacf= folds into the v29 knobs-hash epoch. Hermetic tests: statistic, decision gates, an RRF flip on a decoy corpus, byte-identity when off or strong, keyword-only fallback untouched. TSV ceilings raised to exact counts. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(search): metadata boost gate knob (search.metadata_boost_gate: always | lexical; default always) Cat 13 localization (tuning split, re-simulation validated 359/359 against the live order): gbrain's own vector arm ranks the gold concept page well (nDCG@5 60.3) but the live hybrid scores 50.6 because post-fusion metadata boosts — backlink 1.035-1.124x, graph adjacency, recency — promote hub pages above gold concept pages that carry none; in 73 of 105 gap probes the vector arm was the only voter. `lexical` skips the backlink, salience, recency (+chronicle), graph-signal and alias-resolved stages when no strict keyword, title or relational row reached fusion; supersede downrank, exact-match and title-phrase boosts stay. `always` (default in all bundles) is byte-identical to today; the held-out E3 receipt decides the flip. `mbg=` folds into the v29 knobs-hash epoch; per-call `metadataBoostGate`; meta stamps gate / lexical_voted / boosts_applied so vector-only-voter queries are countable before any flip. Pure module src/core/search/metadata-boost-gate.ts; hermetic PGLite test reproduces the hub-over-concept inversion and its fix. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(eval): --search-pin KEY=VALUE on the LongMemEval harness and the R1 runner (generic knob A/B pins, folded into the knobs hash) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(search): flip search.metadata_boost_gate to lexical in every bundle (Cat 13 E3 receipt) Pre-registered Phase E3 rule (written before the held-out run): gbrain nDCG@5 on the 10 held-out conceptual-recall concepts >= 57.0 (E0 53.0 + 4) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice unchanged. Result: 57.8 (off/off) and 57.9 on the shipped default (was 55.8); tuning 57.3 matched the E1 projection; NamedThingBench 50/50, BrainBench PASS same-hash, canary PASS, LME dev slice 40/40 all identical. Stretch (bare vector 60.5) not met and filed. Under `lexical` the post-fusion metadata boosts (backlink, salience, recency + chronicle, graph signals, alias resolution) are skipped when the vector arm was the only voter; `always` restores the pre-wave pipeline. DEFAULT_METADATA_BOOST_GATE stays `always` so a knobs literal without the field keeps its pre-wave hash identity. Tests force `always` explicitly for the pre-wave rows; default rows expect `lexical`. Docs: KEY_FILES entries for metadata-boost-gate.ts and arm-confidence.ts, search-modes knob rows, RETRIEVAL.md gate stage, FIX_WAVE_BASELINES Cat 13 outcome, CLAUDE.md search-mode table row; llms bundle regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(eval): --search-pin flag row, Phase B located-class receipt, R1 closeout, methodology pre-registrations - eval-bench.md Flags table documents `--search-pin KEY=VALUE` (folds into retrieval_config_hash + knobs hash). - TODOS.md: the temporal-reasoning entry records the Phase B diagnosis (misses are the embedding ranking of near-duplicate sessions; fused rank = vector rank; no knob landed) and the R1 note records the Cat 13 reranker rows + the cat13b re-run left for a follow-up. - SEARCH_MODE_METHODOLOGY.md: dev-slice vs decision-set discipline (§3), three new threats (§5), the ranker wave's ten pre-registrations with the outcomes decided so far (§7), LongMemEval-S dataset sha in the footer. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(changelog): draft the 0.48.3.0 ranker-wave entry (Phase A/C/D measured rows pending receipts) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(key-files): relational pin entry states the core-query outcome precisely (0 losses, one hard-negative gain) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(search): autocut off in balanced and tokenmax (rule R2 receipt); replay joins gold from the dataset Pre-registered rule R2 (autocut floor) on the LongMemEval decision set: keep 0.35 iff the shipped default (reranker on, autocut on) scores >= the reranker-only arm - 2 questions with no type losing > 1. Result: 379/470 vs 449/470, paired +0/-68 on the 430 (multi-session -22, temporal -27, knowledge-update -19). The replay from the captured post-rerank pool (validate-live reproduced all 500 live decisions) found no floor in {0.10 .. 0.80} within the guardrail on either seeded half (0.80 still -9, all knowledge-update), so autocut is off in balanced and tokenmax per the pre-registered chain. DEFAULT_AUTOCUT is unchanged for operators who re-enable it; any-hit stayed >= 99.4% at every floor and the mean returned window went 3256 -> 1633 estimated tokens at 0.35, which is the trade documented in the CHANGELOG. Replay fix that the receipt depended on: harness capture rows carry gold COUNTS only, so `scripts/replay-autocut-floor.ts --dataset <longmemeval json>` joins `answer_session_ids` by question_id and a capture with no gold anywhere is refused instead of scoring 0% at every floor; `buildRow` now also emits `answer_session_ids` per row. CLI tests cover the refusal, the join, and a capture question missing from the dataset. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(todos): R2 decided (autocut off), file session-aware autocut, Cat 13 residual and cat13b reranker follow-ups Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(eval): judge-resume rewrites the output atomically; serial tests opt into autocut explicitly Pre-landing review findings (adversarially verified): - `--judge --resume-from FILE --output FILE` re-emits every prior row after the judge backfill, and the emitter opened the file with 'w' first — a kill mid-backfill (Ctrl-C, timeout, OOM) left a 0-byte file and every paid reader row was gone. `makeEmitter(..., { atomicRewrite: true })` now writes to `<file>.rewrite.tmp` and renames over the original on close, so the resume file is intact until the rewrite is complete. Both rewrite call sites use it; `test/longmemeval-emit.test.ts` pins the mid-run state, the rename, idempotent close, and the summary-after-rename order. - Two serial-lane tests inherited the pre-R2 `balanced.autocut = true` bundle default and failed after the flip; they now turn autocut on per call (the relational-pin file tests the pin THROUGH autocut by design; the reranker-integration test passed a non-boolean autocut object that hybridSearch ignores). - Captured `rerank_pool` rows carry `relational_pinned` so the offline autocut replay can mirror hybrid.ts's preserve/score predicates. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(eval,search): pre-landing review wave — receipt pins, judge gate, replay parity, spend-guard reservations, R1 pin guard, doc truth Adversarially verified findings from the branch review (67-agent pass: six read-only reviewers, two refutation lenses per finding, completeness critic), fixed in disjoint groups and re-verified (typecheck, verify 54/54, touched suites green): - Miss diagnostics read the receipt's pins from a nested `run_config.pins` block the harness never writes; they now read the flat `run_config` (topK → top_k, reranker.{enabled,model}, autocut, expansion, budget, embedder; legacy nested block still accepted), with a round-trip test through the real `buildRunConfig`. Before this a reranker-off receipt was re-diagnosed under the balanced bundle with only a WARN. - Judged lane: the publishability gate now uses `qa_accuracy.complete` (judge_errors, skipped_budget AND unjudged all 0); a judge call that throws inside the backfill stamps `judge_error: 'provider_error'` instead of leaving the row silently unjudged; `judge_config_hash` / `mixed_judge_config` derive from the hashes actually present on rows (a homogeneous backfill under a different resolved reader model is no longer "mixed"); degradation gates fold prior rows on every resume, not only with --by-type; `gold_missing_from_haystack` / `slug_collisions` count the same row set on a fresh run and a resume. - Autocut replay mirrors hybrid.ts's predicates for `relational_pinned` rows (preserved through the cut, excluded from cliff math and the top-score histogram); stale "rows carry only gold counts" comments corrected. - Spend guard fails closed in time: a `running` reservation row lands before the command starts and a `done` reconciliation after (shared run_id; sum = reconciled + unreconciled reservations); INT/TERM/HUP reconcile at the estimate; an unwritable ledger refuses the launch. - R1 runner refuses `--search-pin search.reranker.*` overlays (the arm axis) at parse time; parseArgs tests cover --autocut / --relational-pin / --search-pin acceptance and rejection. - Prose truth: README + KEY_FILES + FIX_WAVE_BASELINES + RETRIEVAL + CHANGELOG no longer call autocut-on "the shipped shape"; the relational pin IS an R1 script flag; A1 parity row filled; mode.ts / metadata-boost-gate.ts / test comments say `lexical`; ModeBundle.reranker_enabled doc matches the bundles; eval-bench legacy_rows and Flags-table claims corrected; TODOS R2 entry no longer both decided and in progress; eval-schema-authoring help says the command is not dispatched yet. - Phase A outcome recorded: CHANGELOG "If you run tokenmax" carries the measured numbers (255 → 394 of 470 with the budget knob; plain hybrid 439), bundles keep the legacy weighting, the TODOS entry is DECIDED and the CRAG-style conditional-expansion follow-up is filed. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(eval): Phase A outcome in search-modes, RETRIEVAL, FIX_WAVE_BASELINES, methodology and README (budget knob real but below rule; bundles keep legacy weighting) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(eval): publish the ranker-wave retrieval receipts — release default 449/470 (95.53%), eight arms, per-type table, tokenmax as released CHANGELOG Measured section, docs/eval-bench.md "Current measured result", README eval paragraphs, the company-brain tutorial line, FIX_WAVE_BASELINES (final release-configuration arm + gate D11 PASS on every leg, tokenmax as released) and the CLAUDE.md search-mode table (autocut row) now carry the 2026-09-06 in-repo harness numbers: A1 439/470, A2 449/470, A3 255/470, A4 379/470, A3′ 394/470, A3′R 381/470, tokenmax-as-released 436/470, release default 449/470 (byte-identical per question to A2). The 2026-09-02 sibling rows stay referenced as the prior receipt. llms bundle regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(eval): the judged lane reads whole sessions and the judge respects the provider's token floor Two defects the 25-question judged dry run exposed before the full run spent: - Every judge call failed with provider_error: the official evaluate_qa.py max_tokens of 10 is below the OpenAI API's minimum of 16. JUDGE_MAX_TOKENS is 16 (a one-token yes/no verdict is unaffected) and the methodology note discloses the deviation. - The reader abstained on 11/25 questions whose gold session was retrieved at rank 1: the sanitizer's 4000-char per-session cap (an extractor-era default) cut the answer out of most retrieved sessions (LongMemEval gold sessions run 5–23K chars). renderChatBlock/sanitizeChatContent take the bound as a parameter; the reader passes READER_MAX_SESSION_CHARS (60K, a safety bound above the longest session) so it reads whole sessions, and every row records reader_context_chars / reader_context_sessions / reader_sessions_truncated. READER_PROMPT_VERSION bumps to v3-abstention-fullsessions (the system text and its sha are unchanged). Tests: reader context construction (full session reaches the prompt once per distinct session; only a >60K session is cut; chunk fallback), the sanitizer's per-call bound + truncatedCount, judge token floor. Docs: eval-bench judged-lane protocol paragraph, CHANGELOG judged-lane bullet. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(eval-bench): move the judged-lane protocol paragraph out of the command block into its section Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(todos): file the R1 runner explicit-embedder / fixture-header follow-up Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(eval): same-file judge resumes append as rows land and compact at run end; integer gold answers grade as strings; capture mapper peeled The first judged run exposed two more defects: - A `--judge --resume-from FILE --output FILE` pass wrote to a temp file and renamed on close (the previous fix for the truncation window), so a pass killed by its own `timeout` lost EVERY row it had produced — the bounded resume loop made no progress across three 900-second passes. A same-file resume now always APPENDS: judged backfill rows and retries land the moment they finish as newer duplicates, and `compactJsonlByQuestionId` (emit.ts) rewrites the file atomically to one row per question_id (last wins, first-seen order, stale summary lines dropped, corrupt tail dropped) before the summary is emitted. `readJsonlRows` and `loadResumeSet` read appended files last-wins (a retry supersedes an error row; a later error row re-opens the question). Rewriting into a DIFFERENT file keeps the atomic temp-and-rename path. - 32 of the 500 LongMemEval-S gold answers are integers; the judge's data-boundary escaper called `.replace` on them and the question became an error row (six multi-session rows in the first pass). Golds are coerced to their decimal string at every judge boundary, as the official evaluator's f-string does. - `--capture-pool` row assembly moved to `src/eval/longmemeval/capture.ts` (`buildCaptureExtras`, `poolKey`) to keep the harness under its size cap; the pool-row shape and key template are unchanged. Tests: compaction (last wins, order, summary + corrupt tail dropped, atomic, idempotent, missing file), last-wins loaders, integer gold escaping; the collision parity test expects the compacted file. KEY_FILES documents the append-then-compact contract and the new module. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(changelog): harness bullet notes append-then-compact same-file resumes Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(todos): file the harness actual-cost ledger follow-up Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(eval): publish the first judged answer-accuracy number (433/500, 86.6%) with full protocol disclosure; merge the wave's ledger records CHANGELOG Measured, README "How it measures up", eval-bench "Judged answer accuracy" (result table, evidence-vs-verdict cross-tab, protocol pins), FIX_WAVE_BASELINES and the methodology pre-registration outcome carry the Phase D result: 500/500 judged, 0 judge errors, 86.6% headline (CI 83.6–89.6), abstention 29/30, per-type breakdown; retrieval on the same rows 449/470. The pre-registered ≥ 92% prediction was missed and is published as such; no comparison claim is made against vendor answer-accuracy rows (protocols differ). `.gbrain-evals/eval-results.jsonl` gains the 15 EvalRunRecords the wave's `--record` passes wrote from the pinned worktree (A1–A4, dev sweep, A3′, A3′R, tokenmax-as-released, FINAL incl. its resume-noop passes, D1). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: autocut integration + modes-report tests opt into autocut explicitly (bundle default is off since rule R2) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(eval,search): pre-landing review round two — pin precedence and hashing, resolved-pin reranker gate, atomic summary, image-modality gate exemption, guard hardening Findings from the /ship review (six specialists, Claude adversarial pass, coverage and plan audits; Codex could not run in this sandbox), applied in disjoint groups and re-verified (typecheck, verify 54/54, ~460 targeted tests): Harness (`gbrain eval longmemeval`): - `--search-pin` values are written BEFORE the explicit `--mode/--reranker/ --autocut/--expansion-variant-budget` pins so explicit flags win, matching `resolvePins`; the sorted raw pin map folds into `retrieval_config_hash` (only when non-empty, so every existing receipt hash is unchanged), so a resume can no longer merge differently-pinned runs. - The reranker readiness preflight and the un-reranked-rows gate key on the RESOLVED pin (flag, pin, snapshot or bundle): a reranked mode without its provider key refuses to start (exit 2) instead of quietly scoring un-reranked rows. - A run in which every question errored exits 1 and records `failed`. - `by_type_summary` rewrites are atomic (temp + rename); the dead `atomicRewrite` emitter mode is gone (same-file resumes append then compact). - The inline judge runs in its own try: a thrown judge call stamps `judge_error: provider_error` and keeps the paid reader row. - Pre-v2 resume rows with normalized session ids are mapped back to raw ids before re-scoring (they scored as misses before). - `complete` also requires zero reader errors; `escapeJudgeData` neutralises `< /judge_input>`; diagnostics error rows are secret-redacted; one `rawSessionId`, one judge-error field builder, `hasJudgeAttempt` used; help text interpolates `JUDGE_MAX_TOKENS`; `SEARCH_MODES`, `isAbstentionQuestion` and `normalizeExpansionVariantBudget` replace local copies; a second positional is a usage error; the reader snapshot compares against the normalized model id. Gateway client and trajectory routing peeled into `src/eval/longmemeval/{gateway-client,trajectory-route}.ts`. Search core: - `search.metadata_boost_gate=lexical` no longer skips metadata boosts for image-modality queries (their lexical arms never vote by construction); the decision records `image_modality`. - `parseRelationalQuery` memoizes the default pattern set (it compiled ~10 RegExp objects per call and ran twice per search). Scripts and shared eval modules: - Embedding cache: raw NUL bytes in the canonical-hash literals replaced by `\0` escapes (identical hash), canonical and file hashes stream instead of materialising the whole cache (776 MB in the wave's cache). - Autocut replay: refuses when ANY captured row lacks gold without `--dataset`, invalid floors are usage errors, non-array gold counts as missing; `mulberry32` imported from bootstrap.ts. - Spend guard: traps armed before the reservation row (the SIGTERM flake's root cause), fail-closed when the ledger audit is not numeric, portable control-character escaping, TERM then KILL after a grace period. - Flag registry: `//` and `/* */` comments stripped from dispatch blocks before flag extraction (a comment had given `storage` a phantom flag); registry regenerated. - R1 runner: explicit `--autocut` / `--relational-pin` win over a colliding `--search-pin`. Tests added: parse-args table, run-config loaders, capture extras, splits fixture integrity, relational-intent memoization, search-pin end-to-end, resolved-pin gate, all-errored exit, atomic summary, inline-judge throw, legacy-id resume, duplicate question ids, qa rebuild without --judge, escapeJudgeData variants, reader snapshot, spend-guard audit refusal and tab escaping, replay refusals, registry comment stripping, R1 overlay precedence. Structural test manifest regenerated. Docs: eval-bench, KEY_FILES, CHANGELOG, TODOS (redaction entry closed). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: chunker-version-insert-default pins its 1536-d embedding shape (shard-order dependence exposed by the wave's new test files) The file hard-codes 1536-d vectors but let initSchema size the vector columns from whatever the gateway held; in the reshuffled shard 1 it followed a file that left a 1280-d configuration and every upsert failed with 'expected 1280 dimensions, not 1536'. It passes alone and on master alone. Pin the shape in beforeAll (the pattern consolidate-valid-until.test.ts uses) and reset after. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore: bump version and changelog (v0.48.4.0) VERSION, package.json, the three plugin manifests, the BOOTSTRAP runbook stamp, the regenerated bootstrap template repo and plugin trees move to 0.48.4.0 in lockstep (master shipped 0.48.3.0 while this wave ran). The CHANGELOG entry for 0.48.4.0 landed with the wave's commits. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(todos): file the unit-parallel OOM-rescue detector gap seen in the v0.48.4.0 ship verification Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: update project documentation for v0.48.4.0 Post-ship documentation sweep for the ranker wave. - CLAUDE.md: search-mode table gains the relational_rerank_pin row (3 in every bundle) beside metadata_boost_gate and autocut; the relational retrieval paragraph names the post-reranker pin and its off switch; the "Effective cache availability" note moves back above the cache-key notes it introduces (a master merge had left it below them). - docs/architecture/KEY_FILES.md: the judge entry states JUDGE_MAX_TOKENS 16 (the OpenAI minimum; the official 10 is rejected), matching judge.ts. - docs/eval-bench.md: the like-for-like command comment names this doc's own A1 row (93.40%) and notes the sibling 93.19% receipt reproduces too. - docs/guides/search-modes.md: the knob list says seven, not five. - docs/TESTING.md: the LongMemEval harness entry names the two .slow files that actually exist (the cited test/eval-longmemeval.test.ts did not) and the inventory gains the wave's test files (harness, judge lane, embed cache, diagnostics, spend guard, autocut replay, R1 runner, flag registry, gateway temperature, and the four search-knob pure + hermetic pairs); two long-stale entries fixed (upgrade.test.ts renamed to upgrade.serial in v0.36.1.1; skillpack-sync-guard.test.ts deleted in v0.36.0.0). - llms-full.txt regenerated (bun run build:llms). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: independent doc-review drifts — eval-bench perf-gate test name, CHANGELOG reranker attribution, RETRIEVAL current-result sentence, two env knobs in KEY_FILES Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(key-files): document GBRAIN_LME_DEBUG and the spend guard's kill-grace knob Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(eval): semgrep pass — argv-form git probe in the harness, clause splitter iterates g-flagged literals instead of constructing RegExps at runtime The PR scan attributed three new blocking findings to this branch: detect-child-process on the harness's git-describe helper (execSync with a string command) and detect-non-literal-regexp twice in the clause splitter (new RegExp(re.source, flags) to add the g flag). The helper now runs a fixed git subcommand through execFileSync with an argv array; the splitter's patterns carry the g flag at their literal source and are iterated with matchAll (which clones the regex, so shared literals never leak lastIndex). Behavior is unchanged; the 47 diagnostics/parse tests pass and typecheck is clean. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
ede85e2e8c |
v0.48.3.0 fix: consistent read policies and reliable verification (#4941)
* fix(ci): require executed verification and isolate routing fixtures Remove cached-success bypasses and preserve failed, cancelled, or unexpectedly skipped execution lanes. Require scheduled full-corpus E2E and actual PgBouncer execution, retain logs, and install locked dependencies consistently. Isolate routing fixture provider state and home directories, disable Bun env-file loading in children, and report bounded redacted failures. Keep coverage percentages advisory under the existing graduation rules. * fix(mcp): limit authentication replay and propagate cancellation Refresh and reconstruct the client once only for the SDK's typed HTTP 401. Preserve operation errors and treat other transport failures as terminal. Carry cancellation through discovery, token minting, connection and tool calls, and close clients after failed initialization or aborted requests. * fix(privacy): enforce scoped reads and certify safe search indexes Authorize concrete rows and contributing pages throughout both engines, history, graphs, search enrichment, and holder-dependent calculations. Normalize stored prose before strict protected-section filtering and replace chunks atomically before admitting them to remote retrieval. Disable shared semantic result caching and restrict stored contradiction reports to trusted unscoped local callers. Keep code inspection local-only until its graph expansion can enforce the same complete read policy. Cover source collisions, history, holder restrictions, index rebuilds, normalization, containment, and real HTTP/stdio and database parity journeys. * v0.48.3.0 fix: consistent read policies and reliable verification Synchronize release metadata and generated distribution stamps. Document the required index rebuild, temporary retrieval availability, provider costs, remote salience behavior, and deferred provenance and code-read follow-ups. * v0.48.3.0 docs: align retrieval and upgrade guidance * fix(test): isolate nested E2E coverage output |
||
|
|
8c70f62550 |
fix(storage): scope status pages to repo source (#4763) (#4802)
Co-authored-by: gbrain-contrib <gbrain-contrib@example.com> |
||
|
|
5cfb84f1d3 |
v0.48.2.0 feat(reranker): voyage:rerank-2.5 default, no_key fail-open, readiness surfaces before the ZeroEntropy sunset
Reranker default moves to Voyage rerank-2.5 ahead of the ZeroEntropy hosted-API end date, with a fail-open no_key preflight (one audit row per process, no stderr), a reranker_skipped ranking-only degraded stage, and readiness surfaces in gbrain init, gbrain doctor reranker_health and gbrain search modes (remote callers get the verdict without the host key inventory). Merges master v0.48.1.0 (both degraded-stage vocabularies coexist). Docs: LongMemEval-S re-run at this release (strict recall_all@5 93.19% reranker off, 95.32% with the default reranker; receipts in gbrain-evals) and a present-tense rewrite of README and docs. Pins transitive fast-uri/qs via overrides. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
e9a14c9528 |
v0.48.1.0 fix: community fix wave — 55 PR adoptions + 22 verified issue fixes + 5 review-hardening rounds
Every open community PR triaged and every open issue verified against master: 55 contributor pull requests adopted or reworked with credit, 22 verified issues fixed directly, and five review-hardening rounds (8-finder adversarial review, /ship review army + cross-model Codex passes, targeted test sweep, red team). Every adopted fix carries a regression test proven red at its base. Behavior changes: remote traverse_graph defaults to bidirectional edges at depth 2 with a 5,000-row cap; atom identity folds the source locator (legacy atoms adopted in place); KNOBS_HASH_VERSION 27 -> 28; consolidate take identity drops since_date; pack vocabulary enforced at capture/add_link; frontmatter-typed captures persist their declared type; open-loop extraction never consumes threads while the chat provider is unavailable. Full record: CHANGELOG.md [0.48.1.0]; wave ledger + triage JSON in the PR. Co-Authored-By: 1kuna <1kuna@users.noreply.github.com> Co-Authored-By: avs-io <avs-io@users.noreply.github.com> Co-Authored-By: chrispaterson <chrispaterson@users.noreply.github.com> Co-Authored-By: danwiggins <danwiggins@users.noreply.github.com> Co-Authored-By: DarkNightForge <DarkNightForge@users.noreply.github.com> Co-Authored-By: Grimnoth <Grimnoth@users.noreply.github.com> Co-Authored-By: javieraldape <javieraldape@users.noreply.github.com> Co-Authored-By: jcnouwens <jcnouwens@users.noreply.github.com> Co-Authored-By: jonathanlesh <jonathanlesh@users.noreply.github.com> Co-Authored-By: jpark43 <jpark43@users.noreply.github.com> Co-Authored-By: Masashi-Ono0611 <Masashi-Ono0611@users.noreply.github.com> Co-Authored-By: matteborje <matteborje@users.noreply.github.com> Co-Authored-By: mike-tech-ship-it <mike-tech-ship-it@users.noreply.github.com> Co-Authored-By: miroslavb <miroslavb@users.noreply.github.com> Co-Authored-By: noelboss <noelboss@users.noreply.github.com> Co-Authored-By: rameshbaskaran <rameshbaskaran@users.noreply.github.com> Co-Authored-By: richtheworld <richtheworld@users.noreply.github.com> Co-Authored-By: scottgigante-hubflow <scottgigante-hubflow@users.noreply.github.com> Co-Authored-By: SilverNine <SilverNine@users.noreply.github.com> Co-Authored-By: sprivalov <sprivalov@users.noreply.github.com> Co-Authored-By: taisy03 <taisy03@users.noreply.github.com> Co-Authored-By: thebergerking91 <thebergerking91@users.noreply.github.com> Co-Authored-By: thomasbek3 <thomasbek3@users.noreply.github.com> Co-Authored-By: thomaskong119 <thomaskong119@users.noreply.github.com> Co-Authored-By: time-attack <time-attack@users.noreply.github.com> Co-Authored-By: Tomlebretonxhec <Tomlebretonxhec@users.noreply.github.com> Co-Authored-By: VasconcelosADV <VasconcelosADV@users.noreply.github.com> Co-Authored-By: xavierboes <xavierboes@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
acf58e0eba |
v0.48.0.0 feat(search,context): hybrid relaxed-arm fusion demotion (LME recall_all@5 51.3%→93.2%) + openclaw volunteer arm (Cat 34 push 1.0000) + adaptive-return config plane (#4787)
* feat(context): openclaw volunteer-arm fusion — push recall 0.9063→1.0000 at precision 1.0 The OpenClaw reflex lane ran pointers-only (3-pointer budget) while the claude-code turn-context lane fused pointers + volunteered pages — exactly why claude-code sat at 1.000 push recall and openclaw at 0.9063. All 9 baseline misses were 4-entity turns where the budget crowded out a gold entity (itemization receipt in the wave PR). This fuses the volunteer layer into the openclaw lane via ONE shared primitive: - volunteer.ts: volunteerStage — the resolve-I/O-injected primitive that OWNS its resolve opts (slug-only suppression, wide ungated pool, probe marker); volunteerContext delegates to it, so op/watch/turn-context/ reflex/bench all volunteer identically by construction. - reflex.ts: Arm 2 after the pointer arm — remaining-budget timeout with pointer-only fallback (a volunteer stall never discards resolved pointers), excludeSlugs dedupe, turn-context render idiom, heartbeat counts both arms; volunteered survivors log via volunteer-events under the new in-process 'openclaw' channel (NOT wire-claimable — a hook client must not spoof production attribution). - resolve-ipc(.ts/-binding.ts): probe:'volunteer' request marker; the binding's onDelivered skips probe resolves so the wide ungated pool is never counted as delivered reflex pointers. - config.ts: retrieval_reflex_volunteer kill switch (default on — parity with the shipped claude-code lane) + GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER env override above config; also registers the E5a search.* keys (the sibling commit's registry rows ride here to keep config.ts whole). - adapters/openclaw.ts: 4-turn window (DEFAULT_WINDOW_TURNS parity) + volunteerContext + renderReflexAddition — bench and production consume the same primitive; codex + claude-code rows byte-unchanged. - Same-commit rebank: evals/brainbench/baselines/main.json (openclaw push 0/96 failed; kta/false-fire/isolation hold at 0 on all seams) + floors test openclaw push_recall 0.88→0.95 (new pre-registration, measured-minus-margin) + BRAINBENCH.md seam disclosure. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(search): E5 adaptive-return config plane — keys registered, KNOBS_HASH v27 fold, adaptive-on calls now cache Pre-filed P2 (TODOS write-path E5), plus two cache-honesty fixes the wave's review surfaced: - config registry (rode the sibling volunteer commit's config.ts change): search.adaptive_return{,_entity_max,_other_max,_min_keep}, search.autocut{,_jump,_min_keep,_min_top}, search.crag_{escalation,think} — all read by the search path, none previously settable via config set; crag_think's per-query LLM spend noted at the registration site. - KNOBS_HASH_VERSION 26→27: ar/arem/arom/armk gate params + ari (the query's resolved intent class) fold into the cache key for adaptive-on calls, so gate-on/off, cross-cap, AND cross-intent rows can never cross-serve (the semantic cache admits similar queries — an entity-capped row must not serve a concept lookup). adaptiveReturnOn leaves skipCache: adaptive-on calls cache within same-config same-intent matches. Gate-off calls hash identically to legacy rows. One-time global cache-cold on upgrade (documented pattern, 26 prior bumps). - dedupOpts cache honesty: per-call dedupOpts (result-affecting, unhashed) now skips the cache — a maxPerPage:1 caller was previously servable from a maxPerPage:2 stored page. - dedupOpts walk precedence: the two-pass walk's capFromWalk no longer silently overrides an explicit per-call maxPerPage — tightest wins (min of the two). - AdaptiveQueryIntent gains 'concept' (= the full QueryIntent union); the hybrid.ts coercion to 'general' is gone; cap mapping unchanged in effect (concept → otherMax, the breadth cap). Tests: the three KNOBS_HASH pinning tests bumped with reason strings; new v=27 divergence suite (gate-off==legacy, on!=off, cross-cap, cross-intent). Module-size TSV: hybrid.ts/config.ts ceilings raised, mode.ts new row (reviewer-visible, per ratchet rule). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: 2026-08 fix-wave bookkeeping — skillopt public export (audit 237/237), fence-write kind-union import, TODO filings + staleness fixes - ./core/skillopt export + src/core/skillopt/index.ts barrel (runSkillOpt, scoreSkillOnTasks, loadHeldOut — the surface gbrain-evals cat30–33 consume via fragile node_modules deep imports today). Closes the 2026-08-31 eval-suite audit's single unfixed finding (skillopt-cats-11 → 237/237). Both paired gates updated (public-exports test 23→24 + check-exports-count.sh). - fence-write.ts: hand-duplicated six-kind union replaced with FactKind (drift hazard — the union had to be updated in two places). - TODOS.md: stale CODEX_HAS_HOOKS=false claim corrected (v0.47.9.0 shipped the hooks writer, SessionEnd only); write-path-E5 vs chennai-E5 id collision disambiguated; new filings from this wave's receipts — facts idea-kind gap (P2), reflex knob ablation (P3), search.dedup_max_per_page (P3, receipt-gated), single-pool volunteer micro-opt (P3, rejected-this-wave rationale), LoCoMo lane (P3). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(tests): chase the wave's env contract + fourth knobs-hash pin - codex plugin manifests (root + both persona variants) gain GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER in env_vars — the manifest chases the code (test/codex-plugin-manifest.test.ts derived contract); plugin-tree drift guard green. - test/search/knobs-hash-reranker.test.ts: the fourth KNOBS_HASH_VERSION pin (26→27) the sibling commit's grep missed. Full unit suite (scripts/run-unit-parallel.sh): 25024 pass / 2 fail → both were these; re-verified green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(search): OR-relaxed lexical rows no longer outvote a healthy vector arm (#3617 follow-up) Honest re-baselining for the eval fix wave caught a severe regression the published numbers had hidden: at the current pin, LongMemEval hybrid recall_all@5 measures 51.3% while vector-only measures 93.8% on the SAME imported corpus — the hybrid pipeline was discarding evidence its own vector arm retrieved. Root cause (single-question probe receipt in the wave PR): the #3617 keyword AND→OR zero-strict-recall fallback (ON in balanced) returns OR-of-common-terms rows that RRF fuses at full voting weight; on queries with zero strict keyword recall the relaxed junk outvotes correct semantic results (probed gold at vector ranks 0-2 sank to fused ranks 14-17; disabling the fallback restored ranks 0-2 exactly). The fix keeps the fallback's designed rescue role and removes its veto: - engines (BOTH, parity-pinned): searchKeyword + the title arm TAG fallback rows with SearchResult.keyword_relaxed inside the OR branch. - hybridSearch: relaxed rows vote in RRF only when EVERY vector list is empty (keyword-only mode, keyless installs, embed outages — the noEmbed and vector-failure paths keep them unconditionally). With a healthy vector arm they are dropped pre-fusion. Strict-match rows unaffected. - Same-knobs behavioral change rides the wave's single KNOBS_HASH bump (v=27) so pre-fix cache rows can't serve post-fix lookups. Tests: test/keyword-relaxed-fusion.serial.test.ts (tagging both arms, precision-consumer isolation, fusion demotion, embed-failure rescue) + an engine-parity e2e pin (a missing tag on one engine would silently re-open the bug there). Post-fix probe: hybrid baseline returns gold at ranks 0-1-2, identical to vector. Full-lane re-measurement lands in the wave receipt (Phase 6). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: pre-landing review fixes (ship review army, 16 findings adjudicated) Review army (checklist + testing/maintainability/security/performance specialists + coverage audit at 92%): - security: the volunteer probe wire-claim is now honored only when the request is volunteer-SHAPED (isVolunteerProbeShaped: slug-only suppression + the wide pool cap) — a normal pointer resolve stamping probe:'volunteer' to evade delivery telemetry keeps logging; predicate exported + unit-pinned. crag_escalation's remote-reachable expansion spend documented at the key registration and in docs/operations/spend-controls.md. - correctness-of-tests: engine-parity relaxed-tagging test gains non-empty assertions (was vacuously passable on fixture drift) + a title-arm parity case; PGLite title-arm tagging + adaptive/dedupOpts cache-plane behavior + E5a key registration pinned (coverage-audit tests adopted); 'concept' joins the otherMax cap loop; loadConfig env-fold pinned with a GBRAIN_HOME fixture; flaky wall-clock bound dropped for the functional assertion; D8 walk-cap precedence extracted to pure resolveWalkDedupCap + unit tests. - maintainability: stale adaptive-cache-skip docs fixed at all three sites (return-policy header, adaptiveReturnEnabled, ops/search.ts param note); three stale KNOBS pin titles updated; negative-parse regex deduped into config.ts isEnvDisabled (4 sites); magic 50ms → MIN_VOLUNTEER_BUDGET_MS; withTimeout clears its race timer on settle (a second instance per turn shipped this wave); PGLite volunteer-event logging gap now honestly documented at both sites (direct-Postgres rung only). - filed: lazy OR-fallback rescue (P3, wasted FTS query on zero-strict-recall queries when vector healthy) + Cat 35 judge-calibration hand-scoring (P2, user-time gate) in TODOS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): adversarial-pass batch 2 — both-mode demotion gate, volunteer fail-open, relaxed-row observability, reflex kill-switch parse Cross-model adversarial review (red team + codex inline-diff + claude), all findings verified in code before fixing: - hybrid: the OR-relaxed demotion gate judges TEXT vector lists only — in cross-modal 'both' mode the appended image branch no longer mutes the lexical rescue arm (exported textVectorArmNonEmpty + pure tests) - hybrid: muted relaxed rows surface as meta.relaxed_dropped (count, never a degraded stage — the common case must not collapse the cache TTL); relaxed rows CARRIED on a vector-enabled run stamp keyword_relaxed_carried so the cache write takes the 60s degraded TTL instead of pinning transitional noise for the full TTL under the same v27 knobs hash - reflex: a non-timeout REJECTION of the volunteer resolve no longer destroys Arm 1's resolved pointer block (own try/catch, fail-open) + test - reflex: GBRAIN_RETRIEVAL_REFLEX widened to the same negative parse family as its child switches ('off'/'no'/case-insensitive) — the incident lever was a silent no-op for the most natural spelling + test - volunteer: display whitespace-collapsed at construction (multi-line brain titles can't forge prompt structure; synopsis was already sanitized) + test; VolunteerResolveFn documents the maxPointers contract host resolvers must honor - resolve-ipc-binding: probe shape check documented as ADVISORY telemetry, not a control (deliberate shaping evades the delivery log; server-side volunteer-report kind filed) - brainbench-floors: avg_injected_tokens ceilings per cell (measured+~30%) so a future gate regression can't buy recall with invisible token cost - BRAINBENCH.md: bench-pinned deviations disclosed (user-only replay window vs production mixed-role window; Arm 1 extraction/suppression differences) — parity claim scoped to the volunteerStage primitive; harness fidelity fix filed as P2 (requires its own rebank) - push-context.md: volunteer arm + kill switch + openclaw channel documented with say-to-your-agent block - TODOS: filed server-side volunteer-report IPC kind (P3), IPC probe-field version echo (P3), assistant-role window fidelity (P2); extended the single-pool micro-opt filing with doomed-rung retry + no-cancellation notes Adjudicated no-change: crag key registration adds no remote surface (default off, local admin enablement, spend.posture governs); bench two-primitive orchestration is decision 13 (deliberately ungraded); intent double- classification residual documented in-code (#4356 class, cache-only, self-healing). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.48.0.0 chore(release): version lockstep + CHANGELOG — eval retrieval fix wave Five-file version set (VERSION, package.json, openclaw.plugin.json, both plugin manifests) + BOOTSTRAP runbook stamp + regenerated template/plugin trees at 0.48.0.0. CHANGELOG entry covers the hybrid fusion demotion fix (LongMemEval recall_all@5 51.3% → 93.2% at the RC preview), the OpenClaw reflex volunteer arm (BrainBench push recall 0.9063 → 1.0000 @ precision 1.0), the adaptive-return config plane + knobs-hash v27 cache reset, the skillopt public export, and the adversarial-review hardening batch. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: module-size ratchet — adversarial batch 2 growth (hybrid.ts/types.ts) + config.ts catch-up miscount from the prior fix batch Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: file the expansion small-k dilution finding (P2) + CHANGELOG known-note Same-run RC receipt: hybrid+expansion recall_all@5 49.57% vs plain hybrid 93.19% (208 flips one way, 3 the other; zero expansion errors). Mechanism verified by construction — only the variant vector lists differ between the two adapters per question. No knob change in-wave (frozen corpus); fix candidates pre-registered in the TODO. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(deps): pin browserslist ≥4.28.7 in admin (osv-scan: GHSA-73wf-gq98-2v4g, GHSA-c83g-rgw3-j3cx) Transitive via the babel toolchain in the admin Vite build; two High advisories published 2026-09-01 fail osv-scan on every branch scanned today (not wave-related). Overrides block per the root package.json convention; fresh admin build output is byte-identical to the committed embedded manifest (verified locally — comment-stamp date aside), so no dist/embed regeneration is needed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(plugins): remove duplicate version field left by the master-merge conflict resolution The merge's version-conflict sed rewrote master's 0.47.10.0 line to 0.48.0.0, duplicating the version key in all three hand-maintained plugin manifests (.codex-plugin, .claude-plugin, openclaw). codex's strict JSON parser rejects it ('duplicate field version at line 4'), breaking the real-codex plugin-install + smoke e2e doors. Generated plugin trees were already clean (the generator builds from VERSION); regenerated for good measure. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
d337920c1d |
v0.47.10.0 feat(memory): opt-in ambient memory writeback — MCP instructions, harness blocks, Stop-hook backstop, read-time TTL validity (#4788)
* feat(memory): ambient-writeback core — config resolution, salience gate, instruction template, audience classifier memory.auto_writeback = off|salient|all (default off), dual-plane keys with a DB-authoritative engine path (the machine-global file mirror never enables a per-brain gap; DB-silent + file-enabled = plane_drift held for retry, an explicit DB off is intent), per-engine atomic last-known-good with a file-mirror-off override, and ambientOptsFrom gating the section on the caller's real remember/extract_facts availability. Pure leaves: ttl-parse (shorthand validation, 365d cap), the zero-LLM CJK-aware turn gate with a frozen skip-reason vocabulary, the one ~15-line instruction builder (transient facts always ride remember + ttl — extract_facts cannot set one), and the personal-vs-shared audience classifier (declaration beats a conservative heuristic; the file-mirror declaration speaks for the host brain only). config set/unset on these keys exits non-zero when the authoritative DB write fails, names the converge step on off/unset, and config get reports them DB-first; facts.default_visibility set/unset re-stamps the harness renderer's posture mirror. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(facts): read-time TTL validity — active reads exclude lapsed valid_until in both engines Active-read predicates (listFactsByEntity/Since/BySession, dedup candidates, unconsolidated backlog, facts-health buckets) gain AND (valid_until IS NULL OR valid_until > now()) in lockstep across PGLite and Postgres, pinned by engine parity. valid_until is temporal validity, not retention: history paths (listSupersessions, findTrajectory, --asof, ontology reads with their own predicates) deliberately still see lapsed rows, and nothing is mutated or swept. Consumers aligned to the same active definition: the hot-memory meta hook clamps each cache entry's deadline to the earliest retained valid_until, the consolidator's bucket scan matches its own re-read, and enrichment evidence reads stop feeding lapsed facts. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(mcp): serve the ambient-writeback section on all three transports, gated on real callability buildMcpInstructions composes the base contract with the ambient section; absent/off stays byte-identical to GBRAIN_MCP_INSTRUCTIONS (three exact transport pins). stdio resolves once at boot (restart-to-flip), OAuth per request (write scope + surface filter + bound-client fence — a slug-bound client whose fence denies remember gets no section), legacy bearer per initialize (surface-clamped). extract_facts is advertised only when the caller's actual tool set can call it. dispatch stamps remember_status into the verbs usage sidecar for doctor's honest all-callers counters. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(hooks): Claude Code Stop-hook writeback backstop — bank, harvest, sweep, all fail-open The Stop hook gates the last user turn (zero LLM), secret-scans and banks it as a content-addressed .wb- corpus file whose NAME carries the session's GBRAIN_SOURCE, then asks the serve to extract under its own 2s deadline — exit 0 on every path; the 128KB transcript tail retries once at the 2MB cap when a large tool result parks the user turn past the window. By-design skips (gate reasons, no_user_turn, flush_skip_*) ride heartbeat outcome ok; degraded is infrastructure only. The serve harvest re-checks the authoritative DB gate with strict semantics: only a genuinely-resolved off writes the terminal sidecar — plane drift, invalid mode values, read errors, and non-transport extraction skips (refusal/content-filter/malformed) leave the file for the sweep, which routes each wb file to its filename-banked source (validated; pass source as fallback), applies the same gate, and records skipped_reason in its terminal sidecar. Per-session prompt-harvest cap rides a true-LRU counter map so a long-lived session's burned budget survives churn. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bootstrap): managed instruction blocks, audience-aware consent nudge, memory_writeback doctor check gbrain bootstrap harness installs the shared contract as an idempotent marker-delimited block in user CLAUDE.md and $CODEX_HOME/AGENTS.md (converge-on-off strips it; a failed strip is recorded as a failed receipt target so status/remove keep tracking the orphan; registrar mode never installs blocks for a remote brain; AGENTS.override.md shadowing fails the target loudly). The fire-once consent ask fires on personal brains only — the bootstrap interview's multi-user answer applies its shared declaration the moment it is recorded, before the agent runs init — with a mechanical disclosure whose off switch names both steps and whose TTL line is honest about the backstop lane. Doctor's memory_writeback check reports the resolved bundle, both visibility postures, audience evidence, plane agreement (with the one-line re-sync), installed-block drift (fix names the config set + bootstrap combo that always converges), a lingering block while writeback is off, validity-lapsed counts, and honest 7d counters. Verified live: a real codex session with the managed block saved a stated preference unprompted. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(memory): hermetic ambient-writeback lifecycle fixture + review-fix pins Six-stage end-to-end fixture with zero LLM calls (the test script obeys the served instructions): enable + bootstrap (idempotent re-run byte-identical), initialize carries the section, durable remember round-trips with provenance and NULL valid_until, an acknowledgement produces nothing, a transient fact gets the configured TTL and drops out of recall the moment validity lapses, and an OAuth client sees the same section the stdio lane serves. Review-fix pins cover strict gate semantics, dual-plane declaration routing, the interview stamp, posture re-stamping, degraded harvest arms, and the private-fact remote round-trip boundary. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(memory): ambient-writeback guide + reference-map, skills honesty updates, follow-ups filed New docs/guides/ambient-writeback.md (enablement + who-gets-asked, three activation surfaces, per-harness honesty table, read-time TTL with the existing-brain reclassification note, plane-drift semantics, privacy and visibility, cost posture incl. the corpus retention bound, diagnostics). KEY_FILES carries the module cluster's current invariants; bootstrap, push-context and ambient-recall cross-reference the new channel; README gains the say-block; signal-detector's always-on honesty statement names the activation key and company-brainify stamps brain.audience=shared at handoff (and shields a pre-stamp init with the nudge bypass env). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(memory): close the cross-model re-review findings — off-gate precedence, install symmetry, fail-closed posture, pattern unset, hedged block surface The writeback gate now resolves BEFORE the keyless/kill-switch short-circuits in both the serve harvest and the sweep, so an operator's OFF terminally retires banked turns even on a brain that cannot extract (previously the file lingered eligible for a later re-enable). Instruction blocks install only when the same host's MCP registration confirmed — a foreign-url refusal or failed write no longer leaves a block directing ambient saves at a server the operator never registered. A posture read failure during the first memory.* config set fail-closes the mirror stamp to private instead of letting the absent-stamp default widen an explicitly private brain. `config unset --pattern` sweeps the dual-plane file mirror alongside the DB rows (and finds file-only leftovers of a failed dual-write). The harness block renders the hedged multi-fact line ("extract_facts when that tool is in your tool list") since the engine-free lane cannot probe a clamped serve surface. Module-size ceilings and the skills lock refreshed for the wave's growth. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(memory): round-3 cross-model findings — mount-mirror isolation, per-host registration guard, smoke-rollback block strip Selecting a mounted brain (--brain / GBRAIN_BRAIN_ID / .gbrain-mount) now writes the mount's DB row only across every dual-plane lane (set, unset, pattern unset, the posture re-stamp): the machine-local mirror gates the HOST's Stop hook, so enabling ambient writeback on a team mount can no longer opt the host's own conversations into banking. The codex instruction block gets the same registration guard the claude lane got (a foreign-toml refusal or failed write never leaves a block directing saves at a server this run never registered), and a failed final smoke now strips the blocks this run installed — no instruction block outlives its rolled-back registration. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(doctor): a FAILED instructions receipt target is a standing warn — the strip-failure survivor is never silently healthy The one physical-survival path left after the smoke-rollback strip (the strip itself throwing) leaves a current-looking block on disk directing sessions at a rolled-back endpoint; only the receipt's failed state knows. Doctor now warns on it with the converge command until a bootstrap re-run or --remove clears it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(memory): refresh the generated CLI flag registry + harness size ceiling for the fix waves The flag scanner's facade expansion picks up the converge/remove hints the consent-path messages now print; harness.ts ceiling raised for the round-3 guards (MCP-confirmed check + smoke-rollback strip). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.47.10.0 feat(memory): opt-in ambient memory writeback — MCP instructions, harness blocks, Stop-hook backstop, read-time TTL validity Five-file version lockstep + runbook stamp + regenerated template-repo and plugin trees. CHANGELOG carries the release entry and the enablement block. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: post-ship documentation sync for v0.47.10.0 Catch the late fix-wave behaviors the guide and reference map missed, and one engine-uniformity claim the wave's own docs got wrong: - ambient-writeback.md: doctor's FAILED-receipt-target standing warn and the off-but-still-instructing warn join the Diagnostics section; the harness-blocks surface now names the registration-confirmed install + failed-smoke block strip; the Stop-hook lane is engine-uniform (#4245 landed the URL-keyed IPC listener), not PGLite-only. - bootstrap.md: the Postgres failure-mode row no longer claims the hook IPC socket is PGLite-only — the pre-wired hooks light up whenever a serve for the brain runs. - KEY_FILES.md: memory_writeback doctor bullet carries the failed-target standing-warn invariant. - CLAUDE.md: Reference map row for ambient memory writeback (the guide was unreachable from the dispatcher) + llms regen. - TODOS.md: refresh the stale CODEX_HAS_HOOKS=false premise on the codex boundary-hooks entry; file the volunteer_channels quiet-guidance staleness (code still tells Postgres operators the hook lane can never fire). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deps): pin browserslist >=4.28.8 in admin via override — clears the osv-scan gate GHSA-73wf-gq98-2v4g / GHSA-c83g-rgw3-j3cx (two HIGH advisories against browserslist 4.28.2, fixed in 4.28.7) flagged admin/bun.lock on PR CI. browserslist is a build-time transitive (@babel/helper-compilation-targets via the vite react plugin), so the pin rides the admin package's existing overrides block — the same mechanism the prior @babel/core, postcss and nanoid transitive pins use — rather than becoming a phantom direct dependency. Verified: a temp-outDir vite build succeeds and produces byte-identical asset hashes to the committed admin/dist, so the shipped artifact is untouched. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
81d01622c8 |
fix(backup): no_remote coverage hint also names bootstrap attach for out-of-band-adopted repos (#4746)
* fix(backup): no_remote coverage hint also names bootstrap attach for out-of-band-adopted repos
computeBackupCoverage's bootstrap_workspace no_remote verdict always
pointed at `gbrain bootstrap repo` when receipt.repo_url is unset. But
`bootstrap repo` is only safe when there is truly no git origin yet —
if the workspace's repo was already pushed or adopted out-of-band, it
is guaranteed to refuse with ORIGIN_NOT_EMPTY (assertAdoptableOrigin in
src/core/bootstrap/repo.ts), whose own error message correctly points
at `gbrain bootstrap attach` instead. attachWorkspace's sameWorkspace
branch already reconciles receipt.repo_url from the real git origin on
re-run, so the fix already existed — the coverage detail message just
never mentioned it, forcing a guaranteed-failing command before the
reader could discover the real one.
Update the detail string only (fix_argv stays `bootstrap repo`, still
correct for the common empty-origin case) so the message itself names
`bootstrap attach` as the fallback. No new logic, no subprocess calls
— coverage.ts stays file-plane only per its own header comment.
Blast-radius check: grepped src/ and test/ for the exact detail string
and for no_remote/fix_argv consumers. The only other reader is
src/core/advisor/collect-backup-coverage.ts, which forwards `a.detail`
verbatim into its finding (no separate copy to update); its test
(test/advisor-backup-coverage.serial.test.ts) asserts detail via
`.toContain('no private repo yet')`, a substring preserved by this
change. Added one assertion to the existing coverage.ts test that
already covers this verdict's state/fix_argv.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SsTeKi2oHyw9FNdZAzWgLh
* fix(backup): leave fix_argv null for the ambiguous no_remote case, refine detail wording
Two code-quality review findings on the initial diff:
- The detail text said "already has a git origin configured" which is too
broad — an empty/unpushed origin is still safe for bootstrap repo. Narrowed
to specifically call out the already-pushed/out-of-band case.
- fix_argv stayed ['gbrain','bootstrap','repo'] even though that command is
guaranteed to fail in exactly the scenario this PR targets. Since coverage.ts
is deliberately file-plane only, it can't distinguish an empty origin from
an already-pushed one, so no single fix_argv is correct here. Set it to
null (matching the source_repo case's existing precedent) instead of
advertising a command that's wrong half the time.
- Found and fixed the same issue one hop downstream: the advisor's
collect-backup-coverage.ts had its own `?? ['gbrain','bootstrap','repo']`
fallback for this exact finding, which would have silently reintroduced
the wrong-command bug regardless of the coverage.ts fix.
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
|
||
|
|
6bf8db908c |
v0.47.9.0 feat(memorable): adopt #4537 — trust hardening (consent-before-egress, disclosure stamp, doctor surface) + multi-harness capture (claude-code/openclaw/codex) + e2e (#4591)
* Optional Memorable integration: session receipts, tool-result join, config-gated relay Adds an opt-in seam so an external tool can turn a finished gbrain session into a stored procedure. Everything here is additive and off by default: with `integrations.memorable.enabled` unset, no new work runs and no new process is spawned. What it adds: - `appendSessionReceipt` — an additive, corpus-ready receipt written at session end, carrying real tool-call arguments rather than placeholders. - Tool-result outcomes joined onto captured calls by `tool_use_id`, so a receipt records what actually happened rather than what was attempted. - A config-gated relay at session end. When enabled, the receipt is piped to an external CLI; a missing binary or a spawn error can never kill the hook (the async 'error' event is handled explicitly). - `peekLock` — a pure read of the PGLite data-dir lock, exported as `gbrain/pglite-lock` so a caller can tell "held by a live serve" apart from "available" without taking the lock itself. - `config set/get` support for `integrations.memorable.enabled` on the file plane, so the switch is discoverable through the normal config surface. Docs: a README section and `docs/memorable-agents.md` describing the flow, the consent model, and exactly what leaves the machine. CI: the serial job needed 25m rather than 15m with the added tests, and `run-serial-tests.sh` no longer exits 141 on a green run (SIGPIPE from a closed pipe in the summary path). Scope notes for review: - One new public export (`gbrain/pglite-lock`). `session-receipts` is deliberately NOT exported — nothing outside gbrain needs it. - Two size ratchets raised (`hook.ts`, `config.ts`) rather than silently crossed, per the note in the limits file. - New tests: `test/session-receipts.test.ts` and additions to `test/pglite-lock.test.ts`. * docs: make the Memorable integration discoverable from the docs it belongs in The integration doc landed unreferenced: nothing linked docs/memorable-agents.md, and the per-file index carried no entry for the code the PR added. Both are the paths a reader (or an agent following AGENTS.md) actually takes. - README links the doc from the integrations bullet and from the setup line. - scripts/llms-config.ts registers it in the Optional section, link-only, so it appears on the llms.txt documentation map; bundles regenerated. - KEY_FILES.md gains current-state entries for what the PR added: peekLock and its gbrain/pglite-lock export, the session-receipt JSONL that hook-heartbeat.ts now owns, parseTranscript's toolCalls join, and the single memorableAllowed gate plus the detached relay in hook.ts's session-end path. - hook.ts pointed at a session-receipts.ts that does not exist; the code lives in hook-heartbeat.ts. Docs only, plus that one comment. No behavior change. * Make the Memorable integration installable from the docs alone Setup was undocumented at the only step that matters: neither the README section nor docs/memorable-agents.md said where the `memorable` binary comes from, and the first command in the doc was `memorable init gbrain`. An agent following those instructions on a machine without the CLI has nowhere to go — in practice it went looking for a source repository, and when `init gbrain` could not connect it tried to initialize gbrain instead, which asks for an embedding model and a provider key. None of that is required, and none of it is Memorable's setup. Docs: - Lead with the install: `npm i -g memorable-cli`. Stated explicitly that this is the only supported install and that there is no source repository to look for or build from. - Standalone `memorable init` is now the documented default; `init gbrain` is the opt-in for machines already running an initialized gbrain, with an explicit "if it cannot connect, use `memorable init` — do not configure gbrain, and do not pick an embedding model" note. - New section stating plainly that no embedding model, provider, dimension count or key is ever configured for Memorable: an existing gbrain provider is reused, otherwise the extraction API embeds server-side, and if embedding is unavailable the procedure is still stored with recall on exact + lexical. - New troubleshooting table covering command-not-found, the embedding-model prompt, init-gbrain connection failure, storage without an embedding, missing session receipts and consent refusals. - README's link pointed at a docs page that currently 404s; it now points at the npm package, with the install and the relay opt-in shown inline. Code: - Resolve the CLI before spawning it (`resolveMemorableBin`, in hook-heartbeat.ts next to the receipt code; honors `MEMORABLE_BIN`). spawn reports a missing executable as an ASYNC 'error' event that lands after the hook has written its heartbeat and exited, so "enabled but never installed" looked exactly like "working, nothing to do". It now degrades the heartbeat with reason `memorable_cli_missing`, which `gbrain doctor` surfaces. The async handler stays: an uncaught ENOENT still kills the hook. - Tests for PATH resolution and the MEMORABLE_BIN override in test/session-receipts.test.ts. No behavior change when the integration is off, and no new dependency. * docs(memorable): name the lock-timeout case in troubleshooting A single-writer PGLite brain times out every other caller while one process holds the data-dir lock, and the message does not say who holds it. The lock file names the PID and the subcommand, so point at it — and say why a live holder is never reaped, so nobody tries to delete the lock out from under a running process. * Fix four defects found by independent testing of the Memorable seam An independent tester ran this branch end to end against a real PGLite brain and 12 real transcripts, with measurements and runnable reproductions. Four gbrain-side defects came out of it. Receipt compaction counted lines but never bytes. appendSessionReceipt triggered a full readFileSync above 320 KB but only compacted above 4000 lines. Receipts carry tool_calls_json and measured ~110 KB on average (max 353 KB), so ~3000 of them are 315 MB across 3000 lines: under the line trigger, never compacted, and read whole into memory on every session end (maxRSS 443 MB). Compaction now honours whichever budget binds first, trimming newest-first under a 32 MB ceiling, which also bounds the read itself. The newest entry is always kept — dropping the receipt just written would break the relay it exists to feed. The session-end hook never enabled the secret-scan rule it needed. redactFindings was called with no options, so ScanOpts.highEntropy was undefined and high_entropy_assignment never compiled; only vendor-prefixed patterns were ever redacted. Over 12 real sessions, one carried two live credentials straight through. This is a new exposure surface: the corpus only ever held [tool: Bash] placeholders, so the receipt is the first artifact to persist raw shell. highEntropy is now on for the tool-call pass specifically, which is the one artifact that leaves the machine, and left off for the local corpus pass, which would lose search signal to false positives. That rule could not match its own keywords either. The left boundary [^A-Za-z0-9_] cannot match inside api_access_token or SMTP_PASSWORD, since _ is a word character; and requiring the keyword to touch the assignment missed AWS_SECRET_ACCESS_KEY, where _ACCESS_KEY intervenes. Both are fixed, and the entropy gate still decides, so the wider anchor costs nothing on prose. CORE_PATTERNS are untouched: they keep _ as a word character on purpose. GBRAIN_MEMORABLE=false did not disable — only the literal 0 did. A kill switch that ignores false/off/no fails exactly when someone reaches for it. The enable side is unchanged and still strict. peekLock's documented contract was wrong. A lock file that parses but carries no usable pid returns held:true, which the doc called "not held". The behaviour is correct and deliberate: isProcessAlive treats an unprovable pid as alive, and reporting "not held" would invite a caller to steal a live holder's lock, which is what corrupted catalogs in #2348. Only the doc comment changed. Tests cover each fix, including one that fails without the compaction change and one asserting the camelCase shape this rule deliberately does not reach. * Stop re-recording resumed sessions, and align tool calls with the corpus span Two remaining findings from the independent test pass. A resumed session recorded itself again. session-end runs once per resume, and the corpus file is session-id-keyed and overwritten, so the corpus deduplicates by construction — the receipt did not. Every append also fired the relay, so a session resumed five times paid for five extractions of one trace. content_hash is the exact discriminator: it is the post-redaction hash of the corpus just written, so an identical hash means identical content and nothing new to record. appendSessionReceipt now compares against the newest receipt for that session and reports whether it wrote; the relay is gated on that answer rather than on the gate alone. A CHANGED hash is real appended work and is still recorded and still relayed, so the at-least-once contract for new content is untouched — only exact re-emissions are dropped. The comparison reads a bounded 1 MB tail rather than the whole file. Receipts carry tool_calls_json and the file may reach the 32 MB ceiling, and a full read on every session end is precisely the cost that ceiling exists to avoid. A resumed session's previous receipt is by construction among the most recent, and a miss only means a duplicate is written — the failure mode is the old behaviour, never a lost receipt. The dedup lives inside appendSessionReceipt so no call site can forget it. tool_calls_json could describe a different span than content_hash. In remainder mode the corpus is only the post-boundary tail, while the tool calls were the whole parsed window, so one receipt could carry a hash of the tail beside the calls of the entire session. The parser now returns toolCallTurnIndexes alongside toolCalls — a call is stamped with the turn it sits at — and decideCorpusMode reports the index the written span begins at, so the two are derived from one origin. The positions ride alongside rather than on ToolCallRecord, which deliberately carries no transcript-internal fields. Tests cover each: identical re-emission writes nothing while appended work still records, dedup is per session, positions stay parallel and non-decreasing, and filtering at a boundary drops the pre-boundary call and keeps the later one. * Redact short credential values, and refuse a binary that cannot be run Two more findings from the independent re-test of the Memorable seam. The receipt on disk kept a 16-character SMTP password in plaintext even after the keyword rule was widened. The value floor was 20 characters, so length was doing gating the entropy check exists to do, and real passwords are frequently 12-16. Lowered to 12; the 3.5 bits/char entropy gate still decides, and it holds against the recall signal — zero false positives across paths, commands, git SHAs, connection strings and NODE_OPTIONS-style exports. resolveMemorableBin reported success for things it could not execute. The env branch used bare existsSync, so a DIRECTORY named in MEMORABLE_BIN resolved happily; and neither branch checked the execute bit, so a non-executable file called `memorable` on PATH did the same. In both cases the hook wrote outcome: ok while nothing ever ran — precisely the silence this function was added to remove. Both branches now share one check: a real file, and one this process can actually execute. The execute bit is not meaningful on win32, so being a file remains the whole test there. Tests cover a directory, a non-executable file, and an executable one, so the check is demonstrably not just refusing everything. * Surface the relay's exit status instead of only checking the binary exists The last open finding from the independent report. gbrain spawns the relay detached with stdio ignored — correct, since a session-end hook must never block on or fail because of an external tool — but the consequence was that gbrain only ever verified the binary EXISTED. A `memorable record` that exited non-zero (refused consent, no receipt, unscanned corpus, failed extraction, dead API) was indistinguishable from a successful one, so `gbrain doctor` could report a healthy relay indefinitely while nothing had been recorded for weeks. A shim exiting 42 produced outcome: ok. Rather than wait on the child, which would trade one real property for a cosmetic one, the child reports its own outcome to a file beside the receipts and gbrain reads the PREVIOUS run's line at the next session end. Nothing is ever waited on and the fire-and-forget contract is untouched; a failure becomes visible one session later rather than never. The reason is a short machine-readable code, never text from a subprocess, because it lands in a heartbeat that is counters and reasons. Only the gbrain-spawned path reports: a hand-run `memorable record` is not the relay and has nothing to tell gbrain about. Reporting is best-effort in both directions, so it can never turn a working record into a failing one, and a torn trailing line falls back to the last valid entry rather than hiding a failure behind it. Tests cover never-reported, last-succeeded, a refusal carrying its cause, a failure with no cause, a torn line, and a later success clearing the signal. * docs: carry the Memorable KEY_FILES entries across the rebase The reference entries were rewritten on master during the v0.46.29.0 wave (WSL path translation, the mcp/server.ts transports) on the same lines this branch had extended, so the rebase took master's text and these were restored on top of it rather than resolved by hand inside 500-character entries. Also brings two of them up to date with work that landed after they were first written: the receipt JSONL's byte ceiling and its re-emission check, and priorRelayFailure surfacing the previous relay run's exit status. * refactor(memorable): extract the gate + receipt/relay + redaction helpers into hook-heartbeat.ts (A-1) Pure refactor, behavior-identical (pinned by the untouched hook-command serial suite): hookSessionEnd's Memorable block becomes three shared, individually-testable helpers so the upcoming openclaw context-engine lane and the doctor check consume the SAME code instead of drifting copies. - memorableGateAllowed(cfg): {allowed, reason} — one gate vocabulary (kill_switch | disabled); env can only ever disable, never enable. - redactedToolCallsJson(calls, indexes, startIdx): the security-load-bearing span-filter + highEntropy redaction in ONE place — the duplication was where a future drift would re-open the credential-egress gap. - recordAndRelayReceipt(entry, {spawnFn}): receipt dedup -> prior-run outcome surfacing -> resolve -> detached fire-and-forget spawn; never throws; spawnFn is a test seam so the unit lane never spawns real processes. hook.ts 1620 -> 1590 lines (ceiling 1620 holds, slack 30 < 50). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(memorable): consent-before-egress — gbrain-authored disclosure stamp, CLI-side evidence check, bounded relay-file (F-1) Three trust holes closed, each verified against the memorable-cli 0.3.4 decompile: 1. CONSENT STAMP (gbrain-authored, forge-resistant). Enabling the relay is now a disclosure ceremony: `gbrain config set integrations.memorable.enabled true` renders the canonical disclosure (what leaves the machine, the closed-source third party, full-DB access in gbrain-backend mode, both off-switches) and, on acceptance, writes a consent stamp the gate REQUIRES. The stamp lives in a separate gbrain-private 0600 file (~/.gbrain/integrations/hooks/memorable-consent.json), deliberately NOT in config.json — the external CLI full-file-rewrites config.json on `memorable enable|disable|setup`, which would allow forgery-by-habit, lost-update races, and resurrection after revocation. Scope-binding: the stamp records the disclosure hash + the capture-harness list; widening either invalidates it and forces re-disclosure. Non-TTY refuses without --yes (agent-relay copy printed); set-false and unset both revoke. `memorable enable`'s out-of-band boolean alone can no longer activate the relay (degrade: memorable_disclosure_missing). 2. CONSENT-BEFORE-EGRESS EVIDENCE. The CLI POSTs the trace to its extraction API BEFORE its own consent-checked store, so gbrain now refuses to spawn without positive evidence of Memorable-side opt-in: ~/.memorable/config.json (dated provisional spec target) must show backend local+read-write, or backend gbrain (where the stamp above is the evidence). No evidence => no child process, receipt still written locally, typed degrade (memorable_not_initialized | memorable_consent_off). 3. BOUNDED RELAY FILE. memorable-relay.jsonl (child-appended, never trimmed) is the receipts-file defect class one file over: lastRelayResult read it whole every session end. All three JSONL readers now share one bounded adaptive tail reader; the hook lane (and only the hook lane) trims the relay file on line boundaries — mtime-stale preferred, hard 8 MB force backstop (busy machines never go stale), newest lines always kept. The child appends open-by-path (appendFileSync), so a post-rename append lands in the new file: the residual loss window is one in-flight write. readSessionReceiptsTail is likewise bounded (doctor calls it every run), with an adaptive window so a receipt line larger than 1 MB never reads as an empty file. gbrain config unset integrations.memorable.enabled now routes to the file plane (the pre-fix DB fall-through printed not-found and left the gate live). src/core/config.ts ceiling 1530 -> 1534 (consent-stamp doc comment). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(doctor): memorable_relay_health rung ladder + heartbeat hygiene (F-2) The PR's code comments promised `gbrain doctor` surfaces memorable_cli_missing — nothing read heartbeat reasons at all, so every relay failure mode was invisible. Now: - New engine-free check memorable_relay_health (doctor/checks/ integrations-memorable.ts, pushed unconditionally so it survives --fast and every --scope; registered in OPS_CHECK_NAMES). Ladder: gate off -> quiet ok; enabled WITHOUT the gbrain disclosure stamp -> FAIL naming the exact fix (the `memorable enable` out-of-band state); CLI-side consent absent -> warn; no runnable binary -> FAIL; last relay run reported failure -> warn with the clamped cause; receipts written but the child never reported -> warn (the enabled-but-broken silence this surface exists to catch); healthy -> ok with structured details for --json consumers. - bootstrap_hooks_heartbeat's ok row now names the most-common degrade reason (a window that is 100% one degrade reason used to read as plain 'healthy'). - priorRelayFailure clamps the child-supplied cause to the reasonCode charset ([A-Za-z0-9_.:-]{1,48}, else 'failed') — subprocess text never lands in a heartbeat or doctor message verbatim. - Degrade ordering: memorable_relay_* reasons describe the PREVIOUS session, so recordAndRelayReceipt appends them last and hookSessionEnd applies them after the push section — under first-degrade-wins they can no longer mask a current-session reason like push_unavailable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(openclaw): surface tool calls from session lines — name-only v1, span-stamped (A-2) mapOpenclawLine now extracts {type:'toolCall', id, name} content blocks as ToolCallRecord-shaped {name, input: null} riding OpenclawLineResult, and readOpenclawBoundaryTail returns them with turn-slot stamps (same semantics as the claude-code parser: a call is stamped at the slot it precedes, so a window-span writer filters calls to the same origin as the text). Deliberately NAME-ONLY: the fixture and the dated spec target pin only {id, name}; the args field name and any result block shape are unobserved, and guessing keys (arguments ?? args ?? input) would feed speculative data into an egress payload — v1 ships input:null and no result, pinned by a test that hands the mapper every candidate args key and asserts none is taken. Placeholder-only lines (toolCall, no text) keep their calls via {kind:'skip', toolCalls} — the turn is skipped, the work is not lost. Import adapter behavior unchanged (it ignores the new field); spec-target note updated with the provisional args/result status. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(openclaw): per-compaction Memorable receipts from the context-engine lane (A-3) OpenClaw has no session end, so capture rides the one lifecycle callback it does have: runCompactCheckpoint. After the segment is SPOOLED (durable), the lane runs the same shared chain as the hook lane — memorableGateAllowed (config gate + disclosure stamp; the stamp's harness list now includes 'openclaw', so pre-existing stamps stop validating and re-disclosure is required, exactly what scope-binding is for) → span-filtered redactedToolCallsJson (highEntropy on, windowTurns is a suffix of the tail so the calls share the corpus's origin) → recordAndRelayReceipt (content-hash dedup, consent evidence, prior-run surfacing, detached spawn). Latency posture inside the host's compact() callback [ENG E1]: this lane never trims the relay file (hook lane is the one trimmer) and defers the receipts-file compaction rewrite when the compact deadline is near (appendSessionReceipt {skipCompaction}) — appends only. The whole block is fail-open for the checkpoint: no refusal in it can change checkpoint status. Semantics (documented): one receipt+relay per distinct compaction window; an identical retried compaction dedups by hash; the post-last-compaction tail is never captured (compaction-only coverage, stated in the docs pass). SessionReceiptEntry.harness gains 'openclaw' — deliberately NOT HookIo.harness (widening that union also requires HARNESS_CHANNELS; see the in-code note). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(codex): hook-lane rollout parser + capture-spec dispatch seam, unwired (B-1) The import adapter (codex.ts) deliberately drops tool traffic; the hook lane needs it. Following the openclaw mapper-export precedent, codex.ts now exports a pure mapCodexLine (the adapter is refactored onto it — behavior pinned unchanged by the existing adapter tests) and two new engine-free modules consume it: - transcripts/codex-hook-lane.ts: confineCodexTranscriptPath (the same S3#8 ladder as the claude root, pinned at codexSessionsDir — CODEX_HOME-resolved since the spawner IS codex); parseCodexHookTranscript (ParsedTranscript shape; head+tail over budget so session_meta identity survives; tool calls from the OBSERVED args keys — custom_tool_call.input fixture-verified, function_call.arguments source-verified at tag rust-v0.147.0; parsed tolerantly, raw string kept on non-JSON; NO result join — 0.147.0 persists no success flag on *_output rows and an inferred ok would be a lie; compacted rows recorded as boundary positions); discoverNewestCodexRollout (bounded newest-first walk, id-in-filename match, symlink-reject, 4096 dirent cap — the fallback for transcript_path:null and the seam for SIGKILL'd sessions, since SessionEnd never fires on SIGKILL). - transcripts/capture-spec.ts: the satisfies-anchored per-harness {confine, parse, discover?} record for STDIN-DRIVEN lanes. openclaw is deliberately not a member (in-process trusted-plane lane); unknown/ undefined/opencode resolve to the claude spec — exactly today's behavior, pinned by a golden test. Everything is UNWIRED (dead-code-but-green): hookSessionEnd dispatch lands next so this commit stays reviewable on its own. SessionEnd payload facts cited from the 2026-08-25 observation run against pinned codex-cli 0.147.0 (live capture): {session_id, transcript_path, cwd, hook_event_name, reason} — reason always 'other', rollout flushed pre-hook. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(hook): dispatch session-end capture through the per-harness seam; codex lane live (B-2) hookSessionEnd no longer hard-imports the claude parser: captureSpecFor(io.harness) resolves {confine, parse, discover?} per lane. claude-code behavior is byte-identical (golden-pinned: the untouched hook-command serial suite plus the capture-spec resolution test — undefined/unknown/opencode all resolve to the claude spec). --harness codex now confines transcript_path to the codex rollout store, parses via parseCodexHookTranscript, and falls back to the bounded id-matched discovery when the payload carries transcript_path:null — the fallback is a DEFERRED heartbeat reason (transcript_discovered*), so it is visible without masking a current-session degrade. Source attribution note [OV2/EV4]: session-end never reads GBRAIN_SOURCE (the env tier feeds session-start/user-prompt/stop only, none of which codex wires); the receipt's workspace_root is the runtime stdin cwd, asserted by the new serial matrix. New test/memorable-relay.serial.test.ts: the runHook-driven end-to-end matrix against a stub binary reporting through a marker file — default-off no-op on both lanes, kill switch beats a full opt-in, spawn argv, resume dedup (one spawn per content hash), fire-and-forget (hook returns while a 2s child still runs), out-of-band-enable stays off, codex confinement refusal, codex discovery fallback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(codex): hooks.json writer with the 0.147.0 trust gate — two-file write, live-verified (B-3) Everything here is built on the 2026-08-25 observation run against pinned codex-cli 0.147.0 (live captures + the rust-v0.147.0 source), and the full chain was re-verified LIVE against the real binary with THIS writer's output: trust hash accepted with no bypass flag, hook fired, detached grandchild survived the 3s hard-kill, payload arrived intact. The three facts that shaped the design: 1. hooks.json is TOP-LEVEL DENY-UNKNOWN-FIELDS (an extra key makes codex silently skip the whole file) — ownership rides the one legal metadata slot (description) plus a command-substring token, never a _gbrain key. 2. User-layer hooks are TRUST-GATED and fail SILENTLY: without a matching [hooks.state."<path>:session_end:<g>:<h>"].trusted_hash in config.toml (sha256 of the recursively-key-sorted compact canonical JSON of the normalized handler identity), the hook is listed and never executed, with zero warnings. writeCodexHooks therefore writes TWO files, re-hashes on every command change, keeps OUR trust entry inside a managed marker block (foreign entries survive byte-for-byte), refuses to double-define a foreign-owned table key (a duplicate table is a hard TOML error that bricks codex), and always strip-ours-then-APPENDS so a foreign group's trust index never shifts. The residual index-staleness case (user reorders their own groups later) degrades to silent non-execution — which is exactly what doctor's codex-wired-but-zero-receipts rung names. 3. SessionEnd handlers are hard-killed at 3s — the command captures stdin to a temp file and detaches a nohup grandchild running the real `gbrain hook session-end --harness codex`, so ingest never races the kill. No GBRAIN_SOURCE in the command [OV2]: hooks.json is user-global; everything resolves from the payload at runtime. host-specs gains codexHooksPath() + CODEX_HOOK_EVENTS (SessionEnd only, v1). Unparseable hooks.json is never touched, on write or removal. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bootstrap): wire codex SessionEnd hooks — workspace + harness lanes, consent-gated (B-4) `gbrain bootstrap hooks --harness codex` now installs the SessionEnd capture entry (consent-gated exactly like the claude lane: --no-hooks / HOOKS_CONSENT decline keep the pull protocol), via the ONE writer in codex-hooks.ts — which lands both hooks.json and its config.toml trust entry, since an untrusted entry is silently inert on 0.147.0. The receipt records 'mcp+hooks'; uninstall strips the entry + trust block; the printed copy names the machine-global blast radius (codex hooks.json has no per-project scope) and that this is session-END capture only. The harness lane (`gbrain bootstrap harness`) wires the same entry with TARGET-DERIVED paths (its config.toml target, never the ambient default) and removes it in removeHarness. CODEX_HAS_HOOKS flips to true; the two 'does not wire codex hooks yet' copy strings are updated. Two defects caught by the existing suites while wiring: - the hooks writer's config.toml backup used the same .bak suffix as the MCP block writer's [X5] rollback anchor and clobbered it — a failed smoke would have 'rolled back' to the post-write state; the hooks writer now backs up to .hooks.bak (pinned by the X5 rollback test staying byte-exact); - the writer now mkdirs CODEX_HOME first (fresh machines/tests have no ~/.codex yet). Dispatcher tests gain CODEX_HOME isolation (the writer resolves CODEX_HOME || ~/.codex and Bun caches homedir() — without it the codex-lane tests write the operator's REAL ~/.codex; caught live in this sandbox and reverted via removeCodexHooks). Ratchets raised visibly: bootstrap.ts 2010→2042, harness.ts 1947→1965. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(doctor): codex-hooks-wired-but-never-fired rung (OV8c) Codex hooks fail SILENTLY on 0.147.0 when their config.toml trust entry is stale or missing (e.g. the user reordered their own SessionEnd groups and shifted our trust index) — zero receipts is the only trace. The memorable_relay_health check now warns when a gbrain-owned SessionEnd entry sits in hooks.json but no codex-harness receipt has ever landed, naming the re-trust command. One codex receipt clears it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(memorable): the truth pass — verified-vs-vendor split, per-command egress table, per-harness capture matrix (1d) README: provenance stated plainly (closed-source npm package, third-party publisher, no attestation); a 'what gbrain verifies vs what is Memorable's claim' split (SECURITY.md register — state the guarantee and its limit together); the 'recall is free' claim corrected (a lexical miss with no local embedding provider sends the query text to /v1/embed); full-DB access in gbrain-backend mode named, standalone mode recommended for sensitive brains; the CLI's out-of-band writes to gbrain's config disclosed; the mandatory disclosure step in the install snippet; the per-harness capture matrix incl. the live-verified evidence findings (args-bearing traces store + verify; name-only openclaw v1 traces are refused as no_decisive_steps). docs/memorable-agents.md: a human-facing 'Trust & exactly what leaves the machine' section (per-command egress table, the three-switch consent model, the scope-bound disclosure stamp, local artifacts + purge one-liner, setup/ install-hooks side effects, anonymous key = no deletion path); troubleshooting rows for the out-of-band-enable state, openclaw no_decisive_steps, and the silent codex trust-gate failure. docs/guides/bootstrap.md: codex SessionEnd hook + Memorable relay rows in the what-runs table; degradation matrix updated (codex hooks are wired for SessionEnd; Memorable row added). docs/guides/checkpoint-compaction.md's stale 'codex hook lane is a filed follow-up' corrected. KEY_FILES.md: current-state entries for capture-spec/codex-hook-lane, codex-hooks, the doctor check, and rewritten hook.ts/hook-heartbeat/ context-engine paragraphs. TODOS.md: codex-hook-lane resolved; five new follow-ups filed (openclaw ARGS capture is the P1 — the lane is plumbing- correct but value-dry until the args observation run; codex SessionStart; native opencode/hermes lanes; memorable-cli >=0.3.5 ordering re-verify). llms bundles regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): codex door asserts the trust-gated hooks pair; e2e-map entries for the capture lane The real-codex door's INSTALL tier now pins the new reality: `bootstrap hooks --harness codex` writes the SessionEnd entry + its config.toml trusted_hash into the hermetic CODEX_HOME (set in-process too — the writer resolves CODEX_HOME || ~/.codex, and without the pin the door would write the runner's real ~/.codex), with no GBRAIN_SOURCE in the command. The stale 'gbrain does not wire Codex hooks yet' assertion + docblock line are gone. scripts/e2e-test-map.ts gains narrowing entries: codex-hooks.ts + codex-hook-lane.ts + capture-spec.ts feed the real-codex door (heavy lane) and the hook-under-serve e2e. Unit-tier suites (codex-hook-lane, codex-hooks-writer, memorable-relay.serial) deliberately stay OUT of the map — it enumerates test/e2e files only, and those suites ride the required PR shards/serial lane. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate cli-flag-registry (memorable wave import-graph drift) The generator's facade-expansion text scan now sees hook-heartbeat.ts's 'record --session' argv from commands/config.ts's lazy import (config gains --session) and the codex '--harness' strings from doctor's new check imports (maintain/doctor gain --harness). Registry freshness guard demands the committed file match a fresh run. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: plugin-lane codex receipt records hooks+plugin-mcp (SessionEnd hook now writes on plugin installs) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * ci(heavy): heal the 3-day-red nightly — re-pin the hermes installer digest, re-pin the claude plugin door to 2 tests Two pre-existing master breakages surfaced by this PR's labeled heavy run (the nightly has been failing since 2026-08-23): - hermes door: upstream's install.sh drifted past HERMES_INSTALL_SHA256. Reviewed the fetched script in full (pin flags intact, expected host set, no obfuscation, sudo limited to distro package installs) — the payload tag+commit pins are unchanged, so the installed code was never unpinned. New digest in the workflow + HERMES-CLI-PIN.md with the review record. - plugin doors: v0.46.18.0 (#4251) added the persona-variant install test to the claude door's VALIDATE describe without re-pinning the workflow's exactly-1 pass count; the door has refused green ever since. Re-pinned to exactly 2, deliberately, with the citation. Remaining red is the opencode door's paid leg only: it hard-fails when the ANTHROPIC_API_KEY repo secret is empty — that needs the repo owner (the keyless tier, including the SMOKE, passes and its coverage is banked). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: document-release audit — last stale codex-hooks claims + CLAUDE.md reference-map row - docs/guides/bootstrap.md: the codex door description no longer claims 'gbrain does not wire Codex hooks yet' (it asserts the trust-gated pair now). - BOOTSTRAP_FOR_AGENTS.md: the codex wiring step tells the agent to disclose the machine-global SessionEnd hook (+ its consent gate and off-ramps) instead of claiming pull-only. - CLAUDE.md: reference-map row routing memorable/session-receipt work to docs/memorable-agents.md + the KEY_FILES entries; llms bundles regenerated in the same commit (the freshness test passes). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(memorable): codex joins the consent scope-binding; doc-review gaps closed The cross-model doc review caught a REAL bug: MEMORABLE_CAPTURE_HARNESSES was never widened when the codex capture lane landed, so the disclosure text omitted codex and a stamp accepted today would have validated codex egress the user was never shown — the exact failure scope-binding exists to prevent. 'codex' is now in the list (the disclosure hash changes, so any pre-existing stamp re-runs the disclosure — correct, since the surface grew); the stale producers comment is corrected. Also from the review: two shipped strings pointed at a nonexistent `gbrain bootstrap remove` (it's `uninstall`) — one printed at install, one PERSISTED into the user's hooks.json description; the harness lane's codex hook wiring + .hooks.bak backup + --remove teardown are now documented in the harness-mode section; the local purge one-liner includes the consent stamp (with the note that `memorable disable` alone never clears it); README's 'can never activate the relay by itself' claim is tightened to what is actually true (never before first consent; gbrain-side revocation forces a fresh disclosure). llms bundles regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: ship-review egress hardening — leaf-first redaction, fail-closed relay lanes, in-place codex hook rewrite Pre-landing review wave (6 reviewers + red team), all confirmed findings: - redactedToolCallsJson redacts string LEAVES before serialization: scanning the serialized JSON let quoted secrets ship verbatim (JSON's \" escaping broke the high-entropy pattern — red-team verified with a live repro). - Hook lane fails CLOSED when the secret scanner is unavailable (memorable_relay_skipped_unscanned) — parity with the openclaw lane — and the corpus scan runs highEntropy whenever the relay is on. - OpenClaw lane re-scans the segment text with highEntropy at receipt time and refuses the relay on any hit (the segment rendering itself feeds the ledger hash and cannot change); it also skips the whole block past the compact() deadline, never compacts the receipts file (single-compactor rule), and now trims the relay file (openclaw-only hosts had no trimmer). - Newest-mtime discovery guesses never feed the relay (can be a different, still-running session); payloads without session_id adopt the transcript's own id instead of collapsing onto one unknown.txt corpus; sanitizeSessionId strips leading dashes (argv-flag injection into the third-party child). - Per-receipt harness scope-binding: a receipt from a lane outside MEMORABLE_CAPTURE_HARNESSES is refused (memorable_harness_undisclosed). - codex-hooks writer: re-runs REPLACE our group in place (strip-then-append shifted foreign trust indexes), tolerant [hooks.state] duplicate-header guard, shell-agnostic top-level `sh -c` command (fish/csh $SHELL), removal cleans our description + names the index shift, atomicWriteTextFile reuse, golden known-answer trust-hash vector. - Receipts compaction triggers on the 32 MB ceiling alone (the 320 KB check fired a growing full read on every session end and then did nothing). - Kill switch trims + widens negative spellings (env still can never enable); the [AGENT] refusal copy no longer advertises --yes; the relay child's cause clamp is shared (clampRelayCause, 32 chars) so composite heartbeat reasons stay inside the 48-char bound; doctor treats no_decisive_steps as the documented ok-with-note instead of a standing warn. - parseTranscript/parseCodexHookTranscript gain collectToolCalls (gate-off default path skips tool-call collection + retention entirely). - Regression tests: secret-scan value floor 12 + passphrase/credential keywords; bootstrap-checks top-degrade-reason clause; tool_result join; peekLock no-pid-reads-held; harness-lane codex hook arms. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: ship-review truth pass — widened kill switch, expected openclaw rejection, current-state KEY_FILES Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: bump version and changelog (v0.46.31.0) Five-file lockstep (VERSION, package.json, openclaw.plugin.json, both plugin manifests) + runbook stamp, template-repo + plugin-tree regeneration, lockfile. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(doctor): expected openclaw rejection is a deferred note, never a mask over the codex rung Convergence review caught the previous commit's early return: on a mixed openclaw+codex host the persistent no_decisive_steps state would paint memorable_relay_health green forever while codex hooks sat trust-stale and silently dead — the exact failure the codex_hooks_never_fired rung exists to name. The ok-with-note now surfaces only after the codex rung passes; pinned by a mixed-host test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: delta truth pass for the egress-hardening + deferred-note commits KEY_FILES context-engine entry catches up to the openclaw receipt lane's current posture (block skipped past the compact() deadline, highEntropy re-scan refuses the relay fail-closed, hook lane stays the one receipts compactor, relay file now trimmed from both lanes); the memorable doctor entry and the troubleshooting row state the deferred expected-rejection ordering — the ok-with-note never masks a dead codex trust entry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-model doc-review fixes — windowed codex rung, dupe-drop index shift, collectToolCalls, corpus-scan scope The doc review pass verified every delta claim against source and caught five precision gaps: the codex_hooks_never_fired rung reads a recent receipt window (tail-200), not all history; duplicate-gbrain-group drops CAN shift foreign trust indexes (the writer notes it); both transcript parsers carry the collectToolCalls gate-off skip; the high-entropy scan covers the session corpus text once the relay is on (the child derives its egress line from it); and the memorable doc's doctor summary now carries the same expected-rejection carve-out as its capture matrix. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: sweep the two stale code comments the doc pass flagged Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * ci(doors): split the missing-secret posture — visible skip on PRs, loud-fail stays on the nightly The hermes + opencode doors failed every labeled PR run solely because the ANTHROPIC_API_KEY repo secret is empty — a state no PR author (fork or branch) can fix, and a permanently-red check trains reviewers to ignore the door entirely (the same masking class the doctor's expected-rejection rung fix closed this wave). Now: - pull_request runs: an empty secret is a VISIBLE SKIP — ::warning + a job summary naming exactly what did not run; the paid steps are gated on the paidgate step output. The hermes installer digest/payload/version pins and the opencode keyless tier (5 tests incl. the SMOKE) still run and still gate. The hermes version-drift check moved above the secret gate so drift is caught even on secretless PRs. - schedule + workflow_dispatch runs: unchanged LOUD-FAIL — the owner is the audience there and sees red until `gh secret set ANTHROPIC_API_KEY` runs. PIN docs carry the split posture + a triage row for the skip signature. No change to the paid-sentinel (key present + suite-skipped still refuses green) or to any pin/evidence/scrub step. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(readme): Memorable section leads with what you get and how to use it User feedback: the section was trust-wall-first and it wasn't obvious what Memorable does for you or how to turn it on. Restructured value → usage → fine print without dropping a single trust claim: - Opens with the cold-start moment (third time fixing the same bug class) and a recall example matching the CLI's real output shape. - Adds the missing "Say to your agent" block (CLI-honest form — no skill backs this feature). - Three-step turn-it-on block with the storage-mode fork stated AT the decision point; the mode contradiction the old copy carried (headline promised brain-DB storage while the install block's default was the standalone store) is resolved everywhere: all four claim sites now agree that procedures live on your machine, standalone store by default, brain DB on opt-in. - OpenClaw honesty moved above the fold ("does not yet yield stored procedures"), the gbrain-verified guarantees split into one-per-line sub-bullets, and the trust content quarantined under "The fine print (read before enabling)" — reorganized, none removed. Three-lens critique panel (fresh-reader, accuracy-vs-code, house-voice) ran on the rewrite; all MUST/SHOULD findings folded. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(facts): key the brain_hot_memory cache by engine identity — cross-engine fact leak CI shard 7 failed the remote-privacy-sweep twice with a tell-tale envelope: the sweep's op responses carried ANOTHER suite's seeded facts in _meta.brain_hot_memory, and the four content-thin ops (get_backlinks, get_timeline, get_versions, resolve_slugs) lost their corpus-contact world marker — which for those ops legitimately rides the injected hot-memory of the sweep's own seed. Root cause (ships on master today; our branch's new test files merely reshuffled the shard bin-packing to expose it): the meta-hook's 30s cache in src/core/facts/meta-hook.ts is process-global but keyed only by (source, tier, session, allow-list) — two ENGINES sharing those components serve each other's cached payloads. The memory-verbs-conformance suite warms default::world::null, and on CI's runner pacing (~49s for the 56 preceding files; every engine cold-inits because coverage instrumentation perturbs the migration-handler toString the snapshot hash folds) the entries were still inside their TTL when the sweep's phase R read the same key. Local pacing falls outside the window, which is why the suite passed standalone, in pairs, full-shard, and full-shard-with-coverage here. Fix: fold an engine-identity segment (WeakMap-issued id, last key position so bumpHotMemoryCache's positional matching is untouched) into the cache key. Over-invalidation on bump stays cross-engine — the safe direction. Pinned by a two-engine isolation test; the expired-entry-eviction test now injects its rebuild failure by patching the SAME engine (a different engine is a different key by design and can never read-miss the entry). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ci): coverage-immune snapshot hash + jitter-proof relay timing — the two live flake amplifiers 1. Every CI shard was silently cold-initting PGLite. The snapshot schema hash folded each migration handler's Function.prototype.toString (W0 D5.13), and coverage instrumentation rewrites loaded function bodies — so under `bun test --coverage` (every CI shard) the runtime hash never matched the plain-`bun run` builder's, every engine logged "snapshot stale (schema hash mismatch) — using normal init", and CI timing permanently diverged from local. That divergence is exactly what exposed (and hid, locally) the shard-7 hot-memory ordering failure. The hash now reads the raw FILE BYTES of migrate.ts + pglite-schema.ts — identical under any loader or instrumentation, the same inputs CI's snapshot-cache key already hashes, and the D5.13 handler-edit property holds structurally (handlers live in migrate.ts). Unreadable sources (compiled binary) return null → snapshot skipped, the safe fallback. Verified live: a coverage-instrumented process now computes the exact hash the builder wrote. CI shards get the snapshot fast path for the first time. 2. memorable-relay.serial's wall-clock assertions hardened: the fire-and-forget bound gets real headroom (6s child vs 4s bound, was 2s/1.5s) with the mechanism proof (marker absent at return) unchanged, and the no-second-spawn window waits a full second after the first marker line is durably present instead of a bare 250ms sleep. Shape-guard test re-pins the recipe against an independent computation; pglite-engine ceiling +5 (hash doc); structural manifest regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: justify the shape-guard's source-byte reads (#3665 guard) The file-bytes snapshot-hash recipe pin readFileSyncs migrate.ts + pglite-schema.ts — the one case where reading source text IS the assertion (the hash is defined over those bytes). The #3665 smell guard requires the test-reads-source-ok marker within 3 lines of EACH read; the second read sat 5 lines below the first marker. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * ci(hermes-door): re-pin drifted installer (full review) + skip the unpinned sub-installer; e2e baseline claim - Hermes installer digest drift (the guard's design case): upstream moved past the 2026-08-25 pin. New script reviewed in full (3,639 lines) — door flags intact with hard-fail unknown-flag parsing, outbound hosts unchanged, no obfuscation, sudo distro-only, payload tag+commit pins untouched. Re-pinned HERMES_INSTALL_SHA256; full review record in docs/mcp/HERMES-CLI-PIN.md. - The door now passes --skip-browser --skip-computer-use: the computer-use sub-installer pipes an UNPINNED third-party script (trycua/cua @ main) from raw.githubusercontent.com to bash — the one part of the install the digest + payload pins never covered. Neither feature is exercised by the door, so the surface is removed rather than accepted. - test/fixtures/e2e-unmapped-baseline.txt: bootstrap-real-codex leaves the baseline — our wave mapped it in E2E_TEST_MAP, and master's new claim ratchet (correctly) refuses redundant baseline rows. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): lifecycle codex pin catches up to the hooks lane — and isolates CODEX_HOME Master's new bootstrap-lifecycle e2e (test-gap wave) pinned the codex receipt as detail:'mcp' — pre-Memorable behavior. Since the wave, codex bootstrap also wires the consent-gated SessionEnd hook pair, so the merged truth is 'mcp+hooks' (matching bootstrap-dispatcher/plugin-lane pins). The catch that matters: the test DELETED CODEX_HOME, so with the hooks lane live the pair would have been written into the operator's REAL ~/.codex on any dev machine running the suite — the exact contamination class the dispatcher suite already isolates against. CODEX_HOME is now pinned to a temp dir, and the test asserts the hooks.json + trust block landed there. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(transcripts): capture tool-call arguments and join their outcomes parseTranscript gains a `toolCalls` field: the tool name, the real input arguments, and a structured `{ok}` outcome joined from the matching tool_result block by tool_use_id. Additive — `turns` and every existing field are untouched, so entryToTurn still renders `[tool: name]` and the token-budget-constrained ambient-recall path does not move. Collection is opt-in and off by default. Only a caller passing `collectToolCalls: true` pays for it; everyone else gets `[]` and a parse that costs what it always cost. That is not a style preference: the per-prompt lane parses up to 2MB in front of every prompt, and on a 2MB transcript collecting and copying tool inputs there takes the median parse from 7.6ms to 12.0ms. The session-end lane is the only caller that asks, and only when the operator has opted in. The join runs after the full scan because a result arrives on a LATER transcript line than its call. Sidechain (subagent) entries are skipped exactly as entryToTurn skips them, and the transcript-internal tool_use id is stripped before the record is returned. String values inside an input are capped at TOOL_CALL_VALUE_MAX_CHARS (32,000) with an explicit omission marker. No real command, path or argument is that long; anything bigger is a file body, which entryToTurn discards outright and which this record must not become the way back in. Measured: one 4MB Write produced a 98-byte corpus rendering and a 4MB record before the cap. Eleven tests in test/claude-code-jsonl.test.ts, next to the parser's own, including the default-off case. * feat(hooks): session-end receipt for an opt-in local consumer Session-end already writes a redacted, deduplicated corpus file. This appends one line describing it to a sibling JSONL, so a locally-installed third-party tool can find the finished corpus without re-parsing the transcript or guessing when the hook is done. gbrain itself never reads it. Folded into core/context/hook-heartbeat.ts rather than given a module: it shares that file's directory, its 0700/0600 permissions, its tail-rewrite compaction and its never-throw contract, and it is written from the same session-end path. Redaction is NOT reimplemented — the caller runs both the corpus text and the tool calls through the one existing secret-scan pass, and the receipt carries secret_scan_ok so a consumer can refuse an unscanned one. ONE gate covers the whole thing, checked before any of it does anything: GBRAIN_MEMORABLE not in {0,false,off,no} AND config integrations.memorable.enabled === true Off is the default and off means nothing happens: no file is created, no tool calls are collected, no extra work is done. Only the literal boolean opens it — isConfigTruthy's "true"/"on"/"yes" spellings deliberately do NOT, so a hand-edited config can only fail closed. The env half is a KILL switch, so it takes the same four spellings as search.track_retrieval's in core/last-retrieved.ts rather than answering to `0` alone. Compaction bounds the file on both axes. Line count alone is not a bound: one session with large tool arguments writes a line orders of magnitude past the 80-byte average the line budget assumes, and a handful of those never reach the line threshold, so the file would grow without limit and every later append would re-read all of it. The byte axis trims to half its ceiling, the same 2x hysteresis the line axis already has: trimming back to exactly the ceiling would put the file on the threshold again after every append, and writeHeartbeat's own doc names the read-tmp-rename window as the one place a concurrent O_APPEND line can be dropped. Measured at the budget: 20 rewrites in 20 appends before, 0 after, and 8.2ms per append down to 1.6ms. Tests: the receipt's own file contract read back the way a consumer reads it (test/session-receipts.test.ts), and the gate end to end through runHook in test/hook-command.serial.test.ts, next to the corpus redaction and dedup tests — off by default, every config spelling, every kill-switch spelling, 0600 inside 0700 on disk, and the planted-secret case for the tool arguments. * feat(config): opt-in Memorable relay at session-end, off by default Adds integrations.memorable.enabled to the file plane and, when it is on, detach-spawns a locally-installed `memorable` CLI after the receipt is written. The child reads the receipt and does its own consent checks; gbrain never blocks on it, never fails on it, and sends nothing off-machine itself. `git diff upstream/master -- src/` adds no fetch, no URL and no socket. The key is registered in FILE_PLANE_DOTTED_KEYS, so `set` and `unset` route to ~/.gbrain/config.json together — the invariant that set exists to enforce. It is the first three-part key in that set, and the unset lane destructures two parts, so `config unset integrations.memorable.enabled` drops the whole `memorable` branch. That is fail-closed (absent reads as off) and it is pinned by a test rather than left to be discovered; a leaf-precise unset would be a real design change and should be made deliberately. The enable banner names both off switches and their spellings, because the env one is documented nowhere else in gbrain's own output. A missing executable surfaces as an ASYNC 'error' event, not a synchronous throw, so the handler is load-bearing: without it the whole session-end hook dies on uncaught ENOENT whenever the CLI is absent. One line of src/core/cli-flag-registry.generated.ts changes as a side effect: the generator scans this command's source for --flag literals and the relay's argv contains `--session`, which `gbrain hook` does not implement. Say so rather than hiding it — moving the spawn a module deeper would suppress the line, at the cost of a worse layering. Docs: a README section and docs/memorable-agents.md, both checked against the published CLI rather than carried forward. `memorable graph` no longer exists and is gone; the install source is named, because the bare name on npm is an unrelated abandoned package; and sign-in is required before `init`, so the setup block leads with it. * fix(review): absorption fix wave — tolerant headroom pin, opt-in docs, cap coverage Review-army pass over the #4743 absorption diff: - session-receipts headroom pin: rewrite-counting over 4 appends (the single ino-equality append raced the 32MB ceiling and tmpfs recycles inodes). - ParsedTranscript.toolCalls + KEY_FILES entries state the opt-in contract and the capToolCallInput bound (interface doc said 'raw args', stale twice). - CHANGELOG: credit the absorbed #4743 improvements. - New pins: … marker prefix, depth-cap → null, codex-lane cap (reverting the shared bound on either lane now fails a test). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * ci(hermes-door): re-pin drifted installer (4-commit delta, full review) + de-flake the LockStolenError reason assertion Hermes installer drifted 4b5839eb… → 2076946e… (4 upstream commits touching scripts/install.sh, matched byte-for-byte at a071fc80d). Full 62-line diff reviewed in docs/mcp/HERMES-CLI-PIN.md: Node gate 24.x → 24.11+, a run_locked_uv_sync helper that RESTORES hash-verified locked syncs (security-positive), and a cosmetic SOUL.md text change. Hosts + fetch surfaces byte-identical; all five door flags intact; unknown flags still hard-fail; payload pins unchanged. test/db-lock-fencing.test.ts: the refresher steal test polled signal.reason, but the runtime can deliver aborted=true with reason=undefined when abort() runs in a microtask off a timer tick — the exact behavior isLockStolenAbort's docblock records and production already keys on the flag for. Now reproduces locally 2-3 in 5 runs (previously one loaded-shard sighting). The test now spies on what the refresher PASSES to abort() (deterministic) and polls the aborted flag, pinning the same contract without the untestable read-back. 10/10 locally. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
2a56b51236 |
v0.47.8.0 feat(dream): the write-path distillation wave — buried-signal rescue, mechanical quote repair, idea facts (#4742)
* feat(dream): F6 — synthesize phase spend surfacing
withChatPhase('phase:synthesize') attribution wrap (triage judge +
orchestrator calls; children keep their job:* tag — innermost ALS wins,
minion_jobs stays the child-spend authority). Triage judge usage captured
per call (paid even when the verdict is degenerate) and summed per pass;
child tokens summed from minion_jobs tokens_input/output/cache_read (no
cache-create column exists there — cost_basis labels the estimate).
details.synthesis.spend + triage tokens/cost_usd (null when unpriced,
never fake 0) + children_zero_pages rule-D visibility counter.
Part of the eval write-path fix wave (Cat 35).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(dream): F1b/F4b — mechanical quote verify/repair on dream pages
New src/core/cycle/synthesize-verify.ts: offset-mapped grounding
normalization (normalizeForGrounding — verbatim replacements map back to
original transcript offsets), quote-span extraction (fence/inline-code/
wikilink masked, paragraph-paired, unbalanced skipped+counted), the
repair ladder (exact → normalized → rare-trigram near-match ≥0.8 token
overlap with ambiguity fall-through → strip marks; NEVER fabricates),
and warn-only ungrounded numeric-claim counting (F4b).
Scope: only pages whose slug carries the transcript's content-hash
suffix (page↔transcript binding); pre-existing people/pattern edits are
skipped + counted. Write-back reuses the canonical importFromContent
pipeline (page+tags+chunks+links, hash recomputed, noEmbed — the
phase-end sweep backfills), only when a span actually changed, BEFORE
stampDreamProvenance/reverseWriteRefs so the stamp, the .md file, and
the embedded chunks all carry the repaired body. Fail-open per page.
Kill switch dream.synthesize.quote_verify (default on, registered).
Telemetry: details.synthesis.quote_verify.
Part of the eval write-path fix wave (Cat 35 quote fidelity 45.4%).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(dream): F1a/F3/F4a — quote escape hatch, fact retention, grounding mandates
One prompt commit for the three OUTPUT POLICY changes (the block's exact
strings are test-pinned together):
- Rule 1 keeps the verbatim mandate and adds the escape hatch: quotation
marks ONLY for spans reproducible exactly; otherwise paraphrase WITHOUT
quote marks (F1a — the model was paraphrasing inside quotation marks).
- Rule 6 (new): preserve the specific numbers, dates, amounts, names, and
who-decided-what OF the salient content — salience-scoped so it never
invites routine-logistics noise (protects 0% distractor leakage).
- Rule 7 (new): ground every claim; attribute speculation as speculation;
never state a completion state the transcript does not show (the
killed-process hazard class).
Adds the previously-missing test pins for rule 1 (was untested) + 6/7.
Part of the eval write-path fix wave (Cat 35).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(dream): F2 — verified-segment rescue for the triage gate (buried signal)
A transcript hiding one deeply synthesis-worthy passage inside routine
chatter legitimately reads MEDIUM (0.30-0.69) under the whole-transcript
rubric and never fires the distiller. New src/core/cycle/triage-rescue.ts:
when the score lands in [rescue_floor, threshold), the gate passes iff
>= rescue_min_segments of the judge's own segments verify as normalized
transcript substrings (>=40 chars, deduped) AND content_type is in the
buried-signal allowlist (mixed/reflection/idea/strategy/people — never
routine/technical). Zero extra LLM calls; fabricated segments can't fire
it; works on CACHED v1 verdicts (gate-time only, no TRIAGE_VERSION bump).
THE ONE GATE RULE: passesTriageGate threads into runTriagePass at report
construction, so reports' worth, below_threshold telemetry, dry-run
counts, the synthesize fan-out, AND dream retriage (reconcile-queue
cancels + --audit-rejects sampling) all read one decision — an operator
sweep can no longer cancel exactly the jobs the rescue admitted.
Knobs (registered, clamped, config-zero-tested): dream.triage.rescue_floor
(0.30), rescue_min_segments (2; 0 = kill switch), rescue_content_types
(CSV). Telemetry: triage.rescue_band/rescue_checked/rescue_fired +
per-report rescued/verified_segments flags. buildTriageMapBlock now uses
the shared normalizeForGrounding (one grounding primitive across the wave).
Part of the eval write-path fix wave (Cat 35: 4/20 emission misses all
scored 0.32-0.42; pure-routine maxes 0.15 and never reaches the band).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(dream): F2b — peak-scoring triage rubric, TRIAGE_VERSION 2, buried-signal calibration
Rubric v2 (narrow MEDIUM/HIGH boundary clarification): score by the
transcript's PEAK signal, not its average — a mostly-routine transcript
containing one clearly synthesis-worthy passage scores by that passage.
Segment selection now prefers passages carrying concrete facts and
decisions (feeds the TRIAGE MAP and the F3 retention mandate).
TRIAGE_VERSION 1→2: cached verdicts invalidate; the first post-upgrade
cycle re-judges bounded by dream.triage.max_ms; dream retriage is the
operator remedy (documented at the constant).
Calibration corpus grows a third band: 5 buried-signal fixtures (two
verbatim substantive passages each, planted in routine chatter — the
measured Cat 35 miss class). CI layer pins parse→gate→rescue plumbing;
live layer gains a buried gate-pass assertion and keeps the original
20-fixture >=80% accuracy as the rubric-drift pin.
Live gate receipt (required Phase-4 gate, run at this commit):
band accuracy 95% (19/20; 1 unparseable, correctly uncached);
buried gate passes 5/5 (scores 0.62-0.72 under rubric v2 — the peak
clarification alone lifts the class; rescue remains the backstop).
Also fixes a pre-existing test-infra bug: operator-env-preload's GBRAIN_*
scrub (#4023) silently stripped GBRAIN_TRIAGE_CALIBRATION_LIVE, making
the documented #4152 live-calibration invocation a no-op — now KEEP_EXACT.
Synthesize docblock flow diagram updated with the gate/rescue branch and
the verify pass (stale-diagram rule).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(facts): F5 — 'idea' fact kind + honest low-notability extraction
The extraction taxonomy (event/preference/commitment/belief/fact) had no
home for ideas — the unknown-kind coercion absorbed them as generic
'fact' or the notability filter dropped them (measured: 38.3% idea-kind
recall on the Cat 35 facts lane, the biggest structural gap). Widened
across every seam that must move together: FactKind + ALL_FACT_KINDS
(engine.ts), ALL_EXTRACT_KINDS + extractor prompt (definition inserted
BEFORE the 'fact' catch-all), facts-fence KIND_VALUES + the
FACTS_TABLE_MALFORMED message (the re-parse seam that would otherwise
DROP idea rows), decay half-life (365d, durable like belief/fact),
recall KIND_ICON (💡), fence-write union, and migration v145
(facts_kind_idea_alter — v47 constraint-swap template, idempotent on
fresh/old/re-run, inline DDL widened for fresh installs).
The frozen MEMORY_VERBS remember enum (verbs.ts) deliberately does NOT
gain 'idea' (docs/protocol/MEMORY_VERBS_v1.md enum-freeze rule) — pinned
by a new conformance assertion.
Honest notability: EXTRACTOR_SYSTEM → buildExtractorSystem(admitsLow).
The batch path (no admission) now instructs 'label honestly — still emit
with notability low; the caller decides storage' instead of 'skip
entirely', matching the code-level all-tier retention the batch path
already had; sync's high-only admission keeps skip-low (no wasted output
tokens on rows the filter discards). notability-eval.ts tier definitions
moved in lockstep. Two precomputed prompt variants (cache-friendly).
Forward-only note: once idea rows exist, an OLDER gbrain's fence
re-parse drops them as malformed (v47 notability precedent) — CHANGELOG
carries the note; shared-Postgres mixed-version brains included.
Part of the eval write-path fix wave (Cat 35).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(dream): F-Eval — hermetic $0 write-path mini-eval
A frozen 3-transcript mini-corpus (high / buried / routine control, with
verbatim expected salient units) drives the REAL runPhaseSynthesize on
PGLite: real triage parse + gate incl. the F2 rescue, real oneshot
drain, real quote verify/repair, real provenance + reverse-write. The
only stub is the gateway chat transport (__setChatTransportForTests),
serving a scripted judge + scripted child.
Honest scope (outside-voice amendment): a scripted child cannot measure
prompt efficacy — that stays with the paid Cat 35 runs. This is the
mechanical regression pin: admission (buried passes VIA rescue and is
NOT below_threshold), emission, the repair ladder acting on real pages
(exact kept / drift repaired verbatim / fabrication stripped), the
repaired body reaching the reverse-written .md, salient-unit presence
100%, and the spend/rule-D telemetry shape. Runs in the unit matrix in
~3s, zero network.
Distinct corpus from Cat 35 (no tuning coupling). Part of the eval
write-path fix wave.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(wave): eval fix-wave phase 6 — TODOs, stale-doc fixes, baselines row, knob docs
- Files the five CEO-review-deferred TODOs (E2 chunk overlap, E3 borderline
second-pass, E4 eval-scaffold honesty, E5 adaptive-return config plane +
knobsHash, E7 LLM grounding judge) with wave-receipt context lines.
- Un-stales the entity-salience header + TODOS entry (lowercase limit lifted
v0.46.15, kta 0.150→0.0000 receipt; remaining gaps narrowed honestly).
- FIX_WAVE_BASELINES row: Phase 0 bracketing baseline (dream 70.2%, quote
fidelity 54.2%, emission 16/20 @
|
||
|
|
b2f5ab89d5 |
fix(doctor): multi_source_drift skips git-root-pinned sources instead of false-positiving (#4725)
findMisroutedPages derived every source's expected slug as local_path- relative, unconditionally — it never read the source's persisted slug_root_mode pin (#4342). A source pinned to 'git-root' mode produces subdir-prefixed slugs the sync pipeline actually writes; the check computed the wrong (unprefixed) slug instead, found it at an unrelated 'default' page, and reported false-positive drift whose remediation advice could name that unrelated page for deletion. Conservative fix per the issue's own "Fix directions": for each source, read its persisted slug_root_mode via readSlugRootMode() before walking. A 'git-root'-pinned source is skipped entirely (recorded in the new git_root_skipped field) rather than compared against a slug shape sync never produces. Both doctor.ts and its remote/thin-client twin (doctor/report-remote.ts) surface the skip via a shared note (multiSourceDriftGitRootSkipNote) appended to the existing ok/warn message. True prefix-aware matching (deriving the git-root slug via git-root discovery, mirroring import.ts's importRelPath) is a larger, separate change and is left as follow-up — this stops the dangerous delete advice immediately without attempting it. Fixes #4712. Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
b0f6f67191 | fix: retry Bun DNS timeout embedding errors (#4718) | ||
|
|
f9328f1b59 |
fix(doctor): extract_health WARN message surfaces staleness per kind (#4677)
extract_rollup_7d is a 7-day rolling-window sum (one row per kind per day), so a kind whose last activity was days ago can still show a high halt rate from entirely historical failures with nothing currently wrong -- there was no way to tell "actively failing" from "hasn't run since a bug that's already fixed" from the message text alone. last_updated_at was already computed (MAX(updated_at)) and present in `details`, just never surfaced in the human-readable message. Adds a "Nd ago" / "today" suffix to each kind in the top-3 summary. Pure message formatting -- no new query, no behavior/threshold change. |
||
|
|
2eed7cbed4 |
docs: fix stale KEY_FILES.md entries for git-remote/sync-failure-ledger/code-graph-readiness (#4691)
3 entries had drifted from current src/core behavior — some from a landed fix that never got the doc updated alongside it, some from ordinary code churn since the entry was last written. Docs-only, no source changes. - src/core/git-remote.ts: durableSsrfFlags() usage in pullRepo/fetchRemote (#3836), corrected GIT_SSRF_FLAGS flag list, removed fabricated argv separator, corrected divergenceSafePull's conflict_aborted claim - src/core/sync-failure-ledger.ts: full 23-code classifyErrorCode list (#3875 EMBEDDING_INFRA_CODES), corrected import-file.ts line anchors, flagged MISSING_CLOSE regex drift, corrected decideSyncFailureSeverity's ts-vs-first_seen claim - src/core/code-graph-readiness.ts: 6-state CodeGraphStatus (#3640, #3707, #4352), documented remote?/scoped_source_id, corrected out_of_scope's proof claim, corrected MCP handler location bun run verify: 55/55. bun run build:llms regenerated (byte-identical). check-key-files-current-state.sh: pass. build-llms.test.ts: 12/12. |
||
|
|
aa820c7f99 |
v0.47.7.0 perf(tests): the test-infra speed wave — 3× local suite, shed-order fix, brainbench tiering, e2e snapshot activation (#4717)
* perf(test-infra): shed intra-shard width first, serial LPT dispatch, e2e snapshot activation, verify dedup
run-unit-parallel.sh: bun's --max-concurrency only bounds test.concurrent
tests (1 file in the corpus), so shedding SHARDS first collapsed a 16GB box
to a serial 1x4 run behind a 12000s watchdog — measured 3.25x slower than
4x1 on the same machine (A/B: mc=1 126.07s vs mc=4 126.43s over the same 20
files). Width sheds first now (new pinned case). The no-timeout-binary
fallback watchdog drops a .watchdog sentinel so rc-143-at-cap classifies as
WEDGED instead of a bare hard fail (mandatory regression pin); heartbeat
summaries and per-shard assigned lists are memoized (cache written only on
success, tmp+mv, loud warning on underivable lists).
run-serial-tests.sh: heaviest-first LPT dispatch from the new advisory
scripts/serial-weights.json (fail-soft: corrupt/missing -> discovery order;
sorter is bun -e, no node dependency), 0.05s dispatch poll, per-file
durations banked to .context/serial-durations.txt before the tmpdir trap
destroys them. New pins: LPT order + a corrupt-weights fixture that
distinguishes fail-soft from a leniently-parsed sort.
run-e2e.sh: sources test-env.sh + ensure_pglite_snapshot after the
--dry-run-list early-exit (the env keep-list always intended it; the call
was missing), exported ABSOLUTE for varying-cwd CLI children; header
rewritten (claimed 13 files; actual 223).
run-verify-parallel.sh: drop check:eval-canary (test/eval-canary.test.ts
spawns the identical runner in the unit matrix; CI's verify job and matrix
always run together; package script stays for on-demand). Keep
check:eval-chronicle (CLI surface, not a duplicate).
* feat(test-helpers): shared speed + environment helpers, each with its own unit test
cli-spawn: hermetic async CLI spawns (--no-env-file, DATABASE_URL/remote-
secret strips, SIGTERM->SIGKILL reap incl. the pipe-rejection path),
runCliBatch width-2 bounded pool with kill-and-reap-on-failure, runCliMemo
for read-only calls (argv+home+timeout key, nonzero exits evicted, results
frozen). wait-for: deadline-clamped condition polling (replaces fixed
sleeps). with-snapshot: withColdPglite per-TEST snapshot opt-out (the
migrate.test.ts pattern, extracted). reset-pglite: resetPgliteStateNarrow
with an explicit REQUIRED table list (a default would silently
under-truncate). git-fixture: build-once repo + clean -ffdx reset.
fs-perms + git-stderr-probe: environment probes so must-fail assertions
skip visibly on hosts that cannot enforce them (non-enforcing filesystems,
no crontab, stderr-polluting git PATH shims) while CI keeps full coverage.
* fix(tests): root-cause the extract-atoms shard flake; visible skips for environment-class failures
extract-atoms-chunk-embed (registered P1): a shard-neighbor's provider key
baked into the gateway's captured env snapshot (preload configures with
env: {...process.env}) survives the neighbor's own env restore, flips
isAvailable('embedding'), and the atom import's real embed dies as
BudgetExhausted -> every transcript skipped -> status 'warn' (the
registered signature verbatim). Fix: keyless configureGateway pin +
resetGateway + a self-asserting hermeticity expect. ambient-recall gains
its missing resetGateway (the same leak class, outbound).
Environment-class hardening: 7 must-fail assertions (read-only-dir writes,
chmod-000 reads, rm-failure simulation, crontab registration, raw-git
stderr slices) now test.skipIf on hosts that cannot enforce them — visible
skips instead of 8 hard reds on non-enforcing sandboxes; CI enforces all
three probes so coverage there is unchanged. stats-health-source-scope's
afterAll no longer buries the real error in a TypeError when beforeAll
dies before assigning the engine.
* perf(tests): minimal-form rewrites of the slowest unit files (13 files, assertion parity)
Batched CLI spawns through the width-2 pool, condition polling instead of
fixed sleeps, one engine + reset instead of per-test boots, build-once git
fixtures, in-process seams where a proven one exists (doctor buildChecks).
Solo timings, snapshot active — pass-count parity verified per file:
minions 19.5->11.4s (218/218) - pages-soft-delete 16.2->2.3s (20/20) -
dream 18.2->7.5s (37/37) - migration-orchestrator 10.3->1.2s (4/4) -
cli-help-discoverability 21.1->13.2s (29/29) - doctor-minions-check
8.8->3.0s (9/9) - frontmatter-cli 7.7->1.7s (10/10) - schema-cli
10.4->7.0s (15/15) - skillpack-check 11.6->5.5s (10/10) - init-migrate-only
11.4->6.4s (6/6) - cli-dispatch-thin-client 14.9->12.3s (20/20) -
eval-canary 9.9->8.0s (9/9) - sources-ops (dead duplicate insert deleted,
60/60). migrate.test.ts adopts withColdPglite; writer.test.ts adopts
resetPgliteStateNarrow.
Deliberate deletion, named: sources-ops' per-test source INSERT
(resetPgliteState already re-seeds it). Four further rewrites were
attempted and REVERTED with cause rather than shipped at risk (bootstrap:
version-rewind arcs need cold engines — a snapshot-restored engine does not
replay migrations after a rewind; cli-search-dispatch: measured slower;
ambient-recall-cli + pglite-lock: no measured gain).
* perf(ci): tier brainbench-e2e to its own slow job; make the e2e snapshot restores live
test/eval-brainbench-e2e.test.ts -> .slow.test.ts: at 98s mined it was 10%
of the matrix's entire weight and the hard cap on shard scaling. The
in-process full-corpus test was deleted (CI's brainbench gate runs the same
committed corpus fresh every PR and its baseline compare is the
fixtures-hash drift guard); the independent CLI runs execute once through a
width-2 pool with per-child timeout+reap (123s -> 72s). Wired atomically:
test-shard.sh exclusion, dedicated slow-brainbench-e2e job, test-status
aggregate result check (needs alone does not gate), cache-write dep,
coverage lane + merge manifest, weights key rename.
e2e workflows: PGLite-snapshot cache restores in all five jobs, with
explicit activation steps for the three bare-bun-test jobs (restore without
the env export was dead weight — the engine gates on the var), exported
absolute behind an already-absolute guard. Proactive cold-path audit: 7
in-memory-PGLite e2e files that assert the path TO post-initSchema state
carry per-file opt-outs with one-line reasons.
Ratchets: check-test-isolation.allowlist 51->42 (7 files made compliant by
the rewrites + 2 dead rows); test-weights.json rescaled by measured ratios
for the 13 rewritten files (sources-ops honestly UP); structural manifest
regenerated; the slow-eval upload step's overwrite:true restored (lost to
the job splice — caught by three reviewers on one fingerprint).
* chore: bump version and changelog (v0.47.7.0)
Five-file version lockstep + runbook stamp + regenerated template/plugin
trees + lockfile. CHANGELOG entry for the test-infra speed wave. TESTING.md
rewritten to current state (shed order, watchdog sentinel, serial LPT, e2e
snapshot + SHARD, the new helpers section, three-outlier slow tier, honest
counts). TODOS: 3 flake entries closed with root-cause citations + 1 stale
entry swept; Ships 2+3 continuation, the Phase-2 tail, serial-overlap, and
tier2-decoupling filed as follow-ups.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: update project documentation for v0.47.7.0
Post-ship /document-release sweep. Four stale claims the test-infra
wave missed, all factual current-state fixes:
- KEY_FILES.md: run-e2e.sh added to the test-env.sh/ensure_pglite_snapshot
caller list; run-e2e.sh entry now records the snapshot activation
(post---dry-run-list placement, absolute re-export for varying-cwd CLI
children, per-file cold-path opt-outs).
- CONTRIBUTING.md: test:serial comment no longer claims --max-concurrency=1
(the serial lane is pooled per-file processes, heaviest-first).
- docs/eval-bench.md: the retrieval canary is CI-gated via
test/eval-canary.test.ts in the unit matrix; check:eval-canary is the
on-demand package script, deliberately out of the verify battery.
- TODOS.md: the open bench-baselines entry's canary cross-reference
updated to the same current state.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: cross-model doc-review fixes for v0.47.7.0
Review pass (Claude subagent; codex errored on sandbox exec) verified
against the shipped diff:
- Lane counts: the slow-brainbench-e2e job makes 14 PR-corpus coverage
lanes / three dedicated slow jobs (TESTING.md x2, KEY_FILES.md
coverage-cluster entry).
- TESTING.md verify row: singular "PGLite-booting chronicle eval check"
now that the canary left the battery.
- TESTING.md serial row: cite the run-serial-pool.test.ts pin for LPT
order + corrupt-weights fail-soft.
- TESTING.md helpers: document withSnapshotValue + clearCliMemo; scope
the unit-test claim honestly (5 speed helpers have their own tests,
the 2 environment probes are exercised through consumers). Same
honesty fix in the CHANGELOG entry.
- CHANGELOG numbers match the measured timings: "up to 3x faster on
memory-constrained machines" (the 3.25x case was the shard-collapse
box), rewrite range 1.2-8.6x (was 1.5-8x).
- CONTRIBUTING: verify battery is 50+ checks (the script's own header;
CHECKS array is 54).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
7b7921d861 |
docs: post-release audit for the v0.47.6.0 community fix wave (#4701 follow-up) (#4703)
* fix(bootstrap): repair the pre-v143 dream_verdicts upgrade wedge on Postgres (#4657) The embedded Postgres schema creates dream_verdicts_expires_idx on expires_at, but the column only lands via migration v143 — so any brain at schema v30-v142 wedged on connect before migrations could run. The forward-reference bootstrap now probes for the gap and adds the column (nullable + SET DEFAULT as separate statements so existing rows keep their judged_at-derived backfill), with v143 remaining the source of truth for backfill/NOT NULL/index. Class closure (4th recurrence of #2537/#2703/#4477): the schema-coverage suite now parses the POSTGRES blob's CREATE INDEX references too, so a blob-only forward reference fails locally at PR time instead of only on the DATABASE_URL e2e lane. Pre-v143 convergence pinned by a live e2e case (red-proven against the unfixed bootstrap). * fix(dream): harden the expires_at upgrade window (both engines) Adversarial review of #4657: if v143 fails mid-upgrade (the CLI warns and continues on migration errors), NULL expires_at rows previously read as permanent cache misses — silently re-judging the whole corpus with paid LLM calls — and the sweep never deleted them. getDreamVerdict now treats NULL as a pre-TTL hit on both engines (v143 stamps those rows when it succeeds). v143 also sets the column DEFAULT before its backfill so a legacy writer racing the upgrade can't insert NULLs between the backfill and SET NOT NULL. The bootstrap banner no longer mislabels newer brains as pre-v0.21. Module-size: both engine ceilings +1 (the NULL-tolerance SQL comment), reviewer-visible in scripts/module-size-limits.tsv. * docs: KEY_FILES bootstrap entry current-state + schema-coverage DDL-forms follow-up TODO * chore: bump version and changelog (v0.47.5.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-check pass for v0.47.5.0 — TESTING.md two-blob bootstrap gate + KEY_FILES v143 invariants TESTING.md: schema-bootstrap-coverage entry now describes both halves (PGLite registry + the Postgres-blob CREATE-INDEX class-closure gate) and the postgres-bootstrap e2e entry now lists the wedge-class convergence cases and the standalone db.initSchema path it actually covers. KEY_FILES.md: migrate.ts entry gains the v143 clause (statement-order invariant, Postgres bootstrap probe, NULL-tolerant read predicate). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: apply doc-review findings for v0.47.5.0 — probe-set superset, standalone-path honesty, e2e/TTL test entries KEY_FILES.md: postgres-engine.ts entry no longer claims the same probe set as PGLite (Postgres carries blob-only probes); forward-reference-bootstrap entry states plainly that the standalone db.ts:initSchema path does not run migrations and why that is safe. TESTING.md: drop the unsupported fresh-install no-op claim on the postgres-bootstrap e2e entry and add the dream-verdict TTL contract test entry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: normalize stale take bigint rows * fix(takes): normalize proposal bigint rows Refs #4634. * fix(takes): parse --limit/--offset in takes list (#4629) The takes_list operation has exposed limit (default 100, cap 500) and offset since v0.28, but the CLI's cmdList never parsed the flags — every `gbrain takes list --limit N` silently ran with engine defaults. Parse both (same validation shape as `takes propose --limit`), pass them through to engine.listTakes, document them in the usage text, and regenerate the CLI flag registry (--offset is new to the takes scan surface). Tests cover --limit capping, --offset paging with and without --limit, and the unchanged bare `takes list` path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(json): recover JSON from reasoning models that emit a <think> block Models with visible chain-of-thought (DeepSeek-R1, MiniMax M2.x/M3, and any model configured to show thinking) emit reasoning in the SAME text channel as the answer, before it. They also routinely draft their JSON while reasoning, so that block contains braces and brackets. This defeats the substring-scan strategies in all three JSON extractors: parseLlmJson /\{[\s\S]*\}/ spans from the first brace INSIDE the reasoning to the last brace of the real answer facts extractor the {"facts":...} scan starts inside the draft atoms extractor indexOf('[') finds a bracket inside <think> In each case a perfectly good response parses as null / "malformed output". The callers then treat it as an empty extraction or burn a retry LLM call that fails the same way. Measured on a MiniMax-M3-backed brain: a 38.2% atom halt rate, and 50 malformed-output fact extractions in 24h. Adds stripReasoningBlocks() and wires it into all three as a fallback LADDER rather than a pre-filter: 1. parse the raw text exactly as today 2. only if that fails, strip reasoning blocks and retry once so behaviour for models that never emit <think> is byte-identical, a payload that legitimately contains the literal string "<think>" still parses, and the atoms extractor returns its ORIGINAL failure reason when the retry also fails. Text with no reasoning block strips to itself, so the success path is unchanged. Handles both a closed <think>…</think> pair and a truncated block the model opened and never closed (output budget exhausted). Tests: 11 new cases covering both block shapes, answer-vs-draft recovery, the ladder's byte-identical passthrough, and both extractors. Existing suites pass unchanged (facts-extract 9, extract-atoms-failure-classes 17, think-pipeline 40, extract-conversation-facts 74). * fix(parser): report generic chat unavailability Refs #4635. * fix(minions): gateway-native subagent path fast-fails on prompt-too-long The legacy raw-Anthropic-SDK subagent path (agent.use_gateway_loop=false, the default) explicitly classifies a 400 "prompt is too long" error as terminal via isPromptTooLongError() -> UnrecoverableError, so the worker routes the job straight to `dead` instead of retrying up to max_stalled (comment cites preventing "the v0.30.x dream-cycle queue-clog"). The gateway-native path (gatewayToolLoop(), required for any non-Anthropic model and increasingly the live path as this fork migrates providers) had no equivalent: its wrapper runLoopConvertingLeaseLoss only re-classified lease-loss errors and re-threw everything else unmodified. A prompt-too-long condition on a gateway-routed job was retried like any other transient failure -- recreating the exact queue-clog class the original fix (#754) closed, just for jobs on the newer path. isPromptTooLongError() now walks a bounded (depth-3) .cause chain in addition to the object it's given directly: gateway.chat()'s catch boundary wraps every error via normalizeAIError(), which copies only the OUTER message onto the new AIConfigError/AITransientError and stores the raw provider error on .cause. Without the cause-walk, the SDK's actual wire shape (the phrase living on the inner .error.message field, per this file's own existing isPromptTooLongError unit tests) would silently fail to match post-wrap on the gateway-native path. A sibling extractPromptTooLongDetail() shares the same walk to surface the matched provider detail (e.g. "prompt is too long: 1707509 tokens > 1000000 maximum") in the UnrecoverableError message, instead of the generic outer normalizeAIError() wrapper text (e.g. "BadRequestError") -- the detail an operator actually needs to diagnose a dead-lettered job. Verified via three rounds of positive control, each isolating one fix: (1) reverted runLoopConvertingLeaseLoss's call site entirely, observed the regression test fail with the raw provider error propagating uncaught through the full production call chain (chat -> toolLoop -> runLoopConvertingLeaseLoss -> runSubagentViaGateway -> subagentHandlerInner -> subagentHandler); (2) reverted only the .cause-walk (keeping the call site), observed the same test fail on a realistic Anthropic-shaped error whose message lives on .error.message, not the outer .message normalizeAIError() copies; (3) reverted only extractPromptTooLongDetail, observed the strengthened assertion fail with the generic wrapper text instead of the token-count detail. Each revert was restored and re-verified green before proceeding. The regression test exercises the real production error boundary via __setGenerateTextTransportForTests (chat()'s own try/catch -> normalizeAIError()), not the shallower __setChatTransportForTests seam, per code-quality review feedback that the shallower seam would let the test pass without actually proving the gateway path is fixed. Both isPromptTooLongError's classification and extractPromptTooLongDetail's message-surfacing gap, and every fix here, were caught by two rounds of independent maintainer-lens + code-quality review during this PR's own development (three review rounds total, final verdict SAFE with no remaining Critical/Warning findings). * fix(minions): oneshot dispatch path fast-fails on prompt-too-long (#4674) Sibling to #4664 (gateway-native loop path): runSubagentOneshot shares the same gateway.chat() entrypoint and therefore the same normalizeAIError()-wrapped error shape, but its catch rethrew every non-abort error unclassified. A prompt-too-long condition on the oneshot dispatch path retried like any other transient failure up to max_stalled, recreating the same dream-cycle queue-clog class the legacy and gateway-loop paths already fast-fail on. Applies the same isPromptTooLongError()/extractPromptTooLongDetail() classification #4664 adds, at the oneshot catch site. Regression test added to test/e2e/subagent-gateway-path.test.ts, red-green verified (fails with AIConfigError pre-fix, passes with UnrecoverableError post-fix). * fix(mcp): deliver agent contract on initialize (#4642) (#4643) Adopted from PR #4643 (author original4422 / Daniel Peng), applied as the author's own resolution against master (second-parent diff of the PR's merge commit). - New src/mcp/instructions.ts: compile-time GBRAIN_MCP_INSTRUCTIONS agent operating contract (~250 tokens), no runtime filesystem dependency. - Returned from ALL THREE initialize transports: stdio SDK server (src/mcp/server.ts), OAuth per-request SDK server (src/commands/serve-http.ts), legacy raw-HTTP initialize (src/mcp/http-transport.ts). - put_page op + content param descriptions now state the write REPLACES the entire page (read canonical content first via get_page include_content:true) — closes the silent-data-loss confusion (#4632 is a dup of #4642). - docs/TOOL_CATALOG.md regenerated; KEY_FILES.md entries updated. - Pin tests: stdio getInstructions e2e (serve-stdio-roundtrip), raw-HTTP initialize instructions assertion (http-transport), put_page replace-warning description pin (mcp-tool-defs). * fix(cli): report models.dream.extract_atoms in `gbrain models` (#4662) `gbrain models`'s per-task routing report omitted `models.dream.extract_atoms` even though `runPhaseExtractAtoms` reads that config key directly as a real, separately priced routing decision — operators had no way to see or verify extract_atoms routing via the standard diagnostic. Adds the entry via a shared `resolveExtractAtomsModel()` (extracted from `runPhaseExtractAtoms`) that both the runtime and the report call, rather than routing the report through the generic `resolveModel()` chain — extract_atoms's actual resolution is narrower (DB config -> key-aware `resolveTierDefault('utility')` only; it does not honor `models.tier.utility` / `models.default` / an env var the way the generic chain does), so reporting via the generic chain could show a value diverging from what extraction actually uses. The extraction keeps the phase's existing fail-soft contract: all per-run config reads stay inside the single try/catch that falls back to safe defaults on any config-read failure, pinned by a regression test (verified via positive control: reverting to the model-read-outside-try shape makes the new test fail with the simulated config error; restoring the fix makes it pass). Also refreshes two stale comments (extract_atoms routing is configurable and key-aware, not hardcoded to Haiku), the KEY_FILES.md per-task-route count, and CLI_FLAG_REGISTRY (models.ts's new extract-atoms.ts import pulls in an existing "--drain" comment there via the generator's documented one-level prose-bleed scan). * fix(embed): honor backfill pricing overrides (#4571) * test(embed): pin fail-closed boundary for explicit caps on unpriced models (X10) Boundary test for the #4571 adoption: uncapped-with-warning applies ONLY to the implicit $10 default cap. An EXPLICIT operator-provided embed.backfill_max_usd with an unpriced embedding model fails closed (TX2 no_pricing -> budget_exhausted, zero work) — including the corner where the explicit value numerically equals the $10 default. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(facts): honor operator pricing in conversation backfills Refs #4633. Adopted with fixes on the wave branch: kept master's link_resolution.cross_source registration while inserting the pricing.overrides key after spend.posture (KNOWN_CONFIG_KEYS conflict), restored the blank line the PR deleted in extract-conversation-facts.ts, and raised the config.ts + extract-conversation-facts.ts module-size ceilings by the one real line each file grew. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pricing): update gpt-5.6-luna to post-cut rates (#4560) OpenAI cut gpt-5.6-luna pricing by ~80% on 2026-07-30 to .20 in / .20 out. CANONICAL_PRICING still carried the launch rate (.00/.00), causing every budget gate to throttle at a fifth of the operator's intended ceiling. * chore(pricing): refresh gpt-5.6-luna price_last_verified after live verification (#4560) Verified 2026-08-29 against OpenAI's official pricing docs (https://developers.openai.com/api/docs/pricing, the redirect target of platform.openai.com/docs/pricing): gpt-5.6-luna Standard tier lists $0.20 input / $1.20 output per 1M tokens — matching the #4598 adoption exactly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): validate put_page slugs at the op boundary (#4665, with sync-slugifier compat widen) Adopt PR #4665: put_page now runs validatePageSlug before allow-list, dry-run, or write handling, so malformed slugs (Dream-style spaces, traversal, control chars) fail the individual tool call instead of entering the database. Applies to both MCP and trusted local CLI callers. Required fix on top of the PR: as submitted it broke put_page round-trips for slugs the repo's own sync slugifier deliberately produces (slugifySegment preserves '.' and '_': notes/v1.0.0, people/my_file_name). validatePageSlug's LOCAL segment grammar in src/core/ops/context.ts is widened so '.' and '_' are allowed as segment-CONTINUATION characters only (word-char lead preserved, so dot-led segments — '..' traversal, '.hidden' — and every H5 rejection: backslash, %2e/%2f encodings, control chars, RTL overrides, spaces — stay rejected). The shared PAGE_SLUG_SEG in src/core/cjk.ts is untouched: cite-render, SlugRegistry, and the dream-cycle SUMMARY_SLUG_RE consume it with different semantics. Tests: put_page ACCEPTS notes/v1.0.0, people/my_file_name, and CJK slugs; still REJECTS spaces, dot-led segments, traversal, and control characters — at both the op level (operations-allow-list) and the unit level (file-upload-security H5 suite). Co-Authored-By: boundless-forest <boundless-forest@users.noreply.github.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(todos): file the fix-wave follow-ups (pricing sweep, think sweep, #4599 instrumentation, #4616, terra/sol verify, hoist, surface-aware MCP, per-source exclude, dating note, slug unification) + September-removal addenda * fix(bootstrap): codex http_headers auth shape for codex-cli >=0.149 (#4574) codex-cli >=0.149 rejects an inline `bearer_token` for streamable_http servers AT CONFIG LOAD, bricking every Codex session on the machine — and the harness rewrite would silently revert any hand-fix. The managed block now carries the credential as `http_headers = { Authorization = "Bearer <token>" }`, which loads on codex-cli 0.147.x AND 0.149.x (reporter's 3-variant probe in #4574). - renderBlock emits the http_headers inline table; both key-set validators (writer post-render + snippet renderer) now assert exactly [http_headers, url] plus an Authorization-only inner-table check, shared via validateOurKeys. - parseCodexBlockBearer reads the new shape and KEEPS a legacy bearer_token read fallback so status/rotation still recover tokens on machines wired by older gbrain; a non-Bearer Authorization hand-edit is not recovered. - gbrain agent register's paste block flows through the same renderBlock via renderCodexHttpServerBlock — no separate fix needed. - host-specs CODEX_SPEC_ID note + references refreshed (0.149.1 probe); KEY_FILES.md's three bearer_token mentions updated. - Tests: new legacy-block upgrade-in-place + legacy-fallback recovery cases; existing suites moved to the new shape (codex-toml, bootstrap-harness.serial, bootstrap-hooks-writers, e2e lifecycle). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(backlinks): undated 'Referenced by' section — stop forging timeline dates (#4552, adopts #4595) Adopts PR #4595 by @mvanhorn with fixes. `gbrain check-backlinks fix` used to stamp every generated back-link with the RUN date and insert it into the target page's timeline, so a large historical repair made old structural links look like current activity and corrupted date-based recency/staleness consumers (#4552). From the PR diff (adopted as the diff actually does, not as the body describes): - buildBacklinkEntry drops the date argument and the '**YYYY-MM-DD** |' prefix; link-path normalization (#1776) unchanged. - insertBacklinkEntry writes undated rows into a dedicated '## Referenced by' section placed ABOVE the timeline region (findTimelineSplitIndex sentinels take precedence over bare '## Timeline'/'## History' headings — consistent with splitBody, so the rows land in compiled_truth, never the timeline half). - insertTimelineEntry kept as an alias; fixBacklinkGaps no longer computes a per-run 'today'. Adoption fixes (guards the PR deleted, re-added adapted to the new semantics): - near-miss heading pin: '### Timeline' / '## Timeline (2026)' are NOT timeline boundaries (fresh section appends at EOF below them). - determinism: with two real '## Timeline' headings the section lands before the FIRST. - CRLF timeline-boundary coverage: bare heading tolerates \r and the inserted section uses the file's dominant EOL. Suites: backlinks, backlinks-job-default, backlink-count-mention-filter, markdown, markdown-serializer, markdown-validation, timeline-write-through, timeline-date-batch — all green. Co-Authored-By: Matt Van Horn <mvanhorn@gmail.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(search): post-sunset reranker short-circuit + audit trail (refs #3657) Once a listed reranker provider's hosted API passes its announced shutdown date, every rerank call could only burn the per-query timeout (up to 5s) before failing. gateway.rerank() now short-circuits: past the RERANKER_SUNSETS date the HTTP call is skipped entirely and search fails open immediately with unreranked results. Per amendments X7+F3: - The check runs where the EFFECTIVE model is resolved (inside gateway.rerank, after `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL`) — an absent per-call model landing on the configured/legacy default is the main case and is covered. - Base-URL-override suppression preserved (self-hosted wire-compatible endpoints outlive the hosted shutdown — same rule as warnSunsetOnce). - Traceability: ONE rerank-failures audit-JSONL row per process per model (reason 'sunset_short_circuit', doctor's reranker_health signal) plus one stderr line per process; applyReranker skips per-query audit rows for this reason so the file can't flood until migration. - Date semantics match doctor's provider_sunset check: the date itself counts as past. New 'sunset_short_circuit' member on RerankError.reason and RerankFailureReason. - defaults.ts constants and mode bundles untouched (the default swap is the separate September decision). Tests (test/rerank-sunset-short-circuit.test.ts, injected clock via __setSunsetClockForTests): absent model, explicit model, base-URL override suppressed, live-model untouched, before/on/after 2026-09-04 with a transport call counter (no HTTP after the date), the single audit row + single stderr line across repeated calls, and applyReranker pass-through on both sides of the date. module-size-limits.tsv: gateway.ts ceiling 4618 → 4692 (+74, noted). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(sync): honor the persisted exclude scope on every sync path (#4667 adoption) Adopts PR #4667: every sync path unions the persisted `sync.exclude` config (comma/newline-separated; trailing `/` normalized to a `/**` subtree glob) into the per-call --exclude set, so internal callers (autopilot, minion sync jobs, dream cycle) stop re-importing excluded derivative files. Union, not override: an ad-hoc flag narrows further but never silently re-opens a persisted scope. Adoption fixes on top of the PR: - FIX 1: the config-union block is hoisted ABOVE performSyncInner's three performFullSync early returns (gc'd anchor / first sync / --include-gitignored). The first sync is exactly where exclusion pollution is permanent — the full walk previously ran before the union resolved, importing every excluded file once and forever. - FIX 2: `sync.exclude` registered in KNOWN_CONFIG_KEYS — without it `gbrain config set sync.exclude ...` exits 1 as unknown-key and the operator path to the feature is unreachable. - FIX 3: first-sync exclusion test pinning FIX 1 (fresh engine + repo, scope persisted before any sync; full walk must carry it). module-size TSV raised in-commit: sync.ts 5704→5752, config.ts 1604→1611. Co-Authored-By: Henrique da Mota <henriquedamota@gmail.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(sync): soft-delete on file removal — honor the 72h recovery window (#4587) All seven delete sites in src/commands/sync.ts hard-deleted through deletePage/deletePages: a git rm (or a full-sync reconcile) destroyed the page + chunks + links immediately, bypassing the soft-delete window every other delete surface honors — and wiped already-soft-deleted rows early, restarting nothing and recovering nothing. New batch engine method (BOTH engines, lockstep): softDeletePages(slugs: string[], opts: { sourceId: string }): Promise<string[]> UPDATE pages SET deleted_at = now() WHERE slug = ANY(...) AND source_id = ... AND deleted_at IS NULL RETURNING slug Mirrors deletePages' contract exactly: empty-array early-return (F1), DELETE_BATCH_SIZE caller-chunking (throw over the cap), RETURNING projects only real transitions. The deleted_at IS NULL predicate keeps a re-run from restarting an existing row's 72h purge clock. Nothing cascades — the purge phase owns the eventual hard delete; a re-import within the window revives via putPage's ON CONFLICT deleted_at = NULL. Swapped call sites (sync.ts): removed-file drain x3 (batched lane, decompose fallback, legacy no-sourceId lane), rename-reconcile stale-row delete, full-sync reconcile x2 (batch + per-slug fallback), unsyncable cleanup. deletePage/deletePages stay purge/teardown primitives everywhere else. X3: decompose-on-batch-failure semantics preserved — one-element softDeletePages batches per slug, failures to the ledger, run CONTINUES (--skip-failed semantics), never abort-the-run. Summary wording now says "soft-deleted (recoverable 72h)". E1 trace (rename-lane/dedup existence checks vs soft-deleted rows): getPage default-hides deleted rows; activeSlugsBySourcePath and resolveSlugsForRemovedPaths filter deleted_at IS NULL; resolveSlugsByPaths does not, so the rename lane can pick a soft-deleted row as its cheap-move source — updateSlug (no deleted_at filter) moves it and the destination import's upsert revives it, which is the correct end state (the file exists at the destination). Pinned by the new rename-lane test. Tests: test/sync-soft-delete.serial.test.ts (drain soft-delete, X3 decompose both shapes, X4 revival, T3-residual query/get_links invisibility, E1 rename lane); softDeletePages primitive coverage in sync-delete-batch.test.ts + idempotent 10K perf gate in the .slow variant; #4587 parity + revival-parity tests in test/e2e/engine-parity.test.ts (green on Postgres + PGLite); softDeletePages registered in engine-surface-coverage INTERFACE_METHODS; sync-rename-reconcile.serial countPages now counts LIVE rows and the failure injections patch softDeletePages. module-size TSV raised in-commit: engine.ts 2550→2583, postgres-engine.ts 5652→5675, pglite-engine.ts 6164→6187, sync.ts 5752→5774. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): heal oversized stale chunks before embed (#4530, adopts #4668) Rows chunked before the #4530 per-model input cap (or before a model declared max_input_tokens) can carry a single oversized chunk_text that fails every `embed --stale` sweep forever on 512-token models. The new src/core/embed-oversize-heal.ts splits those rows in place (never truncates) before the embed call, in both --stale drains and the per-page embed path; split pieces flow through the normal NULL-embedding cursor. Adopted from PR #4668 with fixes: - Peeled the healed-to-stale-row remap (duplicated verbatim in src/commands/embed.ts and src/core/embed-stale.ts) into the shared healedChunksToStaleRows helper in embed-oversize-heal.ts; embed.ts TSV row updated in the same commit (1949 -> 1978; +29 instead of the adoption's +41). - chunk_source now passes through UNCHANGED in the remap. The PR coerced fenced_code -> compiled_truth, which would have made wrapChunkTextsForStoredMode prepend a contextual prefix to code chunks, violating the D20-T4 never-wrap convention. StaleChunkRow.chunk_source widened to include 'fenced_code' (listStaleChunks never filtered it; the narrower union was aspirational). - Dropped the unused isEmbeddingOversizeError export (nothing consumed it; the heal is proactive, not error-driven). Co-Authored-By: Andrew Levine <levineam@gmail.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): bound the single-flight lock heartbeat refresh per tick (refs #4599, adopts #4647) The heartbeat tick awaited h.refresh() unbounded: one hung refresh silenced the heartbeat forever (the beating flag stays true) while the TTL kept lapsing, letting another process steal the single-flight lock mid-drain — mutual exclusion silently lost. Each tick now races refresh against a timeout (GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS, default 30s) with an AbortController threaded into refresh; a timed-out tick counts toward the existing 3-consecutive-errors abort. stopHeartbeat() also aborts any in-flight tick so cleanup never waits on a dead refresh. Adopted from PR #4647 with fixes: - Dropped the PR's unref() on the heartbeat interval. Unref'ing it would turn the #4599 hang class (lost drain promise) into a silent exit-0 truncation with the single-flight locks leaked; the referenced interval keeps the hang loud. The per-tick timeout timer's unref stays (the interval already anchors the event loop). - Recomputed the module-size TSV row on the post-#4668-peel base (1978 -> 2013). Note: the #4599 root-cause theory implicating this heartbeat was retracted by the reporter — this is hardening for an independently verified un-timeboxed-await hole, not a fix for #4599, which stays open. Co-Authored-By: Javier Aldape <6430563+javieraldape@users.noreply.github.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): progress-keyed stall watchdog for --stale drains (refs #4599) A wedged embed drain (lost promise, dead pooler connection, abort-ignoring HTTP call) used to run forever holding its single-flight locks — the lock heartbeat kept refreshing on its own timer, so nothing bounded the run. Root cause is unpinned (#4599 stays open); this bounds the failure the way sync's #1950 watchdog bounds import drains. New core module src/core/embed-stall.ts: - GBRAIN_EMBED_STALL_ABORT_SECONDS (env-only incident knob; default 900, 0 disables) mirrors GBRAIN_SYNC_STALL_ABORT_SECONDS. - Two clocks, one trigger (T6/X5): liveness is keyed at embedding-API- response grain — every settled embed attempt (success, error, retry) ticks noteEmbedApiResponse() via embedBatchWithBackoff — but 'stall' means no SUCCESSFUL forward progress (chunks embedded) for the threshold. Provider retry storms trip it BY DESIGN and the run resumes cleanly; the module comment carries the consecutive-stall backoff note for auto-re-running schedulers. Liveness is run-scoped so a long-lived worker's previous job can't make a wedged drain look alive. - The check interval is deliberately NOT unref'd: for non-single-flight callers it can be the only handle keeping a lost-promise hang loud. Wiring in runEmbedCore (X5/X6): - The drain runs as a captured promise raced against the watchdog; a dead drain can no longer wedge the caller. Firing is idempotent and the watchdog performs its OWN bounded cleanup (~10s deadline, then the force path with the lock TTL as backstop): stops the heartbeat, aborts the drain signal, releases the self-acquired single-flight locks via the engine-backed handles, and flushes the pacing/stall summary — never relying on the stalled drain's finally. Caller-held locks stay with the caller per the heldLocks contract. - Core returns an ERROR RESULT: reason 'stall_timeout' + a stall entry in failures/failure_samples. No process.exit below the CLI layer. - ONLY the CLI wrapper (runEmbed) maps the stall result to a hard non-zero process exit; the embed and embed-catch-up minion handlers fail the JOB via assertEmbedNotStalled; cycle/daemon callers get the failed result through the existing failures>0 surfaces. - [embed.pages] progress continues to reach stderr unbuffered via the shared reporter (process.stderr.write, non-TTY one-line events). Tests: unit suite for the resolver/watchdog/liveness/assert helper (test/embed-stall.test.ts) + integration in the embed serial suite with a 1s injected threshold: stall fires with the single-flight lock released (asserted against an emulated gbrain_cycle_locks table driven by the real db-lock code), summary flushed to stderr, reason surfaced; the non-CLI caller path returns the error result without process exit; a progressing drain never trips. Module-size TSV recomputed for embed.ts and jobs.ts in-commit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): scope get_stats/get_health/get_brain_identity to the caller's source grant (#4592) Aggregates leak by subtraction: since #4433 confined sources_list, a source-scoped remote grant could still recover an excluded source's page count and type mix from the unscoped counters. Both engines' getStats and getHealth now take the sourceScopeOpts shape and confine every counter, coverage numerator and denominator, and degree — a link contributes only when BOTH endpoints are in scope, so a granted-to-ungranted edge can't leak the far side through a degree or rescue a page from orphan-hood. The op layer applies the #4433 ladder: trusted local keeps the brain-wide view; remote scalar/federated grants confine; the __all__ sentinel and an explicit empty grant fail closed to zeros. get_brain_identity (read-scope, the quiet third aggregate surface) rides the same ladder. getHealth's migrations block stays global by decision (host ledger, no per-source semantics). Differential class-closer test: mutating an excluded source moves nothing a scoped caller can see; real-Postgres parity arm included. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: wave true-up — soft-delete lanes, scoped stats, embed heal/stall modules, sunset short-circuit, undated backlink repair, pricing-overrides reach (+1 TODO) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate cli-flag-registry after wave integration (embed stall/heartbeat knobs + codex/backlinks surface text) * chore: regenerate TOOL_CATALOG after the get_stats scope note (#4592) * fix(review): defuse the zerank suite time bomb, accept underscore-led slugs, isolation + privacy fixes Ship review criticals: (1) the legacy zerank suites exercised the real gateway clock — past 2026-09-04 the new sunset short-circuit would flip their audited reasons and fail them deterministically (red-proven by injecting a post-sunset clock); both files now pin a pre-sunset test clock. (2) slugifySegment preserves leading underscores (Hugo _index), so the put_page grammar's lead class now includes '_' — dots stay continuation-only, the traversal fence is unchanged (red-proven: notes/_index was rejected). Also: the sunset suite is quarantined as .serial with a resetGateway teardown (module-global clock + gateway mutation), the scoped-stats suite is order-independent with seed-state restoration, and a real page slug in an embed.ts comment is replaced with a generic placeholder per the privacy rule. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): adversarial-review hardening — features auto-fix stall safety, heal freshness guard, heal-as-progress Composition review of the wave: (1) gbrain features --fix reached the stall watchdog's process.exit through runEmbed, killing the auto-fix loop mid-run — it now uses the core seam + assertEmbedNotStalled so a stall reports { success: false } like any other failed fix (the exit mapping stays strictly in the CLI wrapper, per the X6 contract). (2) healOversizedPageChunks re-reads the chunk set before its upsert and skips on drift — the embed single-flight lock does not exclude sync, and clobbering a concurrent import with pre-sync splits would silently desync chunk_text from page content. (3) heal splits now tick the stall watchdog's progress key via EmbedResult.healed_splits: a corpus-wide heal prelude is forward progress, not a stall, so it can't abort deterministically at the same point on every resume. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(review): mechanical maintainability fixes from the wave ship review - embed.ts: inline import('embed-stall').EmbedStallInfo -> static type import - jobs.ts: two dynamic assertEmbedNotStalled imports -> one static import - subagent(+oneshot): collapse dead ?? fallback; single extractPromptTooLongDetail walk (detail non-null iff matcher matched) - ops/admin.ts: diagnosticScope(ctx) helper replaces the thrice-repeated fail-closed ladder; scope note moved into the FIRST sentence of the get_stats/get_health/get_brain_identity descriptions (TOOL_CATALOG truncates to first sentence); catalog regenerated - ai/defaults.ts: sunsetDateHasPassed() shared by gateway sunsetHasPassed (injected-clock seam kept) + doctor provider_sunset — surfaces can't drift - stall-env.ts: shared resolveStallAbortSecondsFromEnv() behind both resolveEmbedStallAbortSeconds and sync's resolveStallAbortSeconds - backlinks.ts: @deprecated JSDoc on the insertTimelineEntry compat alias - extract-atoms/models: resolveExtractAtomsModelWithSource() returns {model, source} so gbrain models derives value+label from ONE call (fail-soft kept: config read errors -> tier_default) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(embed): pin heal drain integration, heal orchestrator, heartbeat tick timeout, and stall job wiring Four wave-audit coverage gaps in the embed lane: - test/embed-oversize-heal-drain.serial.test.ts: PGLite-backed drain pins for SUP-3874 — embedStaleForSource, embedStalePages, and runEmbedCore({stale}) each heal an oversized stored chunk in place: sweep completes, the embedder never sees the oversized text, stored rows split under the cap, and the embedded sibling's vector survives. Red-proved against both the embed-stale.ts and embed.ts call-sites. - test/embed-oversize-heal.test.ts: healOversizedPageChunks orchestrator unit pins — no-op path skips upsertChunks and returns the loaded array; changed path fires onSplit(n), upserts source-scoped split pieces, returns the RELOADED chunks. - test/embed.serial.test.ts: #4647 heartbeat pin — a never-settling refresh() under a tiny GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS times out three consecutive ticks, flips lock_lost, and aborts the drain. Red-proved by removing the per-tick Promise.race timeout. - test/jobs-embed-stall-wiring.serial.test.ts: the embed Minion handler fails the JOB (throws) on reason 'stall_timeout' and resolves on a clean result. Red-proved by deleting the assertEmbedNotStalled call. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(takes): pin cmdList negative paths, loadProposal normalization, and the real atoms retry-failure case - src/commands/takes.ts: add the /^\d+$/ whole-string pre-check to cmdList's --limit/--offset parsing so parseInt truncation ('12abc' → 12, '1e3' → 1) can no longer slip trailing garbage through silently; error copy stays identical to the numeric guards (same discipline as cmdPropose's parseId). - test/takes-list-subcommand.test.ts: negative-path pins — --limit 0/abc/12abc and --offset -1/3xyz each print the exact Invalid-flag message and exit 1 (process.exit stubbed per the commands-search convention); boundary values --limit 1 --offset 0 still pass. Red-proved by removing the pre-check. - test/take-proposals.test.ts: drive acceptProposal over a munged old-shape loadProposal row (BigInt id, string weight via an executeRaw interceptor on the 'WHERE id = $1' read) and assert the returned proposal carries numeric id AND numeric weight. Red-proved by bypassing normalizeTakeProposalRow. - test/llm-json-reasoning-ladder.test.ts: the 'preserves the ORIGINAL failure reason' test now feeds input that actually ENTERS the retry branch (bracket drafted inside <think>, retry fails with a DIFFERENT reason) and asserts the exact original reason; the old no-op-strip case stays as its own renamed test. Red-proved with a retry-masking mutant the old test missed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sync): pin reconcile/unsyncable soft-delete lanes, cycle purge window, exclude multi-pattern + throw posture Wave-audit coverage gaps in the sync lane (#4587 soft-delete, #4667 exclude): - test/sync-soft-delete.serial.test.ts: - full-sync reconcile over a removed file leaves the row EXISTING with deleted_at set (recoverable via includeDeleted) — pre-#4587 it was hard-deleted; the existing suites only asserted not-live, which a hard delete also satisfies. Red-proved with a hard-DELETE reconcile mutant. - the unsyncable poisoned-filename sweep is soft: the swept row exists with a tombstone. - end-to-end purge window: sync-originated tombstones backdated 73h are hard-deleted by the CYCLE purge phase (runCycle phases:['purge']) while a 71h tombstone and live rows survive. - test/sync-exclude-config.test.ts (fresh engine + repo describe): - a mixed comma+newline 'raw/, tmp/\nlogs/' config value excludes all three subtrees in one sync. - conservative posture: a page imported BEFORE the exclusion stays LIVE (deleted_at IS NULL) across incremental syncs AND a full-sync reconcile. - the getConfig THROW branch: sync completes and no persisted scope is applied (distinct from the existing empty-string case). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(mcp/pricing/backlinks): pin serve-http instructions, backfill cap classification, luna recipe drift, boundary + idempotency - test/e2e/connect-bearer.test.ts: real SDK initialize against the live runServeHttp process asserts client.getInstructions() === GBRAIN_MCP_INSTRUCTIONS — the serve --http lane had no instructions coverage (stdio + legacy transport were pinned elsewhere). Red-proved by dropping instructions from the per-request Server. - test/handlers-embed-backfill.test.ts: the implicit $10 default cap still ENFORCES once pricing.overrides make the model priceable (reserve+record >$10 → budget_exhausted, budgetCapUsd 10) — kills the 'capForModel returns undefined whenever defaulted' mutant every existing test passed under (red-proved); a garbage explicit cap ('garbage') classifies as implicit and runs uncapped-with-warning for unpriced models (success, no budgetCapUsd). - test/model-pricing.test.ts: the openai recipe's expansion cost_per_1m_tokens_usd equals CANONICAL_PRICING['openai:gpt-5.6-luna'].input and luna stays the declared baseline model — a price refresh touching only one home now fails the drift guard. - test/backlinks.test.ts: '## History' is a placement boundary (section lands before it — red-proved by dropping History from the regex); lowercase '## timeline' matches (case-insensitivity); the dashed '--- timeline ---' sentinel is a boundary; and a full second gap→fix→re-scan loop is byte-identical (one heading, one row). - test/mcp-tool-defs.test.ts: GBRAIN_MCP_INSTRUCTIONS carries the same REPLACES / not-a-partial-edit / get_page include_content:true phrases pinned for the put_page descriptions — ties the third client-visible home to the same contract. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed-backfill): stall watchdog on the production backfill lane + fail-closed garbage caps Composition review follow-through: (1) the auto-queued embed-backfill handler — the lane most likely to reproduce the wedged-drain shape — bypassed runEmbedCore and had no watchdog; it now arms one keyed on banked cursor progress, aborts the drain through the same signal the operator path uses, and fails the job (resumable) on stall_timeout. (2) A present-but-unparsable embed.backfill_max_usd means the operator INTENDED a cap: the $10 default now applies and is never droppable for unpriced models (a typo must not silently degrade to uncapped spend); 'off' keeps its documented meaning. (3) The heal orchestrator's freshness guard gets its own concurrent-rewrite pin, and the changed- path stub models the guard's recheck read. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: sync.exclude brain-global caveat (composition review F6) * test(review): withEnv for the backfill stall pin + structural-manifest regen * chore: bump version and changelog (v0.47.6.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-check pass for v0.47.6.0 — test inventory, fail-closed cap contract, sunset short-circuit, embed heartbeat knobs - docs/TESTING.md: unit-test inventory entries for the wave's new suites (sync soft-delete + exclude-config, embed oversize-heal + drain, embed stall watchdog + jobs wiring, embed.serial #4599/#4647 arcs, backfill cap classification, rerank sunset short-circuit, scoped stats/health, takes list flags, bigint normalization, reasoning-ladder, extract_atoms reporting + fail-soft, conversation-facts pricing wiring). - docs/operations/spend-controls.md: the fail-closed garbage-cap contract on embed.backfill_max_usd — a present-but-invalid value keeps the $10 default and is never dropped for unpriced models; only 'off' lifts it. - docs/architecture/RETRIEVAL.md: post-sunset reranker short-circuit behavior (fail-open, audit trail, doctor state, base_urls suppression). - docs/architecture/KEY_FILES.md: embed.ts entry gains the bounded single-flight lock heartbeat (GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS, 3-strikes lock_lost) + stall-watchdog wiring. llms bundles regenerated (no drift); check-key-files-current-state and test/build-llms.test.ts green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: apply doc-review findings for v0.47.6.0 — working sync.exclude example, provider_sunset check name, stall-env entry Cross-model doc review (Claude subagent lane; codex sandbox unavailable here) verified against source: - CHANGELOG 0.47.6.0: the sync.exclude example used a JSON-array literal the comma/newline reader never parses (silent no-op for anyone pasting it) — corrected to the working 'generated/' form with the pattern-list note; the takes list flags were documented on the MCP op, not implied by the CLI help. - docs/architecture/RETRIEVAL.md: the post-sunset reranker state is explained by doctor's provider_sunset check (reranker_health has no sunset branch and reports ok). - docs/architecture/KEY_FILES.md: entry for the new src/core/stall-env.ts shared watchdog-knob resolver (sync #1950 + embed #4599 semantics cannot drift). llms bundles regenerated; guards green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(changelog): credit wave contributors by handle + cover the models extract-atoms report (#4662) * test: widen gateway shim-cast structural pin window for the sunset short-circuit block The zeroentropy-compat-fetch source-text pin allowed 3000 chars between the last fetch-shim cast and resolveEmbeddingProvider; the post-sunset short-circuit helpers grew that gap to ~5000. Window widened to 6000 with the comment updated to name both occupants. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: post-release audit for the v0.47.6.0 community fix wave (#4701 follow-up) Nine factual corrections found by the post-ship documentation audit (six parallel local auditors + a cross-model pass, findings verified against src before editing): - RETRIEVAL.md: exclude_slug_prefixes configures exclusions, not the boost map; documented the real exclusion set (defaults ∪ GBRAIN_SEARCH_EXCLUDE ∪ per-call prefixes). - spend-controls.md: non-TTY cost-gate deferral always defers rows, but a backfill JOB is submitted only when a worker surface exists (manual_drain_required / no_worker_surface / auto_submit_disabled now documented); off-token list corrected to off/unlimited/none. - KEY_FILES.md: takes.ts entry now describes the full dispatcher incl. the new list pagination; added entries for take-proposals.ts (BigInt normalization boundary) and minions/handlers/embed-backfill.ts (cap ladder + stall-watchdog arm). - CHANGELOG 0.47.6.0: added the missed bullet for the parser-probe misreport fix (#4639 adoption) — additive only. - TODOS.md: narrowed the chunk-level embed-quarantine item (the single-oversized-chunk branch is now healed by embed-oversize-heal.ts). - skills/migrations/v0.46.3.0.md: post-sunset consequence updated — the short-circuit means searches no longer pay the timeout. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate skills lock after v0.46.3.0 migration-doc correction Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: lucca sapucaia <luccasapucaia@MacBook-Pro-de-lucca.local> Co-authored-by: RuiWang <224701776+ruiwang20010702@users.noreply.github.com> Co-authored-by: Nathan Maxwell <nathan@hydrolyze.app> Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> Co-authored-by: Daniel Peng <zgpeng2002@163.com> Co-authored-by: gbrain-contrib <gbrain-contrib@example.com> Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com> Co-authored-by: boundless-forest <boundless-forest@users.noreply.github.com> Co-authored-by: Matt Van Horn <mvanhorn@gmail.com> Co-authored-by: Henrique da Mota <henriquedamota@gmail.com> Co-authored-by: Andrew Levine <levineam@gmail.com> Co-authored-by: Javier Aldape <6430563+javieraldape@users.noreply.github.com> |
||
|
|
3f2f300483 |
v0.47.6.0 fix: the community fix wave — 16 contributor PRs adopted + takes-on-Postgres, sync soft-delete, embed stall watchdog, scoped stats, codex 0.149 auth, reranker sunset short-circuit (#4701)
* fix(bootstrap): repair the pre-v143 dream_verdicts upgrade wedge on Postgres (#4657) The embedded Postgres schema creates dream_verdicts_expires_idx on expires_at, but the column only lands via migration v143 — so any brain at schema v30-v142 wedged on connect before migrations could run. The forward-reference bootstrap now probes for the gap and adds the column (nullable + SET DEFAULT as separate statements so existing rows keep their judged_at-derived backfill), with v143 remaining the source of truth for backfill/NOT NULL/index. Class closure (4th recurrence of #2537/#2703/#4477): the schema-coverage suite now parses the POSTGRES blob's CREATE INDEX references too, so a blob-only forward reference fails locally at PR time instead of only on the DATABASE_URL e2e lane. Pre-v143 convergence pinned by a live e2e case (red-proven against the unfixed bootstrap). * fix(dream): harden the expires_at upgrade window (both engines) Adversarial review of #4657: if v143 fails mid-upgrade (the CLI warns and continues on migration errors), NULL expires_at rows previously read as permanent cache misses — silently re-judging the whole corpus with paid LLM calls — and the sweep never deleted them. getDreamVerdict now treats NULL as a pre-TTL hit on both engines (v143 stamps those rows when it succeeds). v143 also sets the column DEFAULT before its backfill so a legacy writer racing the upgrade can't insert NULLs between the backfill and SET NOT NULL. The bootstrap banner no longer mislabels newer brains as pre-v0.21. Module-size: both engine ceilings +1 (the NULL-tolerance SQL comment), reviewer-visible in scripts/module-size-limits.tsv. * docs: KEY_FILES bootstrap entry current-state + schema-coverage DDL-forms follow-up TODO * chore: bump version and changelog (v0.47.5.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-check pass for v0.47.5.0 — TESTING.md two-blob bootstrap gate + KEY_FILES v143 invariants TESTING.md: schema-bootstrap-coverage entry now describes both halves (PGLite registry + the Postgres-blob CREATE-INDEX class-closure gate) and the postgres-bootstrap e2e entry now lists the wedge-class convergence cases and the standalone db.initSchema path it actually covers. KEY_FILES.md: migrate.ts entry gains the v143 clause (statement-order invariant, Postgres bootstrap probe, NULL-tolerant read predicate). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: apply doc-review findings for v0.47.5.0 — probe-set superset, standalone-path honesty, e2e/TTL test entries KEY_FILES.md: postgres-engine.ts entry no longer claims the same probe set as PGLite (Postgres carries blob-only probes); forward-reference-bootstrap entry states plainly that the standalone db.ts:initSchema path does not run migrations and why that is safe. TESTING.md: drop the unsupported fresh-install no-op claim on the postgres-bootstrap e2e entry and add the dream-verdict TTL contract test entry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: normalize stale take bigint rows * fix(takes): normalize proposal bigint rows Refs #4634. * fix(takes): parse --limit/--offset in takes list (#4629) The takes_list operation has exposed limit (default 100, cap 500) and offset since v0.28, but the CLI's cmdList never parsed the flags — every `gbrain takes list --limit N` silently ran with engine defaults. Parse both (same validation shape as `takes propose --limit`), pass them through to engine.listTakes, document them in the usage text, and regenerate the CLI flag registry (--offset is new to the takes scan surface). Tests cover --limit capping, --offset paging with and without --limit, and the unchanged bare `takes list` path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(json): recover JSON from reasoning models that emit a <think> block Models with visible chain-of-thought (DeepSeek-R1, MiniMax M2.x/M3, and any model configured to show thinking) emit reasoning in the SAME text channel as the answer, before it. They also routinely draft their JSON while reasoning, so that block contains braces and brackets. This defeats the substring-scan strategies in all three JSON extractors: parseLlmJson /\{[\s\S]*\}/ spans from the first brace INSIDE the reasoning to the last brace of the real answer facts extractor the {"facts":...} scan starts inside the draft atoms extractor indexOf('[') finds a bracket inside <think> In each case a perfectly good response parses as null / "malformed output". The callers then treat it as an empty extraction or burn a retry LLM call that fails the same way. Measured on a MiniMax-M3-backed brain: a 38.2% atom halt rate, and 50 malformed-output fact extractions in 24h. Adds stripReasoningBlocks() and wires it into all three as a fallback LADDER rather than a pre-filter: 1. parse the raw text exactly as today 2. only if that fails, strip reasoning blocks and retry once so behaviour for models that never emit <think> is byte-identical, a payload that legitimately contains the literal string "<think>" still parses, and the atoms extractor returns its ORIGINAL failure reason when the retry also fails. Text with no reasoning block strips to itself, so the success path is unchanged. Handles both a closed <think>…</think> pair and a truncated block the model opened and never closed (output budget exhausted). Tests: 11 new cases covering both block shapes, answer-vs-draft recovery, the ladder's byte-identical passthrough, and both extractors. Existing suites pass unchanged (facts-extract 9, extract-atoms-failure-classes 17, think-pipeline 40, extract-conversation-facts 74). * fix(parser): report generic chat unavailability Refs #4635. * fix(minions): gateway-native subagent path fast-fails on prompt-too-long The legacy raw-Anthropic-SDK subagent path (agent.use_gateway_loop=false, the default) explicitly classifies a 400 "prompt is too long" error as terminal via isPromptTooLongError() -> UnrecoverableError, so the worker routes the job straight to `dead` instead of retrying up to max_stalled (comment cites preventing "the v0.30.x dream-cycle queue-clog"). The gateway-native path (gatewayToolLoop(), required for any non-Anthropic model and increasingly the live path as this fork migrates providers) had no equivalent: its wrapper runLoopConvertingLeaseLoss only re-classified lease-loss errors and re-threw everything else unmodified. A prompt-too-long condition on a gateway-routed job was retried like any other transient failure -- recreating the exact queue-clog class the original fix (#754) closed, just for jobs on the newer path. isPromptTooLongError() now walks a bounded (depth-3) .cause chain in addition to the object it's given directly: gateway.chat()'s catch boundary wraps every error via normalizeAIError(), which copies only the OUTER message onto the new AIConfigError/AITransientError and stores the raw provider error on .cause. Without the cause-walk, the SDK's actual wire shape (the phrase living on the inner .error.message field, per this file's own existing isPromptTooLongError unit tests) would silently fail to match post-wrap on the gateway-native path. A sibling extractPromptTooLongDetail() shares the same walk to surface the matched provider detail (e.g. "prompt is too long: 1707509 tokens > 1000000 maximum") in the UnrecoverableError message, instead of the generic outer normalizeAIError() wrapper text (e.g. "BadRequestError") -- the detail an operator actually needs to diagnose a dead-lettered job. Verified via three rounds of positive control, each isolating one fix: (1) reverted runLoopConvertingLeaseLoss's call site entirely, observed the regression test fail with the raw provider error propagating uncaught through the full production call chain (chat -> toolLoop -> runLoopConvertingLeaseLoss -> runSubagentViaGateway -> subagentHandlerInner -> subagentHandler); (2) reverted only the .cause-walk (keeping the call site), observed the same test fail on a realistic Anthropic-shaped error whose message lives on .error.message, not the outer .message normalizeAIError() copies; (3) reverted only extractPromptTooLongDetail, observed the strengthened assertion fail with the generic wrapper text instead of the token-count detail. Each revert was restored and re-verified green before proceeding. The regression test exercises the real production error boundary via __setGenerateTextTransportForTests (chat()'s own try/catch -> normalizeAIError()), not the shallower __setChatTransportForTests seam, per code-quality review feedback that the shallower seam would let the test pass without actually proving the gateway path is fixed. Both isPromptTooLongError's classification and extractPromptTooLongDetail's message-surfacing gap, and every fix here, were caught by two rounds of independent maintainer-lens + code-quality review during this PR's own development (three review rounds total, final verdict SAFE with no remaining Critical/Warning findings). * fix(minions): oneshot dispatch path fast-fails on prompt-too-long (#4674) Sibling to #4664 (gateway-native loop path): runSubagentOneshot shares the same gateway.chat() entrypoint and therefore the same normalizeAIError()-wrapped error shape, but its catch rethrew every non-abort error unclassified. A prompt-too-long condition on the oneshot dispatch path retried like any other transient failure up to max_stalled, recreating the same dream-cycle queue-clog class the legacy and gateway-loop paths already fast-fail on. Applies the same isPromptTooLongError()/extractPromptTooLongDetail() classification #4664 adds, at the oneshot catch site. Regression test added to test/e2e/subagent-gateway-path.test.ts, red-green verified (fails with AIConfigError pre-fix, passes with UnrecoverableError post-fix). * fix(mcp): deliver agent contract on initialize (#4642) (#4643) Adopted from PR #4643 (author original4422 / Daniel Peng), applied as the author's own resolution against master (second-parent diff of the PR's merge commit). - New src/mcp/instructions.ts: compile-time GBRAIN_MCP_INSTRUCTIONS agent operating contract (~250 tokens), no runtime filesystem dependency. - Returned from ALL THREE initialize transports: stdio SDK server (src/mcp/server.ts), OAuth per-request SDK server (src/commands/serve-http.ts), legacy raw-HTTP initialize (src/mcp/http-transport.ts). - put_page op + content param descriptions now state the write REPLACES the entire page (read canonical content first via get_page include_content:true) — closes the silent-data-loss confusion (#4632 is a dup of #4642). - docs/TOOL_CATALOG.md regenerated; KEY_FILES.md entries updated. - Pin tests: stdio getInstructions e2e (serve-stdio-roundtrip), raw-HTTP initialize instructions assertion (http-transport), put_page replace-warning description pin (mcp-tool-defs). * fix(cli): report models.dream.extract_atoms in `gbrain models` (#4662) `gbrain models`'s per-task routing report omitted `models.dream.extract_atoms` even though `runPhaseExtractAtoms` reads that config key directly as a real, separately priced routing decision — operators had no way to see or verify extract_atoms routing via the standard diagnostic. Adds the entry via a shared `resolveExtractAtomsModel()` (extracted from `runPhaseExtractAtoms`) that both the runtime and the report call, rather than routing the report through the generic `resolveModel()` chain — extract_atoms's actual resolution is narrower (DB config -> key-aware `resolveTierDefault('utility')` only; it does not honor `models.tier.utility` / `models.default` / an env var the way the generic chain does), so reporting via the generic chain could show a value diverging from what extraction actually uses. The extraction keeps the phase's existing fail-soft contract: all per-run config reads stay inside the single try/catch that falls back to safe defaults on any config-read failure, pinned by a regression test (verified via positive control: reverting to the model-read-outside-try shape makes the new test fail with the simulated config error; restoring the fix makes it pass). Also refreshes two stale comments (extract_atoms routing is configurable and key-aware, not hardcoded to Haiku), the KEY_FILES.md per-task-route count, and CLI_FLAG_REGISTRY (models.ts's new extract-atoms.ts import pulls in an existing "--drain" comment there via the generator's documented one-level prose-bleed scan). * fix(embed): honor backfill pricing overrides (#4571) * test(embed): pin fail-closed boundary for explicit caps on unpriced models (X10) Boundary test for the #4571 adoption: uncapped-with-warning applies ONLY to the implicit $10 default cap. An EXPLICIT operator-provided embed.backfill_max_usd with an unpriced embedding model fails closed (TX2 no_pricing -> budget_exhausted, zero work) — including the corner where the explicit value numerically equals the $10 default. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(facts): honor operator pricing in conversation backfills Refs #4633. Adopted with fixes on the wave branch: kept master's link_resolution.cross_source registration while inserting the pricing.overrides key after spend.posture (KNOWN_CONFIG_KEYS conflict), restored the blank line the PR deleted in extract-conversation-facts.ts, and raised the config.ts + extract-conversation-facts.ts module-size ceilings by the one real line each file grew. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pricing): update gpt-5.6-luna to post-cut rates (#4560) OpenAI cut gpt-5.6-luna pricing by ~80% on 2026-07-30 to .20 in / .20 out. CANONICAL_PRICING still carried the launch rate (.00/.00), causing every budget gate to throttle at a fifth of the operator's intended ceiling. * chore(pricing): refresh gpt-5.6-luna price_last_verified after live verification (#4560) Verified 2026-08-29 against OpenAI's official pricing docs (https://developers.openai.com/api/docs/pricing, the redirect target of platform.openai.com/docs/pricing): gpt-5.6-luna Standard tier lists $0.20 input / $1.20 output per 1M tokens — matching the #4598 adoption exactly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): validate put_page slugs at the op boundary (#4665, with sync-slugifier compat widen) Adopt PR #4665: put_page now runs validatePageSlug before allow-list, dry-run, or write handling, so malformed slugs (Dream-style spaces, traversal, control chars) fail the individual tool call instead of entering the database. Applies to both MCP and trusted local CLI callers. Required fix on top of the PR: as submitted it broke put_page round-trips for slugs the repo's own sync slugifier deliberately produces (slugifySegment preserves '.' and '_': notes/v1.0.0, people/my_file_name). validatePageSlug's LOCAL segment grammar in src/core/ops/context.ts is widened so '.' and '_' are allowed as segment-CONTINUATION characters only (word-char lead preserved, so dot-led segments — '..' traversal, '.hidden' — and every H5 rejection: backslash, %2e/%2f encodings, control chars, RTL overrides, spaces — stay rejected). The shared PAGE_SLUG_SEG in src/core/cjk.ts is untouched: cite-render, SlugRegistry, and the dream-cycle SUMMARY_SLUG_RE consume it with different semantics. Tests: put_page ACCEPTS notes/v1.0.0, people/my_file_name, and CJK slugs; still REJECTS spaces, dot-led segments, traversal, and control characters — at both the op level (operations-allow-list) and the unit level (file-upload-security H5 suite). Co-Authored-By: boundless-forest <boundless-forest@users.noreply.github.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(todos): file the fix-wave follow-ups (pricing sweep, think sweep, #4599 instrumentation, #4616, terra/sol verify, hoist, surface-aware MCP, per-source exclude, dating note, slug unification) + September-removal addenda * fix(bootstrap): codex http_headers auth shape for codex-cli >=0.149 (#4574) codex-cli >=0.149 rejects an inline `bearer_token` for streamable_http servers AT CONFIG LOAD, bricking every Codex session on the machine — and the harness rewrite would silently revert any hand-fix. The managed block now carries the credential as `http_headers = { Authorization = "Bearer <token>" }`, which loads on codex-cli 0.147.x AND 0.149.x (reporter's 3-variant probe in #4574). - renderBlock emits the http_headers inline table; both key-set validators (writer post-render + snippet renderer) now assert exactly [http_headers, url] plus an Authorization-only inner-table check, shared via validateOurKeys. - parseCodexBlockBearer reads the new shape and KEEPS a legacy bearer_token read fallback so status/rotation still recover tokens on machines wired by older gbrain; a non-Bearer Authorization hand-edit is not recovered. - gbrain agent register's paste block flows through the same renderBlock via renderCodexHttpServerBlock — no separate fix needed. - host-specs CODEX_SPEC_ID note + references refreshed (0.149.1 probe); KEY_FILES.md's three bearer_token mentions updated. - Tests: new legacy-block upgrade-in-place + legacy-fallback recovery cases; existing suites moved to the new shape (codex-toml, bootstrap-harness.serial, bootstrap-hooks-writers, e2e lifecycle). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(backlinks): undated 'Referenced by' section — stop forging timeline dates (#4552, adopts #4595) Adopts PR #4595 by @mvanhorn with fixes. `gbrain check-backlinks fix` used to stamp every generated back-link with the RUN date and insert it into the target page's timeline, so a large historical repair made old structural links look like current activity and corrupted date-based recency/staleness consumers (#4552). From the PR diff (adopted as the diff actually does, not as the body describes): - buildBacklinkEntry drops the date argument and the '**YYYY-MM-DD** |' prefix; link-path normalization (#1776) unchanged. - insertBacklinkEntry writes undated rows into a dedicated '## Referenced by' section placed ABOVE the timeline region (findTimelineSplitIndex sentinels take precedence over bare '## Timeline'/'## History' headings — consistent with splitBody, so the rows land in compiled_truth, never the timeline half). - insertTimelineEntry kept as an alias; fixBacklinkGaps no longer computes a per-run 'today'. Adoption fixes (guards the PR deleted, re-added adapted to the new semantics): - near-miss heading pin: '### Timeline' / '## Timeline (2026)' are NOT timeline boundaries (fresh section appends at EOF below them). - determinism: with two real '## Timeline' headings the section lands before the FIRST. - CRLF timeline-boundary coverage: bare heading tolerates \r and the inserted section uses the file's dominant EOL. Suites: backlinks, backlinks-job-default, backlink-count-mention-filter, markdown, markdown-serializer, markdown-validation, timeline-write-through, timeline-date-batch — all green. Co-Authored-By: Matt Van Horn <mvanhorn@gmail.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(search): post-sunset reranker short-circuit + audit trail (refs #3657) Once a listed reranker provider's hosted API passes its announced shutdown date, every rerank call could only burn the per-query timeout (up to 5s) before failing. gateway.rerank() now short-circuits: past the RERANKER_SUNSETS date the HTTP call is skipped entirely and search fails open immediately with unreranked results. Per amendments X7+F3: - The check runs where the EFFECTIVE model is resolved (inside gateway.rerank, after `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL`) — an absent per-call model landing on the configured/legacy default is the main case and is covered. - Base-URL-override suppression preserved (self-hosted wire-compatible endpoints outlive the hosted shutdown — same rule as warnSunsetOnce). - Traceability: ONE rerank-failures audit-JSONL row per process per model (reason 'sunset_short_circuit', doctor's reranker_health signal) plus one stderr line per process; applyReranker skips per-query audit rows for this reason so the file can't flood until migration. - Date semantics match doctor's provider_sunset check: the date itself counts as past. New 'sunset_short_circuit' member on RerankError.reason and RerankFailureReason. - defaults.ts constants and mode bundles untouched (the default swap is the separate September decision). Tests (test/rerank-sunset-short-circuit.test.ts, injected clock via __setSunsetClockForTests): absent model, explicit model, base-URL override suppressed, live-model untouched, before/on/after 2026-09-04 with a transport call counter (no HTTP after the date), the single audit row + single stderr line across repeated calls, and applyReranker pass-through on both sides of the date. module-size-limits.tsv: gateway.ts ceiling 4618 → 4692 (+74, noted). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(sync): honor the persisted exclude scope on every sync path (#4667 adoption) Adopts PR #4667: every sync path unions the persisted `sync.exclude` config (comma/newline-separated; trailing `/` normalized to a `/**` subtree glob) into the per-call --exclude set, so internal callers (autopilot, minion sync jobs, dream cycle) stop re-importing excluded derivative files. Union, not override: an ad-hoc flag narrows further but never silently re-opens a persisted scope. Adoption fixes on top of the PR: - FIX 1: the config-union block is hoisted ABOVE performSyncInner's three performFullSync early returns (gc'd anchor / first sync / --include-gitignored). The first sync is exactly where exclusion pollution is permanent — the full walk previously ran before the union resolved, importing every excluded file once and forever. - FIX 2: `sync.exclude` registered in KNOWN_CONFIG_KEYS — without it `gbrain config set sync.exclude ...` exits 1 as unknown-key and the operator path to the feature is unreachable. - FIX 3: first-sync exclusion test pinning FIX 1 (fresh engine + repo, scope persisted before any sync; full walk must carry it). module-size TSV raised in-commit: sync.ts 5704→5752, config.ts 1604→1611. Co-Authored-By: Henrique da Mota <henriquedamota@gmail.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(sync): soft-delete on file removal — honor the 72h recovery window (#4587) All seven delete sites in src/commands/sync.ts hard-deleted through deletePage/deletePages: a git rm (or a full-sync reconcile) destroyed the page + chunks + links immediately, bypassing the soft-delete window every other delete surface honors — and wiped already-soft-deleted rows early, restarting nothing and recovering nothing. New batch engine method (BOTH engines, lockstep): softDeletePages(slugs: string[], opts: { sourceId: string }): Promise<string[]> UPDATE pages SET deleted_at = now() WHERE slug = ANY(...) AND source_id = ... AND deleted_at IS NULL RETURNING slug Mirrors deletePages' contract exactly: empty-array early-return (F1), DELETE_BATCH_SIZE caller-chunking (throw over the cap), RETURNING projects only real transitions. The deleted_at IS NULL predicate keeps a re-run from restarting an existing row's 72h purge clock. Nothing cascades — the purge phase owns the eventual hard delete; a re-import within the window revives via putPage's ON CONFLICT deleted_at = NULL. Swapped call sites (sync.ts): removed-file drain x3 (batched lane, decompose fallback, legacy no-sourceId lane), rename-reconcile stale-row delete, full-sync reconcile x2 (batch + per-slug fallback), unsyncable cleanup. deletePage/deletePages stay purge/teardown primitives everywhere else. X3: decompose-on-batch-failure semantics preserved — one-element softDeletePages batches per slug, failures to the ledger, run CONTINUES (--skip-failed semantics), never abort-the-run. Summary wording now says "soft-deleted (recoverable 72h)". E1 trace (rename-lane/dedup existence checks vs soft-deleted rows): getPage default-hides deleted rows; activeSlugsBySourcePath and resolveSlugsForRemovedPaths filter deleted_at IS NULL; resolveSlugsByPaths does not, so the rename lane can pick a soft-deleted row as its cheap-move source — updateSlug (no deleted_at filter) moves it and the destination import's upsert revives it, which is the correct end state (the file exists at the destination). Pinned by the new rename-lane test. Tests: test/sync-soft-delete.serial.test.ts (drain soft-delete, X3 decompose both shapes, X4 revival, T3-residual query/get_links invisibility, E1 rename lane); softDeletePages primitive coverage in sync-delete-batch.test.ts + idempotent 10K perf gate in the .slow variant; #4587 parity + revival-parity tests in test/e2e/engine-parity.test.ts (green on Postgres + PGLite); softDeletePages registered in engine-surface-coverage INTERFACE_METHODS; sync-rename-reconcile.serial countPages now counts LIVE rows and the failure injections patch softDeletePages. module-size TSV raised in-commit: engine.ts 2550→2583, postgres-engine.ts 5652→5675, pglite-engine.ts 6164→6187, sync.ts 5752→5774. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): heal oversized stale chunks before embed (#4530, adopts #4668) Rows chunked before the #4530 per-model input cap (or before a model declared max_input_tokens) can carry a single oversized chunk_text that fails every `embed --stale` sweep forever on 512-token models. The new src/core/embed-oversize-heal.ts splits those rows in place (never truncates) before the embed call, in both --stale drains and the per-page embed path; split pieces flow through the normal NULL-embedding cursor. Adopted from PR #4668 with fixes: - Peeled the healed-to-stale-row remap (duplicated verbatim in src/commands/embed.ts and src/core/embed-stale.ts) into the shared healedChunksToStaleRows helper in embed-oversize-heal.ts; embed.ts TSV row updated in the same commit (1949 -> 1978; +29 instead of the adoption's +41). - chunk_source now passes through UNCHANGED in the remap. The PR coerced fenced_code -> compiled_truth, which would have made wrapChunkTextsForStoredMode prepend a contextual prefix to code chunks, violating the D20-T4 never-wrap convention. StaleChunkRow.chunk_source widened to include 'fenced_code' (listStaleChunks never filtered it; the narrower union was aspirational). - Dropped the unused isEmbeddingOversizeError export (nothing consumed it; the heal is proactive, not error-driven). Co-Authored-By: Andrew Levine <levineam@gmail.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): bound the single-flight lock heartbeat refresh per tick (refs #4599, adopts #4647) The heartbeat tick awaited h.refresh() unbounded: one hung refresh silenced the heartbeat forever (the beating flag stays true) while the TTL kept lapsing, letting another process steal the single-flight lock mid-drain — mutual exclusion silently lost. Each tick now races refresh against a timeout (GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS, default 30s) with an AbortController threaded into refresh; a timed-out tick counts toward the existing 3-consecutive-errors abort. stopHeartbeat() also aborts any in-flight tick so cleanup never waits on a dead refresh. Adopted from PR #4647 with fixes: - Dropped the PR's unref() on the heartbeat interval. Unref'ing it would turn the #4599 hang class (lost drain promise) into a silent exit-0 truncation with the single-flight locks leaked; the referenced interval keeps the hang loud. The per-tick timeout timer's unref stays (the interval already anchors the event loop). - Recomputed the module-size TSV row on the post-#4668-peel base (1978 -> 2013). Note: the #4599 root-cause theory implicating this heartbeat was retracted by the reporter — this is hardening for an independently verified un-timeboxed-await hole, not a fix for #4599, which stays open. Co-Authored-By: Javier Aldape <6430563+javieraldape@users.noreply.github.com> Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): progress-keyed stall watchdog for --stale drains (refs #4599) A wedged embed drain (lost promise, dead pooler connection, abort-ignoring HTTP call) used to run forever holding its single-flight locks — the lock heartbeat kept refreshing on its own timer, so nothing bounded the run. Root cause is unpinned (#4599 stays open); this bounds the failure the way sync's #1950 watchdog bounds import drains. New core module src/core/embed-stall.ts: - GBRAIN_EMBED_STALL_ABORT_SECONDS (env-only incident knob; default 900, 0 disables) mirrors GBRAIN_SYNC_STALL_ABORT_SECONDS. - Two clocks, one trigger (T6/X5): liveness is keyed at embedding-API- response grain — every settled embed attempt (success, error, retry) ticks noteEmbedApiResponse() via embedBatchWithBackoff — but 'stall' means no SUCCESSFUL forward progress (chunks embedded) for the threshold. Provider retry storms trip it BY DESIGN and the run resumes cleanly; the module comment carries the consecutive-stall backoff note for auto-re-running schedulers. Liveness is run-scoped so a long-lived worker's previous job can't make a wedged drain look alive. - The check interval is deliberately NOT unref'd: for non-single-flight callers it can be the only handle keeping a lost-promise hang loud. Wiring in runEmbedCore (X5/X6): - The drain runs as a captured promise raced against the watchdog; a dead drain can no longer wedge the caller. Firing is idempotent and the watchdog performs its OWN bounded cleanup (~10s deadline, then the force path with the lock TTL as backstop): stops the heartbeat, aborts the drain signal, releases the self-acquired single-flight locks via the engine-backed handles, and flushes the pacing/stall summary — never relying on the stalled drain's finally. Caller-held locks stay with the caller per the heldLocks contract. - Core returns an ERROR RESULT: reason 'stall_timeout' + a stall entry in failures/failure_samples. No process.exit below the CLI layer. - ONLY the CLI wrapper (runEmbed) maps the stall result to a hard non-zero process exit; the embed and embed-catch-up minion handlers fail the JOB via assertEmbedNotStalled; cycle/daemon callers get the failed result through the existing failures>0 surfaces. - [embed.pages] progress continues to reach stderr unbuffered via the shared reporter (process.stderr.write, non-TTY one-line events). Tests: unit suite for the resolver/watchdog/liveness/assert helper (test/embed-stall.test.ts) + integration in the embed serial suite with a 1s injected threshold: stall fires with the single-flight lock released (asserted against an emulated gbrain_cycle_locks table driven by the real db-lock code), summary flushed to stderr, reason surfaced; the non-CLI caller path returns the error result without process exit; a progressing drain never trips. Module-size TSV recomputed for embed.ts and jobs.ts in-commit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): scope get_stats/get_health/get_brain_identity to the caller's source grant (#4592) Aggregates leak by subtraction: since #4433 confined sources_list, a source-scoped remote grant could still recover an excluded source's page count and type mix from the unscoped counters. Both engines' getStats and getHealth now take the sourceScopeOpts shape and confine every counter, coverage numerator and denominator, and degree — a link contributes only when BOTH endpoints are in scope, so a granted-to-ungranted edge can't leak the far side through a degree or rescue a page from orphan-hood. The op layer applies the #4433 ladder: trusted local keeps the brain-wide view; remote scalar/federated grants confine; the __all__ sentinel and an explicit empty grant fail closed to zeros. get_brain_identity (read-scope, the quiet third aggregate surface) rides the same ladder. getHealth's migrations block stays global by decision (host ledger, no per-source semantics). Differential class-closer test: mutating an excluded source moves nothing a scoped caller can see; real-Postgres parity arm included. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: wave true-up — soft-delete lanes, scoped stats, embed heal/stall modules, sunset short-circuit, undated backlink repair, pricing-overrides reach (+1 TODO) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate cli-flag-registry after wave integration (embed stall/heartbeat knobs + codex/backlinks surface text) * chore: regenerate TOOL_CATALOG after the get_stats scope note (#4592) * fix(review): defuse the zerank suite time bomb, accept underscore-led slugs, isolation + privacy fixes Ship review criticals: (1) the legacy zerank suites exercised the real gateway clock — past 2026-09-04 the new sunset short-circuit would flip their audited reasons and fail them deterministically (red-proven by injecting a post-sunset clock); both files now pin a pre-sunset test clock. (2) slugifySegment preserves leading underscores (Hugo _index), so the put_page grammar's lead class now includes '_' — dots stay continuation-only, the traversal fence is unchanged (red-proven: notes/_index was rejected). Also: the sunset suite is quarantined as .serial with a resetGateway teardown (module-global clock + gateway mutation), the scoped-stats suite is order-independent with seed-state restoration, and a real page slug in an embed.ts comment is replaced with a generic placeholder per the privacy rule. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed): adversarial-review hardening — features auto-fix stall safety, heal freshness guard, heal-as-progress Composition review of the wave: (1) gbrain features --fix reached the stall watchdog's process.exit through runEmbed, killing the auto-fix loop mid-run — it now uses the core seam + assertEmbedNotStalled so a stall reports { success: false } like any other failed fix (the exit mapping stays strictly in the CLI wrapper, per the X6 contract). (2) healOversizedPageChunks re-reads the chunk set before its upsert and skips on drift — the embed single-flight lock does not exclude sync, and clobbering a concurrent import with pre-sync splits would silently desync chunk_text from page content. (3) heal splits now tick the stall watchdog's progress key via EmbedResult.healed_splits: a corpus-wide heal prelude is forward progress, not a stall, so it can't abort deterministically at the same point on every resume. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(review): mechanical maintainability fixes from the wave ship review - embed.ts: inline import('embed-stall').EmbedStallInfo -> static type import - jobs.ts: two dynamic assertEmbedNotStalled imports -> one static import - subagent(+oneshot): collapse dead ?? fallback; single extractPromptTooLongDetail walk (detail non-null iff matcher matched) - ops/admin.ts: diagnosticScope(ctx) helper replaces the thrice-repeated fail-closed ladder; scope note moved into the FIRST sentence of the get_stats/get_health/get_brain_identity descriptions (TOOL_CATALOG truncates to first sentence); catalog regenerated - ai/defaults.ts: sunsetDateHasPassed() shared by gateway sunsetHasPassed (injected-clock seam kept) + doctor provider_sunset — surfaces can't drift - stall-env.ts: shared resolveStallAbortSecondsFromEnv() behind both resolveEmbedStallAbortSeconds and sync's resolveStallAbortSeconds - backlinks.ts: @deprecated JSDoc on the insertTimelineEntry compat alias - extract-atoms/models: resolveExtractAtomsModelWithSource() returns {model, source} so gbrain models derives value+label from ONE call (fail-soft kept: config read errors -> tier_default) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(embed): pin heal drain integration, heal orchestrator, heartbeat tick timeout, and stall job wiring Four wave-audit coverage gaps in the embed lane: - test/embed-oversize-heal-drain.serial.test.ts: PGLite-backed drain pins for SUP-3874 — embedStaleForSource, embedStalePages, and runEmbedCore({stale}) each heal an oversized stored chunk in place: sweep completes, the embedder never sees the oversized text, stored rows split under the cap, and the embedded sibling's vector survives. Red-proved against both the embed-stale.ts and embed.ts call-sites. - test/embed-oversize-heal.test.ts: healOversizedPageChunks orchestrator unit pins — no-op path skips upsertChunks and returns the loaded array; changed path fires onSplit(n), upserts source-scoped split pieces, returns the RELOADED chunks. - test/embed.serial.test.ts: #4647 heartbeat pin — a never-settling refresh() under a tiny GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS times out three consecutive ticks, flips lock_lost, and aborts the drain. Red-proved by removing the per-tick Promise.race timeout. - test/jobs-embed-stall-wiring.serial.test.ts: the embed Minion handler fails the JOB (throws) on reason 'stall_timeout' and resolves on a clean result. Red-proved by deleting the assertEmbedNotStalled call. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(takes): pin cmdList negative paths, loadProposal normalization, and the real atoms retry-failure case - src/commands/takes.ts: add the /^\d+$/ whole-string pre-check to cmdList's --limit/--offset parsing so parseInt truncation ('12abc' → 12, '1e3' → 1) can no longer slip trailing garbage through silently; error copy stays identical to the numeric guards (same discipline as cmdPropose's parseId). - test/takes-list-subcommand.test.ts: negative-path pins — --limit 0/abc/12abc and --offset -1/3xyz each print the exact Invalid-flag message and exit 1 (process.exit stubbed per the commands-search convention); boundary values --limit 1 --offset 0 still pass. Red-proved by removing the pre-check. - test/take-proposals.test.ts: drive acceptProposal over a munged old-shape loadProposal row (BigInt id, string weight via an executeRaw interceptor on the 'WHERE id = $1' read) and assert the returned proposal carries numeric id AND numeric weight. Red-proved by bypassing normalizeTakeProposalRow. - test/llm-json-reasoning-ladder.test.ts: the 'preserves the ORIGINAL failure reason' test now feeds input that actually ENTERS the retry branch (bracket drafted inside <think>, retry fails with a DIFFERENT reason) and asserts the exact original reason; the old no-op-strip case stays as its own renamed test. Red-proved with a retry-masking mutant the old test missed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sync): pin reconcile/unsyncable soft-delete lanes, cycle purge window, exclude multi-pattern + throw posture Wave-audit coverage gaps in the sync lane (#4587 soft-delete, #4667 exclude): - test/sync-soft-delete.serial.test.ts: - full-sync reconcile over a removed file leaves the row EXISTING with deleted_at set (recoverable via includeDeleted) — pre-#4587 it was hard-deleted; the existing suites only asserted not-live, which a hard delete also satisfies. Red-proved with a hard-DELETE reconcile mutant. - the unsyncable poisoned-filename sweep is soft: the swept row exists with a tombstone. - end-to-end purge window: sync-originated tombstones backdated 73h are hard-deleted by the CYCLE purge phase (runCycle phases:['purge']) while a 71h tombstone and live rows survive. - test/sync-exclude-config.test.ts (fresh engine + repo describe): - a mixed comma+newline 'raw/, tmp/\nlogs/' config value excludes all three subtrees in one sync. - conservative posture: a page imported BEFORE the exclusion stays LIVE (deleted_at IS NULL) across incremental syncs AND a full-sync reconcile. - the getConfig THROW branch: sync completes and no persisted scope is applied (distinct from the existing empty-string case). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(mcp/pricing/backlinks): pin serve-http instructions, backfill cap classification, luna recipe drift, boundary + idempotency - test/e2e/connect-bearer.test.ts: real SDK initialize against the live runServeHttp process asserts client.getInstructions() === GBRAIN_MCP_INSTRUCTIONS — the serve --http lane had no instructions coverage (stdio + legacy transport were pinned elsewhere). Red-proved by dropping instructions from the per-request Server. - test/handlers-embed-backfill.test.ts: the implicit $10 default cap still ENFORCES once pricing.overrides make the model priceable (reserve+record >$10 → budget_exhausted, budgetCapUsd 10) — kills the 'capForModel returns undefined whenever defaulted' mutant every existing test passed under (red-proved); a garbage explicit cap ('garbage') classifies as implicit and runs uncapped-with-warning for unpriced models (success, no budgetCapUsd). - test/model-pricing.test.ts: the openai recipe's expansion cost_per_1m_tokens_usd equals CANONICAL_PRICING['openai:gpt-5.6-luna'].input and luna stays the declared baseline model — a price refresh touching only one home now fails the drift guard. - test/backlinks.test.ts: '## History' is a placement boundary (section lands before it — red-proved by dropping History from the regex); lowercase '## timeline' matches (case-insensitivity); the dashed '--- timeline ---' sentinel is a boundary; and a full second gap→fix→re-scan loop is byte-identical (one heading, one row). - test/mcp-tool-defs.test.ts: GBRAIN_MCP_INSTRUCTIONS carries the same REPLACES / not-a-partial-edit / get_page include_content:true phrases pinned for the put_page descriptions — ties the third client-visible home to the same contract. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(embed-backfill): stall watchdog on the production backfill lane + fail-closed garbage caps Composition review follow-through: (1) the auto-queued embed-backfill handler — the lane most likely to reproduce the wedged-drain shape — bypassed runEmbedCore and had no watchdog; it now arms one keyed on banked cursor progress, aborts the drain through the same signal the operator path uses, and fails the job (resumable) on stall_timeout. (2) A present-but-unparsable embed.backfill_max_usd means the operator INTENDED a cap: the $10 default now applies and is never droppable for unpriced models (a typo must not silently degrade to uncapped spend); 'off' keeps its documented meaning. (3) The heal orchestrator's freshness guard gets its own concurrent-rewrite pin, and the changed- path stub models the guard's recheck read. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: sync.exclude brain-global caveat (composition review F6) * test(review): withEnv for the backfill stall pin + structural-manifest regen * chore: bump version and changelog (v0.47.6.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-check pass for v0.47.6.0 — test inventory, fail-closed cap contract, sunset short-circuit, embed heartbeat knobs - docs/TESTING.md: unit-test inventory entries for the wave's new suites (sync soft-delete + exclude-config, embed oversize-heal + drain, embed stall watchdog + jobs wiring, embed.serial #4599/#4647 arcs, backfill cap classification, rerank sunset short-circuit, scoped stats/health, takes list flags, bigint normalization, reasoning-ladder, extract_atoms reporting + fail-soft, conversation-facts pricing wiring). - docs/operations/spend-controls.md: the fail-closed garbage-cap contract on embed.backfill_max_usd — a present-but-invalid value keeps the $10 default and is never dropped for unpriced models; only 'off' lifts it. - docs/architecture/RETRIEVAL.md: post-sunset reranker short-circuit behavior (fail-open, audit trail, doctor state, base_urls suppression). - docs/architecture/KEY_FILES.md: embed.ts entry gains the bounded single-flight lock heartbeat (GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS, 3-strikes lock_lost) + stall-watchdog wiring. llms bundles regenerated (no drift); check-key-files-current-state and test/build-llms.test.ts green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: apply doc-review findings for v0.47.6.0 — working sync.exclude example, provider_sunset check name, stall-env entry Cross-model doc review (Claude subagent lane; codex sandbox unavailable here) verified against source: - CHANGELOG 0.47.6.0: the sync.exclude example used a JSON-array literal the comma/newline reader never parses (silent no-op for anyone pasting it) — corrected to the working 'generated/' form with the pattern-list note; the takes list flags were documented on the MCP op, not implied by the CLI help. - docs/architecture/RETRIEVAL.md: the post-sunset reranker state is explained by doctor's provider_sunset check (reranker_health has no sunset branch and reports ok). - docs/architecture/KEY_FILES.md: entry for the new src/core/stall-env.ts shared watchdog-knob resolver (sync #1950 + embed #4599 semantics cannot drift). llms bundles regenerated; guards green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(changelog): credit wave contributors by handle + cover the models extract-atoms report (#4662) * test: widen gateway shim-cast structural pin window for the sunset short-circuit block The zeroentropy-compat-fetch source-text pin allowed 3000 chars between the last fetch-shim cast and resolveEmbeddingProvider; the post-sunset short-circuit helpers grew that gap to ~5000. Window widened to 6000 with the comment updated to name both occupants. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: lucca sapucaia <luccasapucaia@MacBook-Pro-de-lucca.local> Co-authored-by: RuiWang <224701776+ruiwang20010702@users.noreply.github.com> Co-authored-by: Nathan Maxwell <nathan@hydrolyze.app> Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> Co-authored-by: Daniel Peng <zgpeng2002@163.com> Co-authored-by: gbrain-contrib <gbrain-contrib@example.com> Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com> Co-authored-by: boundless-forest <boundless-forest@users.noreply.github.com> Co-authored-by: Matt Van Horn <mvanhorn@gmail.com> Co-authored-by: Henrique da Mota <henriquedamota@gmail.com> Co-authored-by: Andrew Levine <levineam@gmail.com> Co-authored-by: Javier Aldape <6430563+javieraldape@users.noreply.github.com> |
||
|
|
d9909cddd1 |
v0.47.5.0 fix(bootstrap): self-repairing upgrade path for older Postgres brains + blob coverage gate (#4657) (#4699)
* fix(bootstrap): repair the pre-v143 dream_verdicts upgrade wedge on Postgres (#4657) The embedded Postgres schema creates dream_verdicts_expires_idx on expires_at, but the column only lands via migration v143 — so any brain at schema v30-v142 wedged on connect before migrations could run. The forward-reference bootstrap now probes for the gap and adds the column (nullable + SET DEFAULT as separate statements so existing rows keep their judged_at-derived backfill), with v143 remaining the source of truth for backfill/NOT NULL/index. Class closure (4th recurrence of #2537/#2703/#4477): the schema-coverage suite now parses the POSTGRES blob's CREATE INDEX references too, so a blob-only forward reference fails locally at PR time instead of only on the DATABASE_URL e2e lane. Pre-v143 convergence pinned by a live e2e case (red-proven against the unfixed bootstrap). * fix(dream): harden the expires_at upgrade window (both engines) Adversarial review of #4657: if v143 fails mid-upgrade (the CLI warns and continues on migration errors), NULL expires_at rows previously read as permanent cache misses — silently re-judging the whole corpus with paid LLM calls — and the sweep never deleted them. getDreamVerdict now treats NULL as a pre-TTL hit on both engines (v143 stamps those rows when it succeeds). v143 also sets the column DEFAULT before its backfill so a legacy writer racing the upgrade can't insert NULLs between the backfill and SET NOT NULL. The bootstrap banner no longer mislabels newer brains as pre-v0.21. Module-size: both engine ceilings +1 (the NULL-tolerance SQL comment), reviewer-visible in scripts/module-size-limits.tsv. * docs: KEY_FILES bootstrap entry current-state + schema-coverage DDL-forms follow-up TODO * chore: bump version and changelog (v0.47.5.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-check pass for v0.47.5.0 — TESTING.md two-blob bootstrap gate + KEY_FILES v143 invariants TESTING.md: schema-bootstrap-coverage entry now describes both halves (PGLite registry + the Postgres-blob CREATE-INDEX class-closure gate) and the postgres-bootstrap e2e entry now lists the wedge-class convergence cases and the standalone db.initSchema path it actually covers. KEY_FILES.md: migrate.ts entry gains the v143 clause (statement-order invariant, Postgres bootstrap probe, NULL-tolerant read predicate). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: apply doc-review findings for v0.47.5.0 — probe-set superset, standalone-path honesty, e2e/TTL test entries KEY_FILES.md: postgres-engine.ts entry no longer claims the same probe set as PGLite (Postgres carries blob-only probes); forward-reference-bootstrap entry states plainly that the standalone db.ts:initSchema path does not run migrations and why that is safe. TESTING.md: drop the unsupported fresh-install no-op claim on the postgres-bootstrap e2e entry and add the dream-verdict TTL contract test entry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
c860a411f6 |
v0.47.4.0 fix(tests): the test-gap closure wave — 52 new suites, registry ratchets, fail-closed remote-surface hardening (#4654)
* fix(ops): route salience/anomaly/contradiction reads through source scope get_recent_salience, find_anomalies, and find_contradictions now honor the caller's source scope like every other read op: SalienceOpts/AnomaliesOpts carry sourceId/sourceIds (array wins over scalar), both engines filter in lockstep, the ops spread sourceScopeOpts(ctx), and a contradictions finding surfaces only when both endpoints resolve inside the caller's scope. New two-source isolation suite with anti-vacuity controls; the contradictions op-mechanics fixture moves to a trusted local brain-wide ctx. types.ts ratchet ceiling raised 1882->1890 for the two documented opts fields. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): stable error codes + gate suite for run_skillopt Four throw sites passed (message, code) into the (code, message) OperationError constructor, so remote callers matched on prose instead of stable codes (the open ErrorCode union hid it from tsc). Args swapped; a serial-lane suite pins the name validation, the remote allowlist deny-all default (incl. malformed config), the local bypass, and the caller-supplied path confinement incl. the symlinked-skills-dir acceptance branch — with the optimizer stubbed via mock.module so no real LLM run can launch from tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): extend job-envelope credential redaction to cancel/retry + registry sweep cancel_job/retry_job now apply the same private_queue_owner_token redaction as get_job/list_jobs. The suite gains both ops' redaction + null-passthrough cases and a registry-driven sweep: every id-taking jobs op is dispatched against token-bearing fixtures in two statuses and its whole envelope must never carry the raw capability — a new jobs op is swept automatically. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(schema-pack): validate pack names before any path resolution locateMutablePackFile now requires kebab-case pack names (new INVALID_PACK_NAME error code) before joining them into the schema-packs directory; both applyMutationsAtomic entry points route through it and the guard's message never echoes a resolved path. Confinement suite covers the rejection matrix, the preserved PACK_READONLY bundled contract, a positive-accept fork-shape name, and a byte-identical sentinel above the packs dir. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(ops): pin run_onboard scope gate, spend cap, and check-mode contracts Serial suite (mock.module on the dynamic runAllOnboardChecks import) pins: protected jobs land in skipped_missing_scope without the extra grant, the grant admits them, auto modes refuse without max_usd, check mode never submits, and probe failures degrade open. Also pins that the run_protected_onboard literal is absent from ALLOWED_SCOPES_LIST — making that grant mintable is a capability-model change that must arrive as its own reviewed decision, not a drive-by. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(conversation-parser): confine raw_transcript sidecar reads to the sync repo Frontmatter-supplied transcript paths are ingested content, not trusted config: absolute paths are refused, relative paths must realpath-resolve inside sync.repo_path (symlinks included), and refusals emit one class-only warn before falling back to the summary body. Suite covers the refusal matrix, legit nested sidecars (incl. under a symlinked repo path), and the compiled/timeline summary join. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(fuzz): make the upload-path confinement properties actually bite The fs-backed validateUploadPath properties passed their arguments in the wrong order and swallowed every throw, so the traversal and symlink cases proved nothing. Candidates now join into the box with the box as root, any RETURNED path must live inside the box's realpath, and a new strict:false block pins loose-mode resolution plus the always-on final-component symlink rejection. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(minions): settle embed-backfill spend into the per-client ledger recordMinionJobSpend/getJobClientId existed but had no callers, so the per-client daily spend cap enforced against a ledger generic handlers never wrote. embed-backfill now settles the tracker's spend in its finally block — every exit path, ceil'd to cents, attributed to job.data.client_id (NULL for local submissions), best-effort so telemetry can never fail the job. Suite drives the real AsyncLocalStorage tracker seam. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * ci(e2e): PR-time selected-e2e lane driven by select-e2e + wiring guard New selected-e2e job runs the diff-relevant e2e files on every push/PR: scripts/select-e2e.ts picks them (fail-closed — uncertain diffs emit ALL, selector failure fails the job), named-job and live-key files are excluded with a loud per-file echo, the job carries no repository secrets so fork PRs run it natively, and scheduled runs early-exit green (the nightly full glob already covers them and cache-writes depend on success()). Wired into e2e-cache-write and e2e-status. The wiring test pins all of that plus a shrink-only unmapped-file baseline: a new e2e file must be mapped in e2e-test-map.ts or consciously baselined, and map entries must point at real files. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(ops): satisfy required OperationContext.sourceId in contradictions fixture Follow-up to the salience/contradiction scoping commit: OperationContext declares sourceId as a required member; the brain-wide fixture ctx now carries an explicitly-unset value (sourceScopeOpts treats falsy as unscoped) instead of omitting the key. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(test): registry-walking source-isolation matrix + sources_status scope fence Every non-localOnly read op now carries an explicit disposition in one matrix suite: isolated (scoped callers see nothing from other sources, with an anti-vacuity control ladder that must SEE the foreign marker before the scoped assertions count), brain-wide (rationale string required), or skip (reason + owning suite). The table is ratcheted against the registry, so a new read op fails until classified. sources_status now answers not_found for out-of-scope source ids (anti-enumeration, matching get_agent_job's uniform envelope). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(ops): op-coverage ledger ratchet + shared registry enumeration helper Every op in the registry must map to a covering test file (existence + op-name mention verified) or sit on a shrink-only UNCOVERED allowlist (seeded with the 8 ops that genuinely have zero text-level hits today). The jobs redaction sweep and the ledger now share one registry enumeration helper so the two walkers cannot drift. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(ops): derive the localOnly snapshot + fs/child_process inverse scan KNOWN_LOCAL_ONLY was a stale hand-rolled list (missing two ops that had since gone localOnly); it is now derived from the registry and pinned to a sorted literal that catches both additions and drops. New inverse assertion: any ops module with a top-level fs/child_process import may only contribute localOnly ops or reasoned exemptions (empty today), with regex self-tests so the scan itself can't rot green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sync): pin lock-busy classification in both consumers A held per-source sync lock must classify as skipped, never failed: the minion sync handler resolves {skipped, reason:'sync_in_progress'} with the job completing, and the cycle sync phase reports status 'skipped' with syncStatus 'lock_busy' — each pinned end-to-end through the real worker/cycle with a non-lock red control proving the classifier can fail. formatLockBusyMessage's holder/remediation text and its degraded legacy path are pinned too. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(storage): first behavioral suites for the Supabase/S3 backends + injection seams Both storage classes gain an optional constructor-injected transport seam (fetch impl / S3 client; defaults unchanged) so the previously untested backends run in the fast loop: the signed-URL prefix ladder, TUS-vs-POST size routing, server-offset TUS resume, delete/exists error taxonomies, ETag dequoting, and list URL joins are all pinned, with real-vs-assumed behavior differences documented in the tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(serve): rate-limit the admin auth entry points + real-server scope-gate sweep The admin login and magic-link issuance routes now sit behind the same per-IP limiter that already guarded magic-link consumption (red-first: the exhaustion test failed before the attach), with the happy path pinned so a correct token below the limit still succeeds. The oauth e2e gains the real-server enforcement sweep: insufficient-scope envelopes + denied_after_list request-log rows, the agent-scope request_tools carve-out, scope-filtered tools/list, success_with_warnings rows, and tool_count logging. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): cross-engine INDEX parity via the dormant schema-diff helpers schema-drift now snapshots and diffs the full index set between fresh PGLite and Postgres boots (two documented one-sided allowlist entries), asserts each allowlist entry stays genuinely one-sided, and pins the three ON-CONFLICT-load-bearing unique indexes by name and definition on BOTH engines. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): whole-brain migrate-engine journey PGLite -> Postgres The previous coverage stopped at copyMigrationSources; this drives the full runMigrateEngine transfer against real Postgres: exact per-table row parity, jsonb columns land as objects (never double-encoded strings), 1536-d vectors survive with a NULL-embedding control, the facts id sequence accepts fresh inserts post-migration, config-plane rows copy with the engine row denylisted, the file config flips, and the manifest clears. The failure arm runs the real CLI in a child process (the entrypoint exits the process on validation failures) and proves config did NOT flip and the source brain is intact. Mapped in e2e-test-map so the selected-e2e lane runs it on migrate-engine diffs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(guards): runtime-reachability orphan-module guard with a test-only tier New self-tested scanner walks static + dynamic relative imports from the runtime entrypoints (CLI, MCP server, plugin engines, embedded admin) plus every package.json exports target: a src module unreachable from every entrypoint AND every test hard-fails unless it carries a reasoned allowlist entry (4 seeded, each with rationale; a stale entry fails the guard), and the 46 modules today reachable only from tests ride a shrink-only count ratchet so the tier can't quietly grow. knip v5 was evaluated first per the boring-by-default rule and rejected with evidence (hard crash on this repo layout; rationale in the script header). Registered in guards-manifest with bad/good fixtures — including a dynamic-import-only module in the good tree so the lazy-seam form stays counted — and wired into the verify battery. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): authenticated sender identity for remote job sidechannel messages send_job_message called remotely previously persisted the literal 'admin' into any live job's inbox regardless of caller. Fail-closed now: remote callers need an authenticated client identity (persisted as mcp:<client> per the existing actor convention) and are refused without one; local callers keep the explicit-sender/default behavior. Red-first suite pins both trust tiers plus terminal-state refusals on each. Ledger updated: four newly covered ops move from UNCOVERED to LEDGER (shrink-only ratchet at work); serve-http ceiling raised for the limiter attach. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(serve): structural requireAdmin guard over every /admin registration Scans all app.get/post/put/delete/patch/all/use '/admin*' registrations in serve-http (multi-line shapes and the static SPA mount included, comment lines excluded) and requires requireAdmin as pre-handler middleware modulo a rationale-bearing allowlist (credential/token entry points + SPA arms, each pinned with its expected count and mandatory middleware). Embedded bad-fixture self-test proves the extractor can fail; stale allowlist entries fail loudly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): salience write-path parity — mixed batches, touch semantics, score maps setEmotionalWeightBatch parity pinned across engines with a mixed batch (changed / same-value / missing / wrong-source rows): identical matched counts and stored weights, salience_touched_at advancing ONLY for rows whose weight actually changed, and getSalienceScores returning identical source::slug score maps with analytic expectations for the take term. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(advisor): pin the CLI exit-verdict mapping and the non-TTY apply gate runAdvisorCli driven end-to-end over a stubbed engine: critical/warn/info findings map to exits 2/1/0, --apply under a non-TTY stdin aborts with 'Aborted. Nothing was run.' and never reaches spawnSync (spied without mock.module via named-import live bindings), and unknown apply ids exit 2 listing what IS runnable — including the nothing-runnable suffix branch. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sync): mounted-brain gate + __all__ remediation in the delegate ladder New cases pin the ladder's brain gate: a non-host --brain under a live serve falls through to the direct path; a resolver throw is swallowed and the ladder CONTINUES (fail-open reality pinned, both facets); --source __all__ under a live serve returns handled with verdict 1 and the one-source-at-a-time remediation; an invalid --source is refused with verdict 1. Also fixes the file's pre-existing process.exitCode leak so it exits 0 standalone. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): takes write-op journey on real Postgres Op-layer coverage for takes_add/update/resolve/supersede over live PG: fence-first writes with the DB mirror, the takes_mirror_unavailable envelope on both unset and missing repo paths, concurrent takes_add on one slug serializing under the page lock (plus the deterministic lock-held-past-budget retryable arm), resolved-row immutability with per-op suggestions, and supersede close+link column semantics. Mapped in e2e-test-map for the selected-e2e lane. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(cycle): cast the two propose-takes JSONB binds + pin cycle writers on real Postgres Both uncast positional binds feeding the dedup fence rows and the empty-extraction tombstone double-encoded to jsonb string scalars on real Postgres (captured red-first: jsonb_typeof returned 'string'); PGLite hides the class, which is why no unit test ever saw it. Fixed via the blessed $N::text::jsonb hop. New DATABASE_URL-gated suites drive runPhaseProposeTakes (both write sites) and runPhaseCalibrationProfile (object typeof + text[] round-trip) end-to-end. The check-jsonb-params scanner now also flags UNCAST positional binds fed JSON.stringify into known-JSONB columns, with bad/good self-test fixtures; both new e2e files are mapped for the selected lane. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sync): pin collectGitVisibleFiles edge arms Tracked-then-gitignored files are excluded via the ls-files -ci subtraction (proven against --cached, not untracking), tracked and dangling symlinks are skipped without throwing, results are sorted absolute paths from the cached+others union, non-git dirs return null, and acceptRelPath sees forward-slash relative paths with veto power. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): /ingest fails closed on the pre-v85 client-binding rung With oauth_clients.bound_slug_prefixes absent (simulated by a rename with finally-restore against the live server), a valid write token gets 403 with the apply-migrations remediation — the degraded projection can never fall open to an unbound write. Control + recovery arms prove the same request is accepted with the column intact. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(chronicle): scope the event-page join + diary redaction on timeline reads The chronicle read paths' event-page LEFT JOIN was unscoped in both engines (the same far-endpoint class the links ops fixed in #2200): a scoped caller's own timeline row could surface an out-of-scope event page's slug, date, and kind, and last-seen could date-stamp an entity from an out-of-scope sighting. The join now carries the caller's scope in lockstep on both engines (rows survive; foreign event fields null out; trusted brain-wide callers unchanged). Timeline ops also gain the diary redaction the ontology siblings already had, fail-closed on remote-or-undefined trust. Red-first suite pins scoping, the cross-row arm, redaction on all five ops, and the brain-wide controls; one residual last-seen shape gap is documented in the suite rather than silently widened. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(skillpack): pin the resident-skill locate fences getResidentSkillDetail's three fences pinned with anti-vacuity controls: the 64-char kebab slug gate fires before any engine or fs access (counting-engine proof + exact boundary at 64/65), out-of-scope federated and scalar sources answer not_found with in-scope fetch controls, and a manifest-listed skill dir swapped for an outside symlink hits the realpath confinement error. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): pin the cross-engine CJK keyword asymmetry as a documented gap PGLite's bigram/ILIKE branch finds CJK substring queries; Postgres has no CJK branch and its degradation shape is locale-regime dependent — C-locale websearch_to_tsquery silently DROPS CJK terms (mixed queries can false- positive) while UTF-8 keeps them as whole-run AND lexemes. The suite pins the shared empty-result invariant unbranched, probes the regime at runtime for the divergent mixed-query arm, and carries flip instructions pointing at the filed pgroonga follow-ups for whoever builds the Postgres branch. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(code-intel): pin per-op scope contracts — fenced walks, scoped edges, documented brain-wide lookups code_blast/code_flow's resolveCodeIntelScope fence pinned (remote-no-scope refused, multi-source grants rejected, walks + disambiguation stay in scope with cross-source controls); code_callees' remote scalar/federated isolation pinned with all_sources grant-collapse; code_def/code_refs pinned as the in-code documented brain-wide contract with a deliberate tripwire so any future scoping change fails this suite consciously. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(evals): takes-bootstrap graduation instrument — 123-case corpus, scorer, live/replay harness The TODO-E gate gets its instrument: a deterministic 41-archetype x 3 label-invariant-variant corpus (privacy-safe placeholders) spanning the four take kinds plus the precision classes (empty pages, attribution traps, injection/noise adversarials); a pure scorer with per-kind precision/recall bars where an unparseable case is a FAILURE never a skip and forbid-regex violations block graduation; and a harness that drives the REAL extractTakesFromPages path per case against throwaway PGLite in live mode with a $0 replay re-scorer. Keyless CI validates the corpus, the arithmetic, the graduation boundary, and label satisfiability via an oracle pass; the autopilot tier stays manual_only until a live run graduates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(context): unsafe session ids round-trip checkpoint compaction + tri-copy sanitizer drift guard 'oc:sess/2026-08' survives compact->assemble with the same sanitized key on every wire request and corpus filename; the sanitizer contract is pinned (null for degenerate ids, charset, 120-char clamp); and a drift guard maps a probe set identically across all THREE sanitizer copies (context-engine, hook.ts, corpus-segments) while pinning their deliberate sentinel divergence loudly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): dry-run short-circuit for pause_job/resume_job + lifecycle behavioral suite The lifecycle suite surfaced that pause_job and resume_job lacked the mutating-op dry-run convention — a dry_run:true dispatch still flipped the row. Both handlers now short-circuit with the declared envelope and carry mutating:true. The new suite pins all seven queue-row ops end-to-end on a real PGLite queue: dry-run postures, the actual state machine (cancel's lock-clearing set, retry's fresh-run column reset, replay creating a NEW row with the source untouched and cancelled deliberately non-replayable, token-fenced progress reads), and incompatible-status refusals. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): mount routing journey — resolver tiers, dotfile trust, disable fallback Real-CLI journey over two live PGLite brains pins the resolver ladder (flag > env > dotfile walk-up > registered-mount path prefix > host), the dotfile trust guards (symlinked and world-writable dotfiles refused fail-closed to host), the host opt-out, write-side routing, and disable → ambient host fallback with explicit --brain failing loudly. 20 spawns, ~25s, hermetic env scrub incl. the homedir-derived mounts path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): autopilot linux lifecycle under PATH-shimmed crontab/systemctl Install/reinstall/status/uninstall driven through the real CLI with a round-tripping crontab shim and a systemctl argv recorder: foreign cron lines survive byte-identical through every phase, reinstall is idempotent (no table rewrite), uninstall removes only the autopilot line, the systemd unit lands 0644 with the exact command sequence, and status exit codes pin the installed-but-never-run contract. CI's ubuntu runners finally get behavioral coverage of this platform's only install path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(doctor): behavioral suites for four previously-inspection-only check modules Schema-pack consistency (worst-source attribution, the 10% warn boundary pinned at 10.0 vs 9.9, fail-open on probe throw, source-drift arms), brainstorm health (all four track_retrieval off-variants, cold-start messages, degraded-probe warn), skill checks (corrupt manifest is an ok skip never a warn, tamper listing, +N-more truncation, missing-bundled recommendation), and the memory-verbs sidecar (torn-line fail-open truth pinned via the module's own path seam — stronger than the planned warn). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(minions): dream quota degradation across all three consumers Pins the admission-quota degradation contract (plan C3, TODOS.md:930) at each consumer: cycle patterns phase reports skipped/admission_quota with zero child rows; synthesize latches after one refusal (1 submit attempt for 3 transcripts, cooldown unstamped, filler untouched); agent fanout tree-cancels (aggregator + submitted children cancelled, exit 1). Three anti-vacuity controls prove ample quotas admit. Uses the real admission policy cache reset seam; no mock.module. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(protocol): pin the MEMORY_VERBS protocol document shape Plan B5: ordered deep-equality of Object.keys(doc.verbs) against VERB_NAMES kills the filter(Boolean) silent-drop class; every verb entry carries non-empty input_schema.properties + a response_schema requiring protocol_version const 1; doc.protocol_version pinned to literal 1; the error_schema enum must contain all seven documented error codes (containment, not equality — the contract is additive-forever). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(serve): sync IPC kill-switch narrows without blinding Plan F4: with GBRAIN_SERVE_SYNC_IPC=0 a real startMcpServer (child process — its stdio transport wires onclose to process.exit) answers sync_start/status/abort with unsupported_kind while resolve and turn_context still work; a control child with the switch unset answers unknown_job, killing the broken-import masquerade. Client side: maybeDelegateSyncToServe returns HANDLED with the documented remediation and exit verdict 1 — the direct sync path never runs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(audit): timestamp stamp survives an explicit undefined ts + advisor/suggest suites Plan E4. Src fix (red-first): connection-audit's ts stamp now lands after the event spread, so a caller passing ts: undefined can no longer erase the timestamp from the JSONL row. New suites: advisor collectMigration (fail-toward-migrate on probe failure pinned as reality) + collectUninstalledBrainPack five-gate matrix (remote suppresses before touching the engine); connection-audit ISO-week filename drift guard across implementations + URL credential redaction; schema-pack suggest confidence clamps (non-finite falls to 0), dedup keeps first, and the 0.5 heuristic fallback sits below the 0.6 auto-apply floor (source-text guard pins both literals). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): thin-client daily-driver verbs live over the wire Plan G3: search/query/recall --json run from both the host HOME and the thin-client HOME against a live serve — per-row key-set equality pins routed results identical to local; invalid client secret and a stopped host both exit 1 with the canonical RemoteMcpError surfaces and a fail-fast bound. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): getHealth parity on real Postgres Plan D8 (TODOS.md:643-655 item b): mirrors the PGLite-only islanded-liveness unit fixture onto both engines — entity_page_count below/at the coverage floor, null link/timeline coverage below the floor with identical real ratios at it, and orphan_pages agreeing on the dead-inbound/dead-outbound islanded JOIN semantics. Mapped in the e2e test map on all four engine rows. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(skillopt): dream-cycle cost caps behavioral suite Plan H2 — the only brake on an unattended nightly LLM spender. Pins: strict-string feature-flag gate skips with zero runner calls; once mode runs without persisting the flag (per-skill last_run bookkeeping still banks); the brain-wide cap boundary is >= and checked before the run (at-cap skips, a cent below runs capped to remaining); effective per-skill budget is min(perSkillCap, remaining); abort breaks the loop rather than skipping. Ample-cap control proves all candidates run with the default budget and nightly-safety opts (epochs 1, noMutate). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(eval): conversation-parser scorer fails positive fixtures with unrecognized headings Plan H3 (red-first pair): a heading-anchored pattern regression that folds an out-of-set heading into another speaker's turn kept perfect recall, so scoreFixture passed silently. Positive fixtures now fail with a reason naming the folded labels; the adversarial (pattern null) fixture class keeps its semantics. Corpus gate stays 24/24. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): --surface verbs ceiling over a real HTTP serve Plan G6: hermetic PGLite serve boot pins the frozen 7-verb tools/list for both bare and full-preset clients, the fail-closed unknown_operation envelope on hidden ops, that GBRAIN_MCP_FORCE_SURFACE is narrow-only by construction (min() into the CLI ceiling — cannot widen), and a remember/recall round-trip carrying protocol_version 1. Mapped on the surface implementation module. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): legacy no-grant token federated widening over /mcp Plan G6 (TODOS.md:643-655 item a): transport wiring for the no-grant-federated-scope decision — a legacy token without a source grant sees exactly the locally-federated source set over real /mcp (list_pages source set + cross-source get_page), while a grant-bearing token stays confined to its grant even though the granted source is itself federated (the anti-vacuity contrast pair). Construction-site pin on verifyAccessToken's hasSourceGrant flag. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(claw-test): exhaustive every-fixture-loads guard with orphan ratchet Plan G6 (TODOS.md:5529-5545, guard half): every shipped claw-test scenario fixture must load with coherent config; listScenarios silently filtering a dir missing scenario.json is now visible. The voice-agent-install fixture joins a two-sided KNOWN_ORPHANS ratchet — it must stay well-formed AND keep failing to load, so landing the ScenarioKind wiring forces the entry out of the map. The wiring half stays infra-gated: claw-test's phase runner branches only on 'upgrade', so a loader-only extension would run a bogus fresh-install pass — noted in the ratchet. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(cli): promptLine EOF/timeout/stream contracts Plan E3 wave-5 slice: child-process-driven pins on the interactive prompt helpers — promptLineStderr resolves null (never '') on EOF, bare Enter is '' not null (the truthiness footgun from both sides), answers are trimmed, timeouts with stdin held open resolve null, prompts route to the right stream, and promptLine's no-EOF-handler hang is pinned as reality so a contract change surfaces. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(ops): file_upload defaults to strict confinement when remote is unset Plan A6 op-level companion (eng E24): remote: undefined on the dispatched op takes the strict path exactly like remote: true — an outside-cwd probe is rejected invalid_params — while the trusted remote: false control genuinely uploads the identical probe (loose mode relaxes confinement only; final-component symlinks stay rejected in both modes). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(dream): keyless dream exits 0 with the documented degraded posture Plan G6 (TODOS.md:1661-1674): the nightly cron's unattended keyless run is pinned — exit 0 with status partial across three invocations (json and plain spellings), embed is the only structured-fail phase (the --no-embedding refusal text), propose_takes/synthesize skip with their real keyless diagnoses, no phase carries a crash signature, and the sync half still banks a page (anti-vacuity). Child env is allowlist-built so every provider var is absent by construction. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(verbs): error-path conformance fixtures for entity, context_pack, synthesize Plan B6: every verb that can error now carries an error fixture — entity missing its required param, context_pack malformed since (advertised-only so pre-v0.45.7 endpoints still certify), and the keyless synthesize arm now actually executes in CI via a forced-keyless runConformance self-cert (previously nothing exercised the synthesize error arm). Each new envelope is pinned directly for protocol_version 1, non-empty suggestion, and ERROR_SCHEMA validity. recall stays error-fixture-free by design (degrade-never-error). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(cli): cache/remote/sources-demo hardening batch Plan E3: cache clear refuses without --yes (zero deletions), scoped clear and TTL prune delete exactly their rows, and the 'clear --source --yes' ordering footgun is pinned as reality (binds sourceId='--yes', deletes nothing, exits 0). remote CLI: --timeout 90s/5m/2h parse to real second budgets and malformed input takes the 15m default (never 0/NaN), one poll blip survives, failed jobs exit 1 with failed_reason in --json, non-thin-client config refuses with the init hint before contacting the host. sources demo: writes only under --dir, honors --limit, usage errors exit 2 writing nothing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): read-path parity batch — graph traversal, restore, code edges, ontology merge, event projection Plan D7. engine-parity gains traverseGraph/traversePaths blocks (cycle guard terminates identically at depth 25, in/out/both endpoint scoping, sourceIds variants) and the restorePage arc (second restore false; scoped restore never crosses sources). New suites: code-edges read parity (parsed edge_metadata objects would catch a double-encode), ontology merge matrix (inserted/corroborated/noop/superseded_prior with row-for-row facts dumps, quarantine visibility, asof time-travel, conflict detection), and the first tests anywhere for upsertEventProjection (idempotent single timeline row updated in place — proves the partial dedup index exists on real Postgres). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(engine): mergeOntologyFact returns supersededId as a number on Postgres Surfaced by the D7 ontology parity suite: the Postgres engine passed current.id through un-normalized, returning a runtime BigInt where the OntologyMergeResult contract says number | null (PGLite returns plain numbers; factId was already Number()'d). The parity test now pins the runtime type instead of comparing value-normalized. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): upgrade bun-link arc under a PATH-shimmed toolchain Plan G6: the from-source upgrade journey fully offline — detection via the .git/config remote marker walk (foreign-remote negative control), real git pull --ff-only against a local bare origin ordered before the shimmed bun install (recorder proves the clone was at origin HEAD at install time), the post-upgrade migration ledger advancing exactly one completed entry then idempotent on rerun, and --swap-only stopping after the swap. The dev checkout is tripwired against ever being the upgrade target. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): real SIGKILL mid-sync resumes exactly-once on Postgres Plan F7: a child sync with CHECKPOINT_EVERY=1 is killed on the first banked op_checkpoint_paths row (DB-polled, never sleep-then-kill). Pins: partial banked set with last_commit frozen, the stranded lock refuses an immediate retry naming the dead pid (grace fail-closed), and after the holder ages past TTL + steal grace the second sync resumes from the checkpoint — 31 pages, all distinct, bookmark advanced, checkpoint and lock rows cleared. Suite-scoped source id keeps the shared DB safe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(engine): mechanical surface sweep + searchVector escalation positives Plan D9 (TODOS.md:508-517): a two-way interface census pins all 152 BrainEngine methods against the PGLite prototype (new methods force a visible list edit) with a runtime shrink-only UNCALLED ratchet scanning the whole test corpus. Five never-called methods gain real-shape smokes; getPageTimestamps (deprecated since v0.29.1) and getTakeEmbeddings are flagged as zero-src-caller deletion candidates. Escalation wiring: fire-at-cap positive (1120 dense chunks walk 100→400→1000 with underfilled telemetry) and the exact-scan lane for >2000-dim columns, proving the cap keys on the column descriptor, not the physical index. Postgres halves stay e2e-deferred. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: strike completed test-gap TODOs and document the new ratchets and lanes TODOS.md: seven entries marked done with what-landed notes (parser scorer strictness, chennai test-debt trio incl. one refuted item, dream quota degradation, keyless dream contract, searchVector escalation positives, PR-time e2e selection, request-log rows); TODO-E annotated instrument-shipped/graduation-pending; the coverage-gate flip and claw-test wiring annotated with their remaining gates. TESTING.md gains the registry-walking ratchets section (ops ledger, source isolation matrix, e2e wiring, engine surface census, orphan-modules guard, takes-bootstrap instrument guard) and a grouped inventory bullet for the wave's e2e journey suites. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(evals): corpus privacy tripwire sources banned tokens from the guard scripts The takes-bootstrap corpus lives under evals/, outside the privacy guards' scan surface, so the keyless test re-applies their token lists to it — but the first version embedded the literals, tripping check-privacy and check-test-real-names on the test file itself. The tokens now parse out of the two guard scripts (their one allowlisted home) via a line-state walk that skips comment text, so the tripwire tracks the guards' lists automatically. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate structural-suites.tsv for the guard-sourced privacy tripwire Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sources): scope the sources_status happy-path fixture to its own source The wave's scope fence on sources_status (out-of-scope id answers not_found) correctly rejects this fixture's default-scoped remote ctx reading a different source. The test pins the status payload, not scoping (the fence has its own suite), so the caller is now scoped to the source under test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: pre-landing review fixes — validation parity, scope-boundary alignment, ratchet tightening Src: the pack-name validation now guards every pack lookup surface through one shared predicate, with its charset aligned to the manifest schema's own rule (pre-existing packs with dots/underscores stay mutable); the sources_status confinement now mirrors the documented sources_list boundary (federated grants confine, the scalar floor and trusted local do not) with an anti-enumeration answer shape; remote-submitted job payloads carry the authenticated client identity for spend attribution; find_contradictions filters before its scope pass (bounded existence probes), early-exits at the limit, and applies the same world-visibility filtering as its sibling read ops; the admin auth limiter answers 429 with a JSON envelope. Tests/guards: coverage-ledger and e2e-baseline ratchets lose their stale slack (seeds track current lengths); the corpus freshness test now byte-compares and never dirties the tree; the isolation matrix rejects non-OperationError crashes on scoped calls, derives all dates from one captured instant (leap-day-safe), and expresses the federated-vs-scalar boundary per row; supabase upload failure arms pinned; six previously-unclaimed e2e files mapped (baseline 159→153); the contradictions e2e mechanics fixture uses a trusted brain-wide ctx. Docs: KEY_FILES chronicle entry updated to current redaction behavior. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ops): contradiction fences verify before the limit cutoff Adversarial-review finding: the scope and world-visibility fences ran after the limit-bounded keep loop, so droppable findings ahead of visible ones could starve the response (fewer rows than exist, with total_in_run claiming completeness). Both fences now run before a finding counts toward the limit, batched so the visibility keep-list stays one query per batch. Red-first regression pin included. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: bump version and changelog (v0.47.1.0) Five-file version lockstep (VERSION, package.json, openclaw + codex + claude plugin manifests), runbook stamp, regenerated template repo and plugin trees, refreshed lockfile, and the v0.47.1.0 CHANGELOG entry. Slot advanced past open PR claims (0.46.35.0 x2, 0.47.0.0) per the queue-aware allocator. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test: absorb master-wave deltas the census and storage precondition surfaced The D9 engine census classifies master's three new methods (bulk config read, takes-embedding update, scoped link removal) and shrinks UNCALLED — wave-k gave getTakeEmbeddings real coverage, so its shape pin moves out of the allowlist-driven smoke map. The file_upload trust-default suite configures a local storage backend, required since master's no-backend refusal landed ahead of the insert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(e2e): absorb master-wave behavior changes surfaced by the full-glob run The CJK suite flips its documented-degradation pins to parity per their own flip instructions — master's #3986 gave both engines the shared CJK keyword branch, so the asymmetry the suite pinned no longer exists (the locale-regime probe goes with it). The autopilot lifecycle suite passes --force and pins master's new PGLite single-writer refusal (install without --force exits 1 recommending gbrain serve, crontab untouched). The thin-client seed clears a stale shared-DB sync.repo_path left by prior suites in the glob, which made put_page's reverse-write refuse. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: absorb the v0.47.1.0 scope-fence and CJK-parity outcomes into the reference docs qm-harness.md's isolation-model section stops listing the activity/anomaly/ contradiction/source reads as brain-wide (they now honor the federated grant) and documents the one residual — find_contradictions matches findings by slug within the grant, with the harness-layer mitigation and the filed follow-up. TESTING.md's e2e journey inventory updates the engine-parity-cjk.test.ts description from the pre-#3986 documented- degradation pins to the current cross-engine parity pins. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ci): classify sweepDreamVerdicts in the engine census + annotate corpus-regex sites for semgrep The D9 census fired on wave-k's sweepDreamVerdicts (TTL housekeeping, covered by test/dream-verdict-cache-ttl.test.ts) — classified into INTERFACE_METHODS. Semgrep's non-literal-RegExp rule flagged the three takes-bootstrap scorer sites: the patterns come from the committed, PR-reviewed corpus (regex-compiles pinned in the keyless suite), never runtime user input — annotated with the repo's nosemgrep idiom and the rationale inline. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
1e7093aca5 |
fix(cycle): skip extract receipts in propose_takes candidate discovery (#4621) (#4644)
Excludes `extract_receipt` pages from `propose_takes` candidate discovery via a WHERE predicate, so the phase stops re-ingesting its own operational receipts into the LLM extractor lane. Closes #4621.
Autonomous triage verification (gbrain-pr-triage, MEDIUM tier):
- Floor: merged with current master (
|
||
|
|
17eff27cf0 |
v0.47.3.0 fix: wave-L — wave-k close-out (stricter sources_list confinement #4433, memory writeback contract #4105, reference docs) (#4663)
* fix(sources): confine sources_list for scalar/no-grant remote callers too (#4433) Wave-g's #4433 fix row-filtered the listing only for callers WITH a federated grant and deliberately left the remote scalar default-source floor unfiltered, on the rationale that such a caller can read any source by naming it. The maintainer has now adopted the stricter posture: EVERY untrusted caller (anything not strictly ctx.remote === false) is confined through the canonical sourceScopeOpts ladder, matching the rest of the read-op surface — federated grant > scalar bound source > fail-closed '__all__' (the sentinel passes through as a literal that matches no real source id, so a remote caller gets an empty listing rather than the whole registry). Bulk enumeration of the source table (id, name, page_count) is gone for scalar/no-grant remote callers; reading another source stays an explicit, audit-visible act. The trusted local CLI keeps the full operator listing. No SQL change: the scope maps onto wave-g's existing allowedSourceIds row filter in listSources (shared executeRaw path — both engines covered). Supersedes the wave-g pin in test/sources-list-scope.test.ts (the "remote scalar default-source floor keeps the full listing" test now pins the confinement); the full scalar/no-grant/'__all__' matrix is pinned in test/sources-list-scalar-confinement.test.ts. BEHAVIOR CHANGE for remote MCP clients: sources_list no longer returns sources outside the caller's resolved scope. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bootstrap): enforce same-turn memory writeback Absorb PR #4105 onto current master: additive AGENTS.md write-back contract (audit/repair via `gbrain bootstrap contract [--repair]`), a writeback_contract verify check, the always-on memory loop section in skills/_AGENT_README.md, and template routing of atomic facts through `remember` with explicit provenance. Ported past post-PR drift: - bootstrap.ts: merged with the opencode harness lane ('harness' subcommand, opencode help text) and the restructured dispatcher. - verify.ts: merged imports with the source-resolver lane. - test/bootstrap-verify.serial.test.ts: the #4328 uninitialized-workspace test now seeds the integrated-gate AGENTS.md so the new check passes while the test keeps proving source resolution. - Regenerated skills/skills.lock.json, plugin/, and plugin-variants/ for the _AGENT_README.md change. Absorbed-from: #4105 Co-authored-by: garrytan-agents <garrytan-agents@users.noreply.github.com> * docs: reference homes for apply-migrations flags, embed quarantine knobs, and config get --raw Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.47.3.0 release: version lockstep bump + CHANGELOG + regenerated trees --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: garrytan-agents <garrytan-agents@users.noreply.github.com> |
||
|
|
a9ce8971ca |
docs: post-release audit for the wave-k maintainer train (#4650 follow-up) (#4656)
Coverage audit of v0.46.35.0's public surface against the docs; factual corrections only, one per file: - skills/migrations/v0.46.35.0.md: fix the H1 — the note shipped titled v0.46.34.0 but the config-get redaction behavior change is v0.46.35.0. - docs/protocol/MEMORY_VERBS_v1.md: synthesis_status enum gains output_truncated and the warnings examples gain LLM_OUTPUT_TRUNCATED (#4375 — verbs.ts SYNTHESIS_STATUS_ENUM / SYNTHESIS_FAILURE_CODES now carry both); the refusal-parsing note now distinguishes a max_tokens-cut envelope from malformed output. - docs/architecture/KEY_FILES.md: doctor entry gains the shipped --no-migrate flag (probeOnly connect, observational doctor, #4364); budget-tracker entry's reserve() contract now states cumulative + outstanding admission (#4365 concurrent-reservation fix). - docs/architecture/system-of-record.md: dream_verdicts row documents the 30-day expires_at TTL from migration v143 (expired reads are misses, synthesize sweeps). - docs/integrations/embedding-providers.md: OPENAI_BASE_URL section states the keyless local-endpoint override (#4385 — placeholder key when a base URL is set); Ollama model list corrected to the real pullable tags qwen3-embedding:8b / snowflake-arctic-embed2 (old spellings kept only for validation). - llms-full.txt: regenerated (inlines MEMORY_VERBS_v1.md). - skills/skills.lock.json: regenerated for the migration-note hash. verify 54/54 green. Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
b36ec092b0 |
v0.47.0.0 feat(google-loops): Gmail-first open-loop engine — connector, credential vault, gbrain waiting (#4590)
* feat(creds): generic credential vault + Google OAuth client + hosted-relay stub src/core/creds/: provider-agnostic CredentialVault (0600 file backend, DB backend interface for hosted), typed CredentialError catalog (problem/cause/ fix/doc_url per failure), Google OAuth2 client (PKCE loopback + headless paste-back; invalid_grant sub-classified incl. the 7-day Testing-mode expiry heuristic and clock-skew detection), gbrain.io relay client (feature-gated, zero-retention claim protocol; its test suite is the server conformance spec), and scrypt+AES-GCM export bundles for hosted-upgrade transfer. No googleapis dependency; every client is fetchImpl-injectable. * feat(google): Gmail/Calendar/People API clients + pure page renderers GoogleApiClient with 401-refresh-retry, Retry-After honoring, and api_not_enabled deep links (project number extracted from the client id); GmailClient (history deltas, thread fetch with MIME walk + quoted-reply trim), CalendarClient/PeopleClient (syncToken with 410 recovery). Renderers are pure: thread pages keyed on the first message (stable slugs), code-generated Gmail deep links via the emailCitation scaffold, noise/ signature rules from recipes/email-to-brain.md implemented as code. * feat(loops): open_loops substrate + deterministic thread-state detector Migration v142: open_loops (dedup per source, close-by-state-transition, fact_id projection) + loop_suppressions (gbrain loops mute). Store rides engine.executeRaw with identical SQL on both engines (parity by construction); timestamps normalized to ISO strings; evidence binds through $N::text::jsonb. Detector: zero-LLM thread-state machine — unanswered inbound (they wait on you, 24h grace, To:-only) / unanswered outbound (you wait on them, 72h grace, question heuristic); noise/list/self/CC-only excluded; reply auto-closes; suppression never closes existing loops. Pinned by a 45-case labeled precision corpus. * feat(google): --kind google source + sync orchestration + LLM loop extraction sources add <id> --kind google --account <email> (vault-pointer config, no secrets; CLI-only registration like github). runGoogleSync dispatches from performSyncInner: contacts -> calendar -> gmail (aliases exist before counterparty resolution), per-service cursors commit only on full success, and the initial Gmail backfill is explicitly resumable (newest-first floor cursor, batch-committed, never advanced past a failed thread; 404 threads skip instead of wedging the delta cursor). loops_extract minion job (gateway-refresh registered): ONE model call per recent thread projects commitments into open_loops + a facts row (kind=commitment, fence-first) + typed owes_to/awaiting_reply_from edges (added to KNOWN_LINK_TYPES + the base pack). All-or-nothing parse barrier with calendar-real due-date validation; injection-hardened; trickle + 30-day window only; kill switch loops.extraction_enabled; 50/sweep cap. * feat(loops): open_loops ops + gbrain waiting/loops/google/creds CLI + doctor check open_loops (scope read, fail-closed evidence redaction for remote callers; quotes/deep-links/text digest trusted-local only), loops_close (expires the projected fact), loops_mute. gbrain waiting refuses on stale google sources and names the exact fix; gbrain google connect/setup/status/disconnect implements the [SHOW USER] agent protocol (GCP checklist, client_secret.json intake incl. stdin, two-interaction setup, funnel heartbeats); gbrain creds is the provider-agnostic vault surface. Entity cards surface loop-backed open_threads with additive optional fields (direction/due/counterparty/ status/loop_id — MEMORY_VERBS v1 additive-legal). google_oauth doctor check warns at day ~6 of a Testing-mode consent screen, before Google kills the tokens at day 7. All exit codes route through setCliExitVerdict. * docs(google-loops): skill, rewritten recipes, guides, relay design doc, plugin regen skills/google-loops (harness contract: relay [SHOW USER] verbatim, exactly two user interactions, secrets never in argv); recipes/credential-gateway + email-to-brain + calendar-to-brain rewritten to drive the real commands; docs/guides/google-connect.md (setup + the full typed error catalog) and open-loops.md; docs/designs/HOSTED_OAUTH_RELAY.md (the gbrain.io team spec: confidential-client relay, zero-retention claims, CASA track); briefing + daily-task-prep + executive-assistant now call gbrain waiting; KEY_FILES cluster entries; plugin tree regen (66 skills, google-loops bundled with recorded starter gaps); module-size ratchet bumps; TODOS follow-ups filed (relay server + CASA clock, Pub/Sub push, fulfillment-by-reply, providers). * test(loops): classify the three loop ops in the remote privacy sweep registry open_loops → 'ok' (fail-closed redacted envelope for remote callers); loops_close / loops_mute → 'error' on the sweep's generic empty invocation (required params). Redaction + remote-scope semantics pinned in test/ops-loops.test.ts. * fix: pre-landing review fixes (specialist army pass) Security: loops_mute scalar-scope bypass closed (remote writes stay strictly inside the caller's grant, mirroring loops_close) and both write-op denials now throw enumerated OperationErrors instead of success-shaped payloads; --via relay base requires https and resolves 'gbrain.io' only through the GBRAIN_OAUTH_RELAY_URL gate; full-URL pastes must carry the matching OAuth state; delete/reconcile rmSync paths get the same containment guard as writes. Performance: the Gmail backfill lists page-BOUNDED (partialOk) so a >50k- message window can't wedge on the pagination cap; open_loops gains a (source_id, thread_id) partial index; deepLinksFor is source-scoped onto the composite pages index; HTML bodies pre-truncate before conversion. Contract: creds/waiting/loops --json envelopes carry consistent ok/status (+ export --json, show honors --json, status exit-code parity across output modes); open_loops reports a truncated marker at the 500-row fetch ceiling; the EntityOpenThread additive fields land in the response-shape registry + MEMORY_VERBS_v1.md (loop-backing subsection documents the kind derivation). Durability: engine migration copies open_loops + loop_suppressions (manual mutes/closes are not re-derivable); sources remove cleans g_managed dirs. Maintainability: shared deriveSourceId (connect hint can't diverge from setup), pending two-step flow honors step-1 scopes, setup no longer dies on tail-only flags, single connect_error funnel emission, dead --yes flag and GBRAIN_OAUTH_RELAY_ENABLE gate removed, service-list/sha8 dedup, stale comments fixed, doc_url anchors land on #troubleshooting. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: red-team hardening wave + coverage-gap tests + 4 surfaced CLI/op bugs Red-team fixes (batches A-E): tri-state thread-loop verdicts (turn-flip-only closes; grace/noise/suppression are holds, not closes), gmailSweepOk gating of last_sync_at, per-group source_id for entity-card context, migrate-engine sequence setval, calendar event_id keying for reschedules, scope preflight + scope_missing tracing, vault O_EXCL lock (EEXIST-only contention, parent-dir mkdir, post-network re-read merge), atomic state writes + .corrupt quarantine, bounded history-fallback with conditional re-anchor, markStaleLoops overdue now also requires 14d inactivity, loops idempotency keys fold the source. Coverage-gap test wave: 4 new suites (loops CLI, google connect state machine, oauth doctor, source reconcile) + 7 extended (relay-client, clients, redirect, materialize, extract-run, ops-loops, engine-parity open_loops section). Bugs the wave surfaced, fixed here: - gbrain waiting / loops read paths were silently scoped to source 'default', hiding every loop in a real google source; they now span the brain (__all__, trusted local) with --source to narrow, and loops mute resolves the single google source instead of writing a useless 'default' suppression. - open_loops now fail-closes an unscoped remote caller (permission_denied) instead of spanning every source, per the trust invariant. - loops show no longer renders a literal "undefined" status (view carries status); done/drop --json keeps the envelope status ('closed') and moves the row's terminal state to loop_status instead of clobbering. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.47.0.0 feat(google-loops): Gmail-first open-loop engine — version bump, CHANGELOG, manifest lockstep Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: raise sources.ts module-size ceiling to 1876 (v0.47 google source-kind flags) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: adversarial-review wave — sweep honesty, close-guard, vault/OAuth hardening Six High findings from the fresh-context adversarial pass, all fixed with regression pins, plus seven mediums: - A persistently-failing Gmail thread can no longer wedge the pipeline while the staleness gate reads fresh: sweepGmail reports thread-level failures via its return value (failed sweeps never stamp last_sync_at) and a per-thread fail ledger skips a thread after 3 consecutive failures — loudly, with --full retrying it. - Manual `gbrain loops done/drop` survives sweeps: the upsert's reopen now requires genuinely newer activity, so label-only history touches and same-content re-extraction leave closed loops closed (upsertOpenLoop returns `applied`). - Vault lock fail-open paths no longer delete another process's live lock. - The vault persists the scopes Google ACTUALLY granted (consent lets users uncheck) so narrowed grants surface as scope_missing, not opaque 403s. - Contact deletion tombstones (no names attached) and renames resolve by google_contact_id in the DB — deletes land, renames don't strand pages. - The history-expired fallback anchors before listing (zero-gap ordering). - Mediums: freshness gate fails toward stale on error; LLM evidence quotes verified verbatim against the thread (fabricated quotes dropped, edge label falls back to the commitment text); two-step connect keeps the --account binding, clears consumed pending state, and survives corrupt timestamps; replacing the OAuth client warns about client-bound sibling refresh tokens; malformed relay expiry can't crash connect; creds import arg parsing skips valued-flag values; suppression cache keyed per engine; doctor treats a missing expiry as unknown, not expired. INVESTIGATE-class findings (auto-reply/spoof close precision, model-worded commitment dedup, extreme-volume history caps, per-loop staleness markers) filed as P3 follow-ups in TODOS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: full-suite gate wave — skill conformance, resolver triggers, recipe pin, pack bump, flag registry The fresh evidence run's in-branch failures, all six fixed: - skills/google-loops/SKILL.md gains the required Output Format and Anti-Patterns sections and quotes its frontmatter triggers so the RESOLVER round-trip parser sees them. - gbrain-base-v2 bumps to 1.2.0 for the two open-loop link verbs (owes_to/awaiting_reply_from); schema-cli + lens-pack pins updated (15 → 17 link verbs). - The calendar-to-brain recipe test now pins the recipe's NEW shape (native connector: no repo-relative output_paths, command probe instead of a mismatched heartbeat id). - Flag registry regenerated for the new --source flags on waiting/loops. - Plugin tree + llms bundles regenerated for the skill edit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: post-release audit for v0.47.0.0 — late-wave behavior into guides, KEY_FILES, README discoverability Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-model doc-review fixes — precise staleness/close semantics, error-catalog completeness, two CHANGELOG over-sell corrections Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(cli): OPEN LOOPS section in gbrain --help + vault-readiness TODO /document-release flagged that the top-level help listed none of the four new commands (google, waiting, loops, creds); the recipes' vault-blind readiness check is filed as a P2 TODO (code fix in integrations.ts, not a doc fix). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: post-ship audit round 2 — AGENTS.md waiting task, hosted-relay design-doc discoverability Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: cross-model doc-review round 3 — freshness-gate precision, doctor-warning honesty, cold-start native path Six gaps from the independent doc review, all verified against src first: - The "fully-successful sweep" freshness claim overstated the gate: the last_sync_at stamp is gated on the GMAIL sweep (KEY_FILES + guide reworded to the exact predicate; contacts/calendar failures mark partial only). - The doctor google_oauth warning was over-promised: it fires when a Testing-mode account goes 5+ days WITHOUT a successful refresh — an actively-syncing account gets no pre-warning. Guide, skill, CHANGELOG wording, and both recipes (which still said "day ~6") aligned. - cold-start no longer forbids OAuth outright: the native connector is the sanctioned path (tokens in gbrain's vault, never in the agent's context), consistent with the skill's own safety principle; ClawVisor and Takeout remain as alternatives. README cold-start paragraph matches. - gbrain google --help now lists --timeout-ms and setup's --account / --history-days / --sync-budget-ms (the guide pointed at --help for flags it didn't show). - The relay design doc's error-code row dropped its stale count and gained relay_disabled. - --consent-state production documented as a re-consent run (pair with --reauth), not a metadata-only stamp. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: CI gate wave — GCM tag length, bigint-id parity, cross-engine hot-memory cache leak, skills lockfile Four CI failures on PR #4590, each fixed at the root: - semgrep (gcm-no-tag-length): bundle import now pins authTagLength: 16 on createDecipheriv and rejects truncated tags as tampering — without the pin, Node accepts attacker-supplied tags down to 4 bytes, weakening forgery resistance. Regression test added. - Tier 1 engine parity (open_loops round-trip): postgres.js returns BIGSERIAL/BIGINT columns as STRINGS while PGLite returns numbers, so close-by-id equality (`closed.id === first.id`) and `loops show <id>` silently failed on real Postgres only. normalizeRow now coerces id/fact_id/confidence. - test (7) remote-privacy-sweep phase R: the hot-memory meta cache (src/core/facts/meta-hook.ts) keyed on source/tier/session but NOT the engine — one process serving two brains (test shards, hosted multi-tenant, mounts) could serve brain A's cached facts to brain B's caller within the 30s TTL. CI's shard packing put the verbs-conformance suite seconds before the sweep and its fact surfaced in the sweep's _meta while the expected markers vanished. The key now folds a WeakMap-issued engine serial; bumpHotMemoryCache prunes engine-agnostically (safe over-invalidation). Cross-engine isolation pinned; the expired-eviction pin updated to same-engine semantics (pre-existing bug surfaced by this branch's shard reshuffle, v0.45.7-era). - verify (check:skills-manifest): skills/skills.lock.json regenerated after the round-3 skill doc edits (plugin-tree regen alone does not cover it). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: post-merge regen — plugin trees, template repo, skills lockfile, flag registry, llms bundles Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: post-merge regen + v143 renumber artifacts — schema mirrors, plugin trees, skills lockfile, flag registry, llms Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: post-merge regen — plugin trees, template repo, skills lockfile, flag registry, llms bundles Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(google): pluggable access modes + open_loops scope params + honest no-source copy Generic Google access (--access vault|command|env): a stack that already holds Google access — a Google CLI with its own auth store, gcloud, or a credential gateway that mints tokens — can drive the native source and the open-loop engine without gbrain's OAuth flow. CommandAccessProvider runs a local token-printing command (bare token or JSON w/ expiry; cached with a 60s margin; 30s timeout); EnvAccessProvider reads a live token from a named env var. Non-vault modes synthesize the identity entry (scope preflight trusts the configured services; send-as aliases fetched live best-effort). Secrets never enter sources.config (command string / env NAME only; keys unreachable over MCP). Two typed catalog codes: access_command_failed, access_env_missing. The --token-env flag is parsed once and routed by kind (an earlier draft shadowed github's flag; regression-pinned). open_loops gains source_id / all_sources through the canonical grant resolver, tightened for remote callers (loops carry no visibility tiering, so a scalar-scoped caller cannot widen via source_id — summaries derive from private email). An MCP client whose transport is bound to another source can now reach the google source's loops within its grant. gbrain waiting on a brain with no google source in scope now says the engine has nothing to read (naming both connect paths) instead of a false "You are clean"; results carry no_google_sources. 63 new tests (access providers, command/env-mode sweeps end-to-end, scope params incl. scalar-grant denial, CLI flag validation, no-source copy). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: post-merge regen — plugin trees, template repo, skills lockfile, flag registry, llms bundles Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: post-merge regen — schema mirrors (open_loops → v144), plugin trees, skills lockfile, flag registry, llms Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
3464179ce9 |
v0.46.35.0 fix: wave-k maintainer train — 31 red-proven fixes (5 fix-wave-j salvages, 11 verified issues, 15 credited reimplementations) (#4650)
Wave K's maintainer train: 31 red-proven fixes — 5 salvaged from fix-wave-j (#4363), 11 newly verified open issues, and 15 community PRs reimplemented with credit. Every fix carries a regression test proven RED at its base commit and passed an independent fresh-context review (32/32 approved). Retargeted across the megawave, wave-g, backup-coverage, and db-availability trains with zero suite regressions vs a same-sandbox master comparator; verify 54/54; PR CI 28/28 green. Behavior change: `gbrain config get` now redacts secrets by default (--raw opts out) — see skills/migrations/v0.46.35.0.md. Migration v143 (dream_verdicts_ttl). Full-E2E note: PR CI ran Tier 1+2; the nightly full-suite validates this head post-merge (merge authorized by maintainer). Closes #3910, #4041, #3943, #4107, #4108, #4365, #4385, #4366, #4373, #4392, #4394, #4412, #4364, #4375, #4376, #4380. Completes #4363. Co-authored-by: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: DarkNightForge <DarkNightForge@users.noreply.github.com> Co-authored-by: DarkNightForge <eashanbabber@gmail.com> Co-authored-by: Dr Deeb <drdeebtech@users.noreply.github.com> Co-authored-by: Kkkkkuro <180382840+Kkkkkuro@users.noreply.github.com> Co-authored-by: francisco guzman <49572136+Crackde@users.noreply.github.com> Co-authored-by: harshsahrawat-commits <233312378+harshsahrawat-commits@users.noreply.github.com> Co-authored-by: jared-voss <262417861+jared-voss@users.noreply.github.com> Co-authored-by: kyle944 <297432264+kyle944@users.noreply.github.com> Co-authored-by: leihaozhou <leihao_zhou@qingsongchou.com> Co-authored-by: miroslavb <31091373+miroslavb@users.noreply.github.com> Co-authored-by: y2688 <172344182+y2688@users.noreply.github.com> |
||
|
|
534a27a982 |
v0.46.34.0 feat(db): engine detection, Postgres-first installs, and access auto-repair — the db-availability wave (#4596)
* feat(core): pg-access classifier + engine-free repair seams The db-availability foundation: a data-driven classifier (classifyPgAccessError / diagnoseDbConfig) with an append-only 16-reason union, pre-redacted remediation single-homed per reason, and the GBRAIN_DB_ACCESS marker contract; redaction-safe receipts with cooldown-memory retention; gbrain's own docker-postgres seam (loopback-only, named volume, env-carried password); supabase-admin hardening (alphanumeric refs, bounded timeouts, no constructed fallback hosts); the lazy-reconnect degraded engine (healing call throws RECOVERED-retry so no call executes under a stale scope; caller wait capped); lock-aware PGLite inspection; and the hybrid-search both-lexical-arms-dead rethrow so a dead DB can never return an empty success. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(commands): engine status, db-repair, the Postgres-first init ladder, and classified doctor checks gbrain engine status (engine-free detection: engine, URL source, env shadow, mounts, lock-aware --probe with classified failures); gbrain db-repair (diagnose-only default, tiered flag-gated consent, probe-first forged-marker defense, reversible locked undo, docker-start arm matching the container's real port, healthy-path stale-DB-plane report); gbrain init --prefer-postgres (5-rung ladder that refuses over an existing config, content-gates bare DATABASE_URL, consent-gates every mutation of infrastructure gbrain doesn't own, and detects the surviving-volume auth mismatch); config set database_url/database_path routed to the file plane (engine-free, engine-flip warning, thin-client refusal) with engine hard-refused; doctor's connection check classified in every failure shape plus the pglite_scale and db_repair_recurrence checks; sync's checkpoint-dead abort emits the marker. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(serve): degraded-mode serve + the GBRAIN_DB_ACCESS marker loop across CLI and MCP A dead Postgres at serve startup no longer removes gbrain from the harness: serve boots on the degraded engine (gated on the RESOLVED brain's engine; reconnect guarded so a vanished config throws into the classified envelope instead of exiting the server), the degraded source scope honors a validated GBRAIN_SOURCE, tools/list fail-closes publish gates without touching the engine, recovery re-sends tools/list_changed, and the HTTP /health endpoint reports the classified degraded reason. MCP dispatch returns database_error envelopes (verbs keep the frozen v1 codes) with cached url+brain context; the CLI bottom handler, no-config exit, and doctor fallback emit the marker with everything redacted; engine/db-repair dispatch runs before connectEngine; help documents the new surface. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(skills): db-repair + postgres-adopt bundled in both plugin personas skills/db-repair literal-matches the GBRAIN_DB_ACCESS marker (gbrain-scoped triggers only — bare Postgres phrases would misfire on the user's own apps) and walks diagnose -> --yes -> operator-consented rewrites -> verification, with the hardcoded-command safety clause; skills/postgres-adopt owns engine detection and Supabase adoption (wrapping gbrain migrate, never reimplementing it). Both registered in the manifest/resolver/lanes and shipped to both personas; setup + smoke-test skills updated (engine identity line, classified doctor branch, db-repair auto-fix arm with a timeout above the repair's worst case); plugin trees + skills.lock regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: engine preference, the db-availability loop, and the repair surface INSTALL_FOR_AGENTS/BOOTSTRAP guides carry the ladder table (including its refusal + adoption guards) and the marker contract; ENGINES.md promotes local Postgres to a first-class section and documents engine detection + access repair; KEY_FILES entries for the new modules in current-state voice; the four docs that recommended the dead config-set form now recommend the working one; CLAUDE.md gains the reference-map row; TODOS files the follow-ups (marker scoping, mount-targeted repair, sslmode, GBRAIN_AI_ACCESS generalization, #1050 interaction); llms bundle regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.46.31.0 feat(db): engine detection, Postgres-first installs, and access auto-repair — the db-availability wave Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: post-push document-release sweep for v0.46.31.0 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ci): test-isolation quarantine, structural manifest, semgrep annotation, remediation-string resolution Four env-mutating suites from the wave renamed to *.serial.test.ts (the isolation lint's sanctioned quarantine) with structural-suites.tsv regenerated; the new inspectLockHolder read carries the repo's standard path-traversal nosemgrep annotation (operator-configured data dir + module-constant filename, read-only, trusted-local — same shape as this module's pre-baseline join sites); a rung-3 note reworded so the remediation-resolution scanner stops parsing prose as a command. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ci): teach the #4175 worker-health stub the rewritten smoke-test DB contract Master's test stubbed the OLD section-3 shape (human doctor output); the merged script speaks the new one (engine status --json + doctor --json + db-repair fix arm), so the DB section failed under the harness and shifted every expected exit code by one. The stub now answers the new calls (minimal engine-status/doctor JSON, same 97 score); the worker assertions — the test's actual subject — are unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
74932d004e |
v0.46.32.0 docs: post-release audit for the wave-k train (#4565 follow-up) (#4645)
* docs: post-release audit for v0.46.32.0 (#4565) Three gaps between the docs and what shipped in the wave-k train: - docs/guides/live-sync.md: the "What Gets Synced" hidden-path exclusion now documents the --include-hidden <glob> waiver (sync + import) and its bounds (matching paths only; vendored/generated exclusions never waived). - docs/guides/search-modes.md: keywordOrFallback joins the knob prose (on in every mode, config key search.keywordOrFallback, AND→OR keyword-arm relaxation when strict matching finds nothing). Left OUT of the mode table deliberately — it doesn't differentiate modes, and the table's verbatim homes (CLAUDE.md / init picker / INSTALL_FOR_AGENTS) stay in sync. - docs/takes-vs-facts.md: migration v142's dimension-follow behavior — resize clears existing take vectors by design; run `gbrain takes embed` once after upgrading, keyword-only takes retrieval until then. llms-full.txt regenerated (inlines the guides). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: apply cross-model doc-review findings (v0.46.32.0 audit round 2) The independent doc review verified every claim against source and caught: - live-sync.md HIGH: --include-hidden documented for `gbrain import` too, but the import CLI never parses the flag (it is threaded only through sync's full-sync path) — corrected to sync-only, and the two shipped bounds added (single-invocation scope, no --all; does not reach a non-git FS-walk import fallback). - takes-vs-facts.md: `takes search --semantic` reports no matches until re-embed (it has no keyword fallback); only `think` falls back. - search-modes.md: the AND→OR fallback also covers the title arm. - mcp/DEPLOY.md: DCR section now documents native-client registration (custom-scheme/loopback redirect_uris, unknown-scope filtering, HTTP 400 invalid_client_metadata instead of 500). - KEY_FILES.md current-state clauses for three shipped behaviors that had no reference entry: the doctor schema_version/schema_columns pair, the put_page storage_error write-through contract, and the source-scoped analytics reads + validated search source_id param. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(todos): file the import --include-hidden accepted-but-ignored flag gap (doc-review finding) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
8a22ee8bcc |
v0.46.33.0 feat(backup): monthly backup-coverage check — recreate your agent from a git remote, verified across every harness (#4594)
* feat(backup): backup-coverage core — cached verdict, bounded nag gate, fix-path invalidation src/core/backup/status-file.ts (engine-free: verdict cache, notice renderer, nag gate with 24h dampener + per-channel ceiling + global monthly cap) and src/core/backup/coverage.ts (probed compute deduped by git root, positive origin/never-pushed determination, degraded verdicts never persisted, host-brain-scoped cache). Exports aheadCount from workspace-push, types repo_url on InstallReceipt, and invalidates the cached verdict when a fix lands (bootstrap repo receipt write, sources harden, guarded workspace-push). * feat(backup): gbrain backup status|check + CLI rail + backup.* config keys Pre-engine dispatch (lock-safe: a serve-held PGLite lock degrades to the cached verdict), recovery statement in human and --json output, exit 0 ok / 1 warn / 2 usage, startup stderr nag with the BACKUP_LOCAL_ONLY machine marker, and file-plane backup.check_enabled / check_interval_days. * feat(backup): backup_coverage doctor check + backup-coverage advisor collector Local runs probe (the checkSyncFreshness D4 stance); remote surfaces are cache-only readers with aggregate counts, never asset ids. Advisor emits per-repo findings with fix argvs locally, one aggregate finding remotely, gated by the shared nag budget and the kill switch. * feat(backup): harness render channels + automatic compute triggers Claude Code user-prompt banner (push failure outranks) + session-start note + session-end detached spawn; MCP aggregate extra block once per stdio serve process (HTTP attaches nothing, fail-closed on unset transport) with the stdio-gated in-process refresher; OpenClaw context line (read-only against the nag budget, per-process latch); post-sync stale-only recompute. * docs(backup): ops guide with recovery drill, KEY_FILES entries, skill notes, follow-up TODOs docs/operations/backup-check.md (coverage table, five channels, nag budget, state files, privacy rules, fix recipes, quarterly recovery drill), the CLAUDE.md reference-map row (+llms rebuild), monthly-cadence notes in the gbrain-advisor and maintain skills, the HEARTBEAT backup-check job row, four filed follow-up TODOs, and the module-size ratchet bumps. * chore: bump version and changelog (v0.46.31.0) Five-file version lockstep (VERSION, package.json, openclaw + codex + claude plugin manifests), the BOOTSTRAP runbook stamp, the CHANGELOG entry for the monthly backup-coverage check, and the regenerated version-stamped trees (template-repo, plugin, plugin-variants). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: regenerate cli-flag registry (backup scan surface adds --verify) The freshness guard (test/cli-flag-validation.test.ts) requires the committed registry to match a fresh generator run; the backup command's scan surface picks up the rev-parse --verify probe token. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(changelog): restore the v0.46.30.0 entry header clobbered by the v0.46.31.0 bump The version-bump commit consumed master's `## [0.46.30.0] - 2026-08-25` header, leaving that release's body orphaned inside the v0.46.31.0 entry. Restores the header verbatim; no content was lost or rewritten. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(backup): align backup-check docs with shipped behavior (9 review findings) Cross-model doc review of the v0.46.31.0 diff surfaced nine doc-vs-code gaps; all verified against the code before fixing: - name the probe helpers actually used (originRemoteState/hasRemoteTrackingRef, not sync-git's hasOriginRemote, which coverage.ts deliberately rejects) - document the second no_remote warn path (origin configured but never pushed) - ops doc: status/advisor impressions spend the shared nag budget; per-channel ceiling is per month PER VERDICT; CLI-rail skip set includes the upgrade surfaces; --quiet and disabled force exit 0 even on a cached warn - interval semantics: config set rejects <1, invalid env values fall back to the 30-day default (nothing "clamps to 1") - sources push invalidation is conditional on a warn/failing/unpushed cache - test suite count: eight, not seven check-key-files-current-state + build-llms freshness both pass. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(ci): regenerate structural-suites manifest (two new backup source-text-pin suites) check:structural-manifest failed on PR #4594 — the branch's new backup-cli lock-fallback and backup-invalidation receipt-contract suites changed the structural inventory shape. Regenerated with bun scripts/classify-tests.ts; --check passes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
271a707b7f |
fix(sync): mark importErrored on skipped+error rename destinations (#2683) (#4624)
The rename lane's status='skipped' + .error branch (frontmatter slug-authority rejection, invalid YAML, symlink refusal, oversize file) recorded the failure in failedFiles but never set importErrored, so the later succeededPaths/markCompleted(to) gate read !importErrored as true and checkpointed the rename anyway. A resumed sync then treated the still-broken destination as permanently done and never retried it. status='error' and thrown import errors already set importErrored (#2683 residual, PR #4496) — this closes the same gap for the sibling skipped+error branch. |
||
|
|
77bb9d8c21 |
v0.46.32.0 fix: wave-k community train — 54 contributor PRs absorbed, reconciled with the v0.46.29.0 wave-g train (#4567) (#4565)
* fix(enrichment): resolve entity slug aliases before writes (cherry picked from commit 917f56affd93292d9cfe392c8b3c06f17b99725e) Absorbed-from: #4282 Co-authored-by: TheLordArgus <215461619+TheLordArgus@users.noreply.github.com> * fix(entity): prefer canonical exact-title pages (cherry picked from commit e93a2c9703783b4fbf16d65123fe71450252ad94) Absorbed-from: #4341 Co-authored-by: TheLordArgus <215461619+TheLordArgus@users.noreply.github.com> * fix(bench): toRefKeySet dedupes by page identity, bounding recall_at_k to [0,1] (#4303) toRefKeySet was named as a set but implemented as a plain .map() with no deduplication. When chunk-level search results from the same page appeared multiple times, they were double/triple-counted in the recall numerator -- a real 4-question qrels run reported recall_at_k=1.75, violating computeRecallAtK's own documented [0,1] contract. Fix: build an actual Set keyed by the existing canonical makeRef (source_id, slug) identity, matching the convention already used elsewhere in this file (refKey). A page contributes at most once to the recall numerator regardless of how many of its chunks matched, and the same slug in two different sources still counts as two distinct pages. (cherry picked from commit 079dae6fc28fbbbbaeb33b18c0078e2c529154ae) Absorbed-from: #4453 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(init): retry schema setup on transient pooler timeouts Retry the idempotent initSchema pass when schema setup itself hits statement_timeout or a transient connection error, covering cold-start pooler flakes before pending migrations run. Keep the existing per-migration retry envelope authoritative by not wrapping MigrationRetryExhausted again. Related to #1915. (cherry picked from commit 64ada5d6ec33d407d70ec4eb0d1062c8a2f42fae) Absorbed-from: #4402 Co-authored-by: gbrain-contrib <gbrain-contrib@example.com> * fix(source-resolver): parallelize tier-4 registered-source realpath resolution Absorbed-from: #4411 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix: cancel timed-out health queries (cherry picked from commit 36ad7ee61b7d241672e28c7c825c219769f66a57) Absorbed-from: #3666 Co-authored-by: Mike <mahathaway93@gmail.com> * fix(mcp): preserve federated stdio __all__ scope An explicit source_id=__all__ in grantless stdio bypassed the transport-computed federated source set after the v0.46 operations peel, making it narrower than omission. Treat the sentinel as unqualified only when no OAuth allowedSources grant is present. OAuth grants, including an explicit empty grant, remain authoritative so caller input cannot widen read access. Pin the behavior in the scope unit tests and a real stdio MCP round trip. (cherry picked from commit 42d7bca716e0961385b1dc65f59e12f6ca6e366c) Absorbed-from: #3846 Co-authored-by: nullhex-io <lab@nullhex.io> * fix(doctor): detect dangling free-text aliases (cherry picked from commit 0ab55f24beb161cdc5d8c796128aac7bf934dc3c) Absorbed-from: #4336 Co-authored-by: TheLordArgus <215461619+TheLordArgus@users.noreply.github.com> * fix(doctor): bound sampled entity coverage (cherry picked from commit c16357b0597d70eb08b8fd5c8c17ff348c55e7b2) Absorbed-from: #4343 Co-authored-by: TheLordArgus <215461619+TheLordArgus@users.noreply.github.com> * fix(import): honor sources.set-cr-mode on the import path (#3885) importFromContent hardcoded contextual_retrieval_mode: null and trust_frontmatter_overrides: false when resolving the CR mode for a page, instead of reading the source row's stored override. This made `gbrain sources set-cr-mode <id> none` (or title/per_chunk_synopsis) invisible on every write path that funnels through importFromContent: CLI put, capture, and markdown reindex all silently fell back to the global contextual_retrieval_mode config, ignoring the per-source setting a user had explicitly configured. Fix: look up the source row (contextual_retrieval_mode, trust_frontmatter_overrides) before resolving, with an Array.isArray guard so a missing row (mock engines, pre-source callers) falls through to the existing global-config behavior rather than throwing. Does not touch the existing per_chunk_synopsis -> title demotion cost-containment logic (inline import still refuses paid synopsis generation; that stays Minion-backfill-only by design). Test plan: - 4 new live-PGLite + embed-stub cases in test/e2e/contextual-retrieval-pglite.test.ts: importFromContent + source-none beats global title; put_page (capture) + source-none; reindex --markdown + source-none; source per_chunk_synopsis + global conservative correctly demotes to title wrap (proves the override is seen without triggering inline paid synopsis generation). - bun run typecheck: pass - bun run check:module-size: pass - bun run check:structural-manifest: pass - bun test test/e2e/contextual-retrieval-pglite.test.ts test/import-file.test.ts \ test/contextual-retrieval-resolver.test.ts test/sources-set-cr-mode.test.ts: 76 pass, 0 fail, 195 expect() calls (cherry picked from commit d8f278ff58fd1da6e6114317d71374b0d39f544c) Absorbed-from: #4459 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(facts): avoid embedding rejected high-only facts (cherry picked from commit 00814a3d8115a64e9606b47433f5a37250a6d010) Absorbed-from: #4076 Co-authored-by: Codex <codex@local> * test(memory): isolate no-embedding conformance cases (cherry picked from commit 481e081a64c3dedb92dce42fba1e26d2d8dd6488) Absorbed-from: #4313 Co-authored-by: leihaozhou <leihao_zhou@qingsongchou.com> * fix(facts): reconcile a Facts fence below the timeline sentinel loudly, not destructively Absorbed-from: #4406 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(facts): canonicalize entity_slug in extract-conversation-facts (#3729) The extraction prompt (src/core/facts/extract.ts) documents `entity` as a display name the CALLER is responsible for canonicalizing. The sibling caller, src/core/facts/backstop.ts, correctly resolves it via resolveEntitySlug before insert. extract-conversation-facts.ts wrote the LLM's raw entity string straight into facts.entity_slug instead, producing phantom/uncanonicalized slugs (reported 22.5% rate). Mirrors backstop.ts's exact pattern: resolveEntitySlug(engine, sourceId, entity_slug) before insert, null stays null, an already-canonical slug is unchanged. (cherry picked from commit 077e8d2b51114be338d5822920c959f2cd303bd1) Absorbed-from: #4446 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(pages): anchor get_page's shadow tiebreak on sourceIds[0], not 'default' (#3931) get_page(slug, { sourceIds: [...] }) resolves a slug that exists in more than one federated source with `ORDER BY (source_id = 'default') DESC, source_id ASC LIMIT 1` (added in #4219 to fix the original planner-order nondeterminism). That closed the pure nondeterminism, but still silently prefers a hardcoded 'default' source over the caller's own — a federated sourceIds[] array puts the caller's resolved source at position 0 (see localFederatedSourceIds in source-resolver.ts), and #4219's fix ignores that ordering entirely. Anchor the tiebreak on sourceIds[0] instead: the caller's own copy of a shadowed slug wins when it exists, falling back to lexical source_id order when the anchor has no matching row (unchanged fallback behavior). Applied identically to PGLiteEngine.getPage and PostgresEngine.getPage to keep the two engines in lockstep, per the repo's engine-parity invariant. New tests in get-page-federated-scope.test.ts cover: anchor wins even when lexically later, re-anchoring flips the winner, anchor absent from the candidate rows falls back to lexical order, and repeated calls with the same scope are stable. Fixes #3931 (cherry picked from commit f2487649dfe31ed0cf853e2fd083bad43ae54251) Absorbed-from: #4466 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * docs(claude-md): route per-file detail to KEY_FILES.md in the post-ship checklist The Reference-map refactor moved per-file and per-version detail out of CLAUDE.md and into docs/architecture/KEY_FILES.md, behind the on-demand layer. The post-ship checklist was not updated to match: it still instructs /document-release to record "new files, test files, or architecture changes" in CLAUDE.md itself. That is the append-only pressure that grew CLAUDE.md to 67KB before the refactor, and it is still pointed at the always-loaded file, so the growth recurs on every ship. CLAUDE.md is read in full at the start of every session; KEY_FILES.md is not. Route file-level detail to KEY_FILES.md, and state explicitly that CLAUDE.md is a map rather than a log — condensed or deleted as entries go stale, never appended to. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> (cherry picked from commit 4f3b65da3ee17bbaa50cdb30a236401847e1fd6f) Absorbed-from: #4099 Co-authored-by: TOC-macmini <kbyeon@gmail.com> * fix(doctor): fail on forward schema skew (#2036) (cherry picked from commit 78ccb70c6b69d02aca056d6c2a552ba62641074d) Absorbed-from: #4257 Co-authored-by: TheLordArgus <215461619+TheLordArgus@users.noreply.github.com> * fix(doctor): add read-only schema_columns check to catch ledger/live-schema drift schema_version only compares the migrations-ledger counter — it reports "ok" even when a migration's DDL never landed (the ledger row still gets written as applied, e.g. PgBouncer transaction-mode silently swallowing an ALTER TABLE — a failure mode schema-verify.ts already documents and self-heals for at init/migrate time via verifySchema()). Extract that same live-column detection into a new read-only detectMissingColumns(), and wire it into `gbrain doctor` as a new schema_columns check right next to schema_version. A plain diagnostic run should never issue DDL on its own, so this only detects and reports — it does not self-heal (that stays `gbrain init --migrate-only`'s job). Repro (gbrain 0.46.25.0, Postgres): schema_version reported "Version 135 (latest: 135)" while content_chunks.embedded_text_hash was actually missing, breaking `gbrain import` on every file for two nights running before `gbrain init --migrate-only` surfaced and healed it. Issue #4421. Fixes #4421 (cherry picked from commit ffc88a95516e0f9589b6418c7e4c10846a39d81a) Absorbed-from: #4425 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(cycle): thread the cycle's resolved source into synthesize_concepts writes runPhaseSynthesizeConcepts wrote concept pages via importFromContent with no sourceId, and hardcoded source_id: 'default' into its receipt and extract rollup. Every write in that path substitutes the literal 'default' when sourceId is undefined, so on any brain whose content lives in a source not named 'default' (the one-brain-one-source layout in docs/architecture/brains-and-sources.md) every synthesized concept page silently lands under the seeded 'default' source instead of the source the cycle is scoped to - wrong provenance, invisible to source-scoped reads. On v0.45.x deployments the same missing sourceId was fatal rather than silent: the existence probe there was source-agnostic, so an update to an existing concept page found the row in the real source, then createVersion looked it up under 'default' and threw createVersion failed: page "concepts/..." (source=default) not found killing global maintenance and every phase ordered after synthesize_concepts (grade_takes, calibration_profile, drift, skillopt, embed, orphans, purge). Observed in production on a single-source brain. Fix: cycle.ts passes cycleSourceId - already resolved and already threaded into the extract, orphans, and calibration phases - into runPhaseSynthesizeConcepts; the phase threads it into importFromContent, the receipt, and the rollup. The `?? 'default'` fallback survives, so brains whose content actually lives in 'default' are byte-for-byte unchanged. Regression test: concept page + rollup land under the given source, and the re-run (createVersion) path survives on a non-default-source brain. Verified failing pre-fix: the concept page lands under 'default' instead of the given source. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> (cherry picked from commit 42023b2fb0dd2a8180e9cec55582b276501edaa0) Absorbed-from: #4417 Co-authored-by: Robin <rayme@boltdsolutions.com> * fix(sync): rename-sentinel operator exit + orphan self-heal (#3570) Absorbed-from: #3583 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(search): offset cache-skip also covers negative offsets (#4358 residual) hybridSearchCached's cache-skip condition for offset-bearing requests was (opts?.offset ?? 0) > 0 on master — a positive-offset-only form that landed via an unrelated merged wave PR (#4368), which absorbed the positive-offset half of an existing not-yet-merged fix (#4397, for #4358) but dropped the negative-offset half and its accompanying KNOBS_HASH_VERSION bump. A negative offset re-slices an already offset/limit-sliced stored cache page just as badly as a positive one (Array.prototype.slice's negative-index semantics), so `> 0` still let those requests read/write the cache. Widens to `!== 0` and bumps KNOBS_HASH_VERSION 21->22 to invalidate any cache rows written while the gap was live. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EY6s1KwmznCuJnZTRPxmBp (cherry picked from commit 432d43c73f75c310828a777164e7bbf48a85f929) Absorbed-from: #4414 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * docs(sync): remove stale resolveSlugByPathOrSourcePath references in KEY_FILES.md Absorbed-from: #4396 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(smoke): respect native worker supervisors Absorbed-from: #4183 Co-authored-by: Caleb Hicks <calebhicks@gmail.com> * fix(bootstrap): pin harness detection in the E2E, unblocking nightly CI `coverage-full-e2e` has failed every night since 2026-08-17 (runs 32453421876, 32338537649, 32222333677, 32105820276) with a byte-identical failure set. `bootstrap-harness-lifecycle.serial.test.ts` fails at lines 175 and 220; `qm-provisioning` and `serve-stdio-roundtrip` co-occur on all four nights. Root cause: the E2E injects only `runner` into `runBootstrap`, so harness detection falls through to `resolveDeps`' production default, `Bun.which('claude')`. `Bun.which` resolves against the live PATH and reads the real password-database HOME, so it ignores the test's remapped HOME/PATH entirely. The suite therefore asserts something different depending on which agent CLIs the host happens to have installed: - developer laptop: `claude` on PATH -> claude lane runs -> green - GitHub runner: `claude` absent -> claude lane skipped, no `claude mcp add` exec'd, no user-scope settings file written -> red Not a flake and not xdist: reproduced byte-for-byte on this machine by running the file with a claude-free PATH. Fix: add a `harnessDetect` seam to `RunBootstrapOpts`, mirroring the existing `probeSpawn` seam, and pin all three probes in the E2E. The helper type and narrowing live in `core/bootstrap/harness.ts` so the size-ratcheted `commands/bootstrap.ts` absorbs only the wiring; its ceiling moves 1923 -> 1928 in this same commit, per the check's own instruction. Production behaviour is unchanged: `harnessDetectDeps` omits any probe that was not explicitly supplied, so `resolveDeps` keeps its `Bun.which` defaults when the option is absent. The gate is strengthened, not weakened. Nothing is skipped, suppressed or loosened — the assertions are untouched, and CI can now exercise the claude lane it previously could not reach at all. Verified by mutation: disabling the claude lane (`wireClaude = false && ...`) makes the test fail 2/5, so it still kills a real regression. Verification: - claude-free PATH, before: 2 fail (lines 175, 220) — matches CI exactly - claude-free PATH, after: 5 pass, 3/3 runs - claude on PATH, after: 5 pass - qm-provisioning: 11 pass; serve-stdio-roundtrip: 8 pass - `bun run verify`: 52 pass (module-size green; check:privacy and check:test-isolation only exceed the 120s harness cap, and both exit 0 on pristine master and on this branch when run with a real timeout) (cherry picked from commit 1ceb36509abf1f8413b6cb1002670cc10f543928) Absorbed-from: #4408 Co-authored-by: auroracapital <info@auroracapital.nl> * fix(recipes): drop retired gemini-2.0 models (cherry picked from commit a10be75fc8ea8248dc66059953c1e486f415d6ba) Absorbed-from: #3760 Co-authored-by: Alexey <alexey@metaengage.ai> * fix(context-engine): reflex ignores turn delivered via `prompt` (empty `messages`) Absorbed-from: #4035 Co-authored-by: Orcun Simsek <orcun@joyolabs.com> * fix(gateway): two Anthropic-compatible-provider defects that fail silently Absorbed-from: #4071 Co-authored-by: Anton Rusakov <rusa4ok@gmail.com> * fix(cli): route `takes --help` to its own usage block instead of the generic stub `gbrain takes --help` printed the one-line CLI_ONLY stub: Usage: gbrain takes gbrain takes - run gbrain --help for the full command list. `takes` was in CLI_ONLY but missing from CLI_ONLY_SELF_HELP, so the generic short-circuit in main() fired before runTakes could print its own help. The detailed usage block in src/commands/takes.ts — every subcommand, its flags, and the --dir default — was unreachable from the CLI, so add/update/supersede/resolve/scorecard/calibration/search were undiscoverable without reading the source. Same holdout pattern already fixed for `capture` (v0.39.3.0 WARN-5), `sync` (v0.37 CDX2-12), and `schema` (v0.40.6.0), and the fix is the same two parts both of those needed: 1. add 'takes' to CLI_ONLY_SELF_HELP so the generic stub stays out of the way; 2. add a pre-engine-bind `--help` branch in handleCliOnly, because the dispatch case still binds an engine — without it `takes --help` on a fresh tmpdir fails with "No brain configured. Run: gbrain init" instead of printing help. runTakes' help path returns before it touches the engine, so it takes null like runEnrich/runSync do. Verified: all three new tests fail on the parent commit and pass here. `bun run verify` green (34/34). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> (cherry picked from commit a66f57f8afde6283603693506086767a777257a7) Absorbed-from: #3780 Co-authored-by: Constantin Gozman <constantingozman@gmail.com> * fix(features): treat heartbeat-backed integrations as configured The 'Set Up Integrations' recommendation previously flagged a recipe as unconfigured whenever its secret env vars were not exported in the current shell. Integrations installed through Hermes (and other hosts) store a setup_complete heartbeat at ~/.gbrain/integrations/<id>/heartbeat.jsonl rather than in shell env vars, so they were falsely reported as missing. Now a recipe is considered configured if EITHER its secrets are present in the environment OR a real setup_complete heartbeat exists on disk. Verified locally: previously reported 7 unconfigured, now correctly reports only the 3 with no heartbeat file. (cherry picked from commit 2490a19777a69c43660812ed2529e9033b261816) Absorbed-from: #3900 Co-authored-by: Mitch Ryan <mitch.paul.ryan@gmail.com> * fix(cli): reach real usage block for gbrain auth --help Absorbed-from: #4083 Co-authored-by: Abhirama Sonny <abhirama.sonny@gmail.com> * fix(oauth): stop DCR returning HTTP 500 for native MCP clients Warp (rmcp) and other OIDC-flavored MCP clients failed Dynamic Client Registration because gbrain threw plain Errors that the MCP SDK mapped to opaque 500 server_error. Filter unknown scopes, allow custom-scheme redirect_uris, and surface validation failures as invalid_client_metadata. Co-Authored-By: Oz <oz-agent@warp.dev> (cherry picked from commit b454c8f84ec4b10fc1d522832203142a39f34887) Absorbed-from: #3819 Co-authored-by: ShintaroKawakami <shintaro@example.com> * fix(put_page): fail the operation when write-through cannot produce the file put_page reported success even when the disk write-through failed, leaving a page reachable only from the DB index with no markdown file anywhere in the configured repo. Reject the call instead, except for the one deliberate DB-only configuration (no sync.repo_path set at all). When the failed write-through was for a page this same call just created, delete the row instead of leaving an index-only orphan. (cherry picked from commit ed6630db05865818646f2d3af399448e725b1612) Absorbed-from: #3935 Co-authored-by: Dov Stern <dovstern@users.noreply.github.com> * v0.46.6.1 fix(jobs): make job-control dry runs non-destructive Absorbed-from: #4179 Co-authored-by: Caleb Hicks <calebhicks@gmail.com> * fix(doctor): recognize generated concepts as DB-only Absorbed-from: #4188 Co-authored-by: Caleb Hicks <calebhicks@gmail.com> * fix(doctor): report summary-only conversation pages separately from parser misses (#4193) conversation_format_coverage treated every page in the conversation type allowlist as a transcript-parsing candidate, so meeting/slack summary pages (headings + bullets, no transcript) counted as parser misses and could push a healthy brain over the 10% warn threshold. - New src/core/conversation-parser/transcript-signals.ts: isTranscriptClaiming(page, body) — true on raw_transcript frontmatter, a transcript section heading, or timestamp-dense lines (>=3 and >=10% of non-blank). Conservative: never treats 'Name: text' labels as a signal; a false positive only keeps today's behavior. - conversation_format_coverage peeled verbatim from doctor.ts to src/commands/doctor/checks/conversation-coverage.ts (unit-testable, computeExtractAtomsBacklogCheck pattern; doctor.ts re-exports). A no_match page that never claimed a transcript reports as _summary_only in the breakdown and leaves the coverage denominator. - doctor.ts ceiling lowered 4270 -> 4220 (peel shrank it 57 lines). - Drift guard updated: doctor.ts no longer imports ALLOWED_TYPES; the peeled check is guarded in its new home. (cherry picked from commit b903910659a659002fb41c1e40c39494281e0f9a) Absorbed-from: #4262 Co-authored-by: harjoth <harjoth.khara@gmail.com> * patch 85: wedged_queue liveness-aware message (local-only, no upstream PR) issue #3063 (closed 2026-08-20 as "valid but not on the near-term roadmap"): computeWedgedQueueCheck always says "worker alive but not claiming work" even when no worker was ever subscribed to the wedged queue, misdirecting the operator toward restarting a worker that doesn't exist instead of starting one. Fix: thread the existing local worker-registry liveness signal (readWorkers(), already used by computeQueueHealthCheck and `jobs stats`) into computeWedgedQueueCheck, split wedged queues into "stuck" (worker registered for that queue but not draining it) vs "no worker subscribed", and message each with the correct repair. Reproduced locally: our default queue was wedged for the exact reason #3063 describes (cron-queue-only supervisor running, nothing subscribed to default) while doctor reported "worker alive". Positive control: two new test cases in test/doctor-wedged-queue.test.ts assert the message differs by readWorkers() liveness (fires on no-worker, does not fire when a worker IS registered for that queue). 28/28 tests pass, typecheck clean. (cherry picked from commit cb8802063e6aa515d1c59d008e3fe8b3b442550c) Absorbed-from: #4400 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(search): honor resolved mode searchLimit on text-path miss + cache-hit Absorbed-from: #4360 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(mcp,search): honor per-call source_id on federated read ops Absorbed-from: #4000 Co-authored-by: pavel.ponomaryov <pavel@topia.com> * fix(eval): score unique pages across retrieval metrics Absorbed-from: #4184 Co-authored-by: Caleb Hicks <calebhicks@gmail.com> * feat(search): make the keyword-arm AND→OR fallback a mode knob (search.keywordOrFallback) The hybrid keyword arm's zero-recall AND→OR retry (fix/title-retrieval-arm, D2) was hardcoded on. That is the right default for stemmed languages, but on corpora the FTS config cannot stem — CJK/agglutinative text under the 'english' config — strict AND collapses on almost every natural-language query (particles make tokens non-co-occurring), so the OR retry fires constantly and can match a quarter of the corpus; ts_rank has no IDF, so nothing demotes the common-token hits and the relaxed rows blend into RRF as noise. Measured on a 22K-chunk Korean-heavy corpus: a conversational query matched 0 chunks strict vs 5,577 relaxed (25% of the corpus), with a stopword-only document outranking the true answer by 36%. This exposes the existing engine flag as a mode knob: - ModeBundle.keywordOrFallback — default true in every bundle (previous hardcoded behavior; no change unless an operator opts out). - Per-key config override: search.keywordOrFallback (same parse/precedence as search.intentWeighting), registered in SEARCH_MODE_CONFIG_KEYS and the gbrain search modes dashboard. - hybrid.ts threads the resolved knob into the keyword arm's engine opts. - Cache safety: kof= joins knobsHash (append-only) and KNOBS_HASH_VERSION bumps 14→15 — a fallback-on row must never serve a fallback-off lookup. Tests: knob resolution/parsing/hash participation (search-mode), and an end-to-end pair through hybridSearch on PGLite (title arm deliberately starved so the OR retry is the only rescue path): bundle default rescues, config=false suppresses. Version pins updated. (cherry picked from commit 22d204852f2e57c8bb49080813840beb514db9aa) Absorbed-from: #3617 Co-authored-by: YMYD <paul@ymyd.co.kr> * feat(entities): resolve conversation facts through shipped alias_exact Bulk extract writes skip writeSingleFact, so they never hit the v0.46.15 resolver. Call resolveEntitySlugWithSource before insertFacts instead of re-implementing an alias_match/alias_redirect cascade. (cherry picked from commit ebe52b19795323f8b9c69135eddf4d5bab31192e) Absorbed-from: #4052 Co-authored-by: Sean Gearin <sean@indistinct.ai> * fix(facts): install a record-only budget tracker at the pipeline choke point so extract_facts spend reaches the audit (#4210) Every runFactsPipeline entry point outside a cycle scope — the extract_facts op, sweep pass 3, the put_page backstop, checkpoint harvest, file/code import — called gateway.chat with no ambient BudgetTracker, so the Haiku extraction spend was a budget no-op: real money spent, zero rows in budget-*.jsonl. runPipelineWithBody now installs a fallback BudgetTracker labeled facts:<ctx.source> when no ambient tracker exists. Uncapped, so it can never throw BudgetExhausted; an ambient tracker (cycle phases, transcripts ingest) wins and keeps its own label — no double scope. Pinned by test/facts-pipeline-budget-accounting.test.ts: op-path and hook:compact spend land in the audit with per-entry-point labels, response envelope unchanged, ambient scope recorded exactly once. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> (cherry picked from commit 459af01bbaa61ce6accc5c22a61596899f011393) Absorbed-from: #4260 Co-authored-by: harjoth <harjoth.khara@gmail.com> * fix(facts): record typed provider failures in the absorb pipeline Absorbed-from: #4308 Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> * fix(security): fail-closed facts visibility — omitted remote flag reads world-only findTrajectory's visibility filter keyed on opts.remote === true, so a context that lost its remote flag (widening cast, caller that forgot to thread it) read private fact rows. The repo's own trust posture (CV6 / v0.26.9 F7b, as stated at put_page's remote coercion) is the opposite: anything not strictly local is remote. Flip both engines' remoteFilter to opts.remote !== false and the two ops-layer coercions (think + find_trajectory handlers) to ctx.remote !== false. Every trusted local caller now passes remote: false explicitly: CLI think, the auto-think dream cycle, founder-scorecard, and eval-trajectory (eval-longmemeval already did). The facts meta-hook was already fail-closed and is untouched. Owner-visible behavior is unchanged; only the ambiguous-context default moves from private-leak to world-only. Test pins updated: the old undefined-is-trusted pin is replaced with undefined-is-world-only, and trajectory/think test callers gain explicit remote: false so each test keeps its original intent. (cherry picked from commit 2276152ef122c4559a6005796173728bb06ae987) Absorbed-from: #3855 Co-authored-by: jeanpierre121 <jeanpierre121@hotmail.com> * fix(consolidate): fetch pending facts before limit (#4057) (cherry picked from commit c0cb0f649296defa5a6de87e481a605c1c940d68) Absorbed-from: #4070 Co-authored-by: arisgysel-design <arisgysel-design@users.noreply.github.com> * fix(dream): resolve context limits from recipes (cherry picked from commit 237314bf716acad92f3e378b561aa190a88bfbaa) Absorbed-from: #4080 Co-authored-by: Kuro Chen <kurochen@MacBookPro.lan> * fix(import): thread the resolved sourceId into recordFailures + logIngest Both of runImport's own bookkeeping writes used the wrong value whenever the resolver routed a bare (no --source-id) call away from 'default': - recordFailures(opts.sourceId ?? 'default', ...) used the unresolved CLI/opts parameter, which stays undefined unless the caller passed --source-id explicitly — not the `sourceId` local variable every importFile/importImageFile call in the same run actually used. Every ledger row landed with source_id: 'default' regardless of where the pages really went. - engine.logIngest(...) never passed source_id at all (the field exists on IngestLogInput, just wasn't populated here), so it always fell back to the schema default 'default'. Both call sites now use the resolved `sourceId ?? 'default'` local variable instead. New test (PGLite, hermetic): registers a sole non-default source with a local_path so resolveSourceWithTier's tier 5.5 fires on a bare `gbrain import <dir>` call, causes one file to fail (oversized-content soft skip), and asserts both the sync-failures ledger row and the ingest_log row report the real source, not 'default'. Confirmed the test fails against the pre-fix code (git stash) before confirming it passes fixed. Fixes #3838. (cherry picked from commit 4b613aa68d421a2263a9412c8e9a33d8d0b7f1fd) Absorbed-from: #3842 Co-authored-by: Bo <bo.developing@gmail.com> * feat(sync): --include-hidden waives the dot-prefix prune for named globs pruneDir's leading-dot heuristic (.git, .obsidian, and any other dot-prefixed directory) was unconditional and unreachable by any CLI flag, --include/--exclude glob, or per-source config — a ledger convention that stores schema'd entries under a dot-prefixed directory (e.g. kazi-org/dira's .dira/entries/) was silently unsyncable and unimportable on every git-tracked source, with no workaround. classifySync (sync's incremental + full-sync dry-run/reconcile paths) and isCollectibleForWalker (import's git-ls-files fast path, the one every git-tracked source actually uses) independently reimplemented the same segment-level prune check — exactly the shape of bug that let node_modules drift out of sync before PRUNE_DIR_NAMES existed (#923, core/sync.ts, so a future change to the exclusion set can't fix one call site and silently leave the other pruning differently. --include-hidden <glob> is repeatable, matches the same glob dialect as --exclude, and only waives the leading-dot part of the exclusion set — PRUNE_DIR_NAMES (node_modules/vendor/dist/build/venv) and *.raw stay unconditional, by design. Threaded through every collection call site that needed it, including the full-sync reconcile-deletes pass (missing it there would have looked like the included pages vanished on the very next sync and triggered the mass-delete valve). Known scope gap, documented in isPathPruned's doc comment: this does not reach pruneDir's live-filesystem-walk callers (import's fallback walker for non-git directories, storage.ts's walkBrainRepo) — those decide per-directory during real recursive descent and would need prefix-of-a-glob reasoning to honor the same waiver safely. Every git-tracked source goes through the fast path this change covers, so the gap is scoped to importing a bare, non-git directory. Cannot be combined with `sync --all` (same restriction as --exclude and --src-subpath — these scope a single invocation). (cherry picked from commit 469f83373de52d36427d9d8e4292f3b9b03d1578) Absorbed-from: #4027 Co-authored-by: David Ndungu <ndungu.sink@gmail.com> * fix(think): activate semantic takes retrieval Absorbed-from: #3776 Co-authored-by: Hunter Veltri <veltrifinancial@gmail.com> * fix(engine): NUL-sanitize pages body columns + chunk_text (both engines) putPage bound title/compiled_truth/timeline raw, and upsertChunks bound chunk_text raw, in both postgres-engine and pglite-engine. A raw 0x00 byte in a page body aborts the INSERT with `invalid byte sequence for encoding "UTF8": 0x00` (Postgres text / PGLite cannot store NUL), silently failing the whole page ingest — one bad byte drops the entire document. #2011 added NUL + lone-surrogate sanitization (sanitizeForJsonb) for the free-text of links, timeline entries, and takes, but missed the pages table's own body columns (title, compiled_truth, timeline) and content_chunks.chunk_text. This extends the same free-prose-body policy to those fields via a new null-safe `sanitizeText` helper. Verified end-to-end: the current build rejects a NUL-containing document with the exact error above; the patched build ingests it (NUL stripped) and it persists. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> (cherry picked from commit 0ce1ebbc8ab0d05c5a687577e2a30b980851bafc) Absorbed-from: #3998 Co-authored-by: Forge <forge@pequeno.ai> * fix(pglite-lock): reap locks whose PID was recycled by a non-gbrain program Absorbed-from: #4331 Co-authored-by: Roi Holgarsson <roi@zakk.fo> * fix: source-scope get_recent_salience and find_anomalies (cherry picked from commit ccb697bfd4a6df95470109225443070cebd63158) Absorbed-from: #3867 Co-authored-by: Alexey <alexey@metaengage.ai> * fix(config): read the config table once instead of once per key `gbrain stats` against a Supabase-hosted brain took 7.7s. pg_stat_statements showed 54 queries totalling 2.3ms of server time, 44 of them `SELECT value FROM config WHERE key = $1`. The database did no work. The CLI paid one network round trip per config key, one after another, before running the command. Two startup paths do this. `loadConfigWithEngine()` reads two dozen keys to merge the DB plane over file/env. `reconfigureGatewayWithEngine()` resolves six models (expansion, chat, and four tiers), each walking a precedence chain that reads up to four keys plus alias expansion — about 40 sequential reads, and 3.1s of that 7.7s on its own. The pattern survived because it is invisible on PGLite, where each read costs microseconds. It only shows up once the brain is a network hop away. The config table is a handful of rows, so read it once and answer every key from memory. `engine.getAllConfig()` lands on both engines; `config-snapshot.ts` wraps it as either a raw map or a `ConfigReader`. `resolveModel`/`resolveAlias` now take a `ConfigReader` rather than a `BrainEngine` — `getConfig` is the only method they ever called. Behavior is unchanged: same keys, same precedence, same per-key quiet failure. The snapshot lives for one resolution pass, not for the process, so a `gbrain config set` from another process is still picked up by the next command. When the bulk read is unavailable — a brain mid-migration with no config table, or an engine implemented outside this repo — every read falls back to the old per-key path. Measured on a Supabase brain (transaction pooler, us-east): gbrain stats 7.7s -> 1.9s Tests pin the round-trip count rather than the wall clock; a timing assertion would be flaky in CI, while a call counter is deterministic. Both fallback paths are covered. (cherry picked from commit 6d2a34a80a654263360b3c02cb0c55a3165dc920) Absorbed-from: #3980 Co-authored-by: Jordan Baker <jbb@scryent.com> * fix(eval): normalize cross-modal dimension names Trim and lowercase judge dimension keys before rolling scores across models so casing differences cannot create separate one-model dimensions. (cherry picked from commit bfffc854ec767bef689a2a007dc8bb96d341c097) Absorbed-from: #3491 Co-authored-by: leihaozhou <leihao_zhou@qingsongchou.com> * chore(ratchet): wave-k TSV true-up — 3 raises for cross-commit absorb growth (gateway.ts, cycle.ts, integrations.ts), reasons inline * chore(gen): regenerate plugin trees after wave-k skill absorbs * test(doctor): await-import the doctor graph instead of sync require — Bun 1.3.10 warm transpiler cache parses `with { type: 'file' }` template assets as code on the sync-require path, cascading 59 'module not instantiated' failures on every warm re-run (reproduces on unmodified master; test-file-only fix, 103/103 cold and warm) * chore(docs): regenerate llms bundles after wave-k absorbs 49804ef5 (Absorbed-from: #4183) and 9132b606 updated skill/doc sources that feed scripts/build-llms.ts without regenerating llms-full.txt. Output of `bun run build:llms`, no hand edits. * test(sync): GATE13 corrupts via invalid YAML, not a NUL — #3998's write-time NUL sanitize (absorbed in this wave) makes a NUL payload ingest cleanly, so the forced-re-chunk failure vehicle must be a failure class sanitization cannot repair * v0.46.29.0 release: version lockstep bump + CHANGELOG + regenerated trees (template-repo, plugin, llms, lockfile) * chore(semgrep): suppress 5 path-traversal FPs in pglite-lock reap paths — getLockDir(dataDir)-derived dirs joined with the LOCK_FILE constant, no user input (repo precedent: autopilot.ts:551) * test(auto-link): give the #2544 probe's source-b a real temp dir — #3935 (absorbed this wave, fixes #3929) makes put_page throw storage_error on failed write-through, so the probe's fake local_path failed the put before scoped resolution ran * chore(gen): refresh structural-suites.tsv after merge (new sync include-hidden structural pin) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pglite-lock): basename-match the recorded command so a live bun-run holder is never classified as a recycled PID The #4331 reap classifier compares the lock's recorded first token (Bun normalizes argv[1] to an ABSOLUTE script path) against ps/procfs cmdline, which reports the spawn-time RELATIVE form (bun run src/cli.ts serve). When the checkout path carries no 'gbrain' substring the literal includes() veto never fires, a LIVE serve is classified as recycled, and the acquiring process steals its lock — observed as bootstrap-harness mint writing a token to a second PGLite instance the live serve never sees (invalid_token on the smoke test). Veto on the token's basename too; regression pinned red/green in test/pglite-lock.test.ts. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(sync-reconcile-postgres): reset sources.local_path per test so the registered-directory guard doesn't pin case 2 to case 1's repo Latent since authoring (the file skips without DATABASE_URL): each case mkRepo()s a fresh dir but beforeEach only reset last_commit/last_sync_at, so the v0.46.25.0 registered-directory guard refused to advance last_commit for the second case's repo and its quiet run reported first_sync instead of up_to_date. First real-Postgres run surfaced it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: TheLordArgus <215461619+TheLordArgus@users.noreply.github.com> Co-authored-by: masashiono0611 <masashi.ono.0611@gmail.com> Co-authored-by: gbrain-contrib <gbrain-contrib@example.com> Co-authored-by: Mike <mahathaway93@gmail.com> Co-authored-by: nullhex-io <lab@nullhex.io> Co-authored-by: Codex <codex@local> Co-authored-by: leihaozhou <leihao_zhou@qingsongchou.com> Co-authored-by: TOC-macmini <kbyeon@gmail.com> Co-authored-by: Robin <rayme@boltdsolutions.com> Co-authored-by: Caleb Hicks <calebhicks@gmail.com> Co-authored-by: auroracapital <info@auroracapital.nl> Co-authored-by: Alexey <alexey@metaengage.ai> Co-authored-by: Orcun Simsek <orcun@joyolabs.com> Co-authored-by: Anton Rusakov <rusa4ok@gmail.com> Co-authored-by: Constantin Gozman <constantingozman@gmail.com> Co-authored-by: Mitch Ryan <mitch.paul.ryan@gmail.com> Co-authored-by: Abhirama Sonny <abhirama.sonny@gmail.com> Co-authored-by: ShintaroKawakami <shintaro@example.com> Co-authored-by: Oz <oz-agent@warp.dev> Co-authored-by: Dov Stern <dovstern@users.noreply.github.com> Co-authored-by: harjoth <harjoth.khara@gmail.com> Co-authored-by: pavel.ponomaryov <pavel@topia.com> Co-authored-by: YMYD <paul@ymyd.co.kr> Co-authored-by: Sean Gearin <sean@indistinct.ai> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: jeanpierre121 <jeanpierre121@hotmail.com> Co-authored-by: arisgysel-design <arisgysel-design@users.noreply.github.com> Co-authored-by: Kuro Chen <kurochen@MacBookPro.lan> Co-authored-by: Bo <bo.developing@gmail.com> Co-authored-by: David Ndungu <ndungu.sink@gmail.com> Co-authored-by: Hunter Veltri <veltrifinancial@gmail.com> Co-authored-by: Forge <forge@pequeno.ai> Co-authored-by: Roi Holgarsson <roi@zakk.fo> Co-authored-by: Jordan Baker <jbb@scryent.com> |
||
|
|
80a899031d |
v0.46.31.0 feat(connectors): live ChatGPT/Claude chat-history sync into the brain (#4584)
* feat(connectors): live ChatGPT/Claude history sync into the brain Provider-pluggable chat connectors that fetch a user's own conversation history via their session credential and ingest it through the existing runTranscriptsIngest pipeline (redaction, slugging, splitting, idempotency reused). New src/core/connectors/ module: ChatHistoryProvider seam + registry (chatgpt/claude), GitHubClient-style HTTP client with off-origin guard + refresh-on-401, pure classify.ts (Cloudflare-403 vs auth-403), file-plane credential store (0600), dependency-free OAuth PKCE loopback, batched spool, and the runConnectorSync orchestrator with a config-scalar watermark (not op_checkpoint, whose 7-day GC would wipe it) and an engine-branched embed kickoff (runEmbedCore inline on PGLite, never submitEmbedBackfill). Surfaces: connectors_status/connector_sync ops (localOnly), the gbrain connectors CLI family, the connector-sync minion handler + opt-in autopilot staleness dispatch, and a doctor health check. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(connectors): unit + e2e suites against a Bun.serve fixture backend 76 tests: pure classify/config-keys/credentials/pkce/providers units, an embed-kickoff engine-branch unit, and PGLite e2e suites that run the real ConnectorClient against a scriptable Bun.serve fixture (keyless-in-CI: retrieval via getPage + searchKeyword). Covers full pipeline, incremental watermark incl. the >30-day-gap-survival regression, idempotency/in-place updates, adapter edge cases, redaction, real HTTP behavior (401-refresh, 403-fingerprint vs 403-auth, drift), dry-run/limit, receipt, spool 0600/ prune, handler lock/terminal-status, and the doctor conditions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(connectors): chat-connectors skill + guide + reference updates New chat-connectors skill (live account lane; dedup boundaries vs conversation-archive) with manifest/RESOLVER/lock/plugin registration. Guide at docs/guides/chat-connectors.md; KEY_FILES + CLAUDE.md reference-map row; README section; 7 deferred follow-ups filed in TODOS.md; llms bundle regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.46.31.0 feat(connectors): live ChatGPT/Claude chat-history sync Version bump + CHANGELOG for the chat-connectors feature. Regenerates the plugin trees + template repo (chat-connectors skill + conversation-archive dedup edit propagate into the codex/claude plugin trees). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(connectors): post-ship doc-release pass /document-release audit: add a "bring in your chat history" task to AGENTS.md's operating protocol (discoverability for non-Claude harnesses), and disambiguate inbound MCP "Connectors" from outbound `gbrain connectors` in the README (the word is overloaded on the same page). Regenerate llms. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(connectors): resolve CI failures (verify + test lanes) - test-isolation: connectors-credentials.test.ts mutates process.env (GBRAIN_HOME + env cookies) → rename to *.serial.test.ts (the test is process-global-state-bound, so serial is also more correct). - skill-brain-first: add the brain-first convention callout to the chat-connectors skill (a writing skill needs the lookup-before-write discipline). Regenerate skills.lock + the plugin tree. - exit-verdict ownership: route the 9 raw `process.exitCode = 1` writes in the connectors command family through setCliExitVerdict(). - doctor-categories drift: categorize the new `connectors` doctor check under OPS_CHECK_NAMES. - remediation text (#3697): teach the flag-registry generator that connectors/ is a peeled command dir (facadeExpansion) so the safety flag `--dry-run`, consumed in sync.ts, carries consumption evidence into depth-zero and registers; split the first-run `config set` / `autopilot --install` hint onto separate lines so `--install` isn't misattributed to `config`. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: add "Say to your agent" end-user phrasebook convention New CLAUDE.md IRON RULE: every public feature doc carries a common "**Say to your agent:**" block — the natural-language phrases an END USER types into their harness, not just the operator CLI. Phrases must come from (or contain) the backing skill's frontmatter triggers so the doc and the router never drift; CLI-only features name the command honestly. Applied throughout README (query, capture, transcripts, connectors, schema, graph, contradictions, search, minions, FTS, eval, integrations, the loop, troubleshooting) + the skills phrasebook pointer to RESOLVER.md, the v0.46.31.0 CHANGELOG "To take advantage" block, and the chat-connectors guide. Phrases verified against real skill triggers (adversarial two-lens review). Regenerate llms. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
872c3d6ae4 |
v0.46.30.0 fix(privacy): registry-driven remote privacy sweep + world-only filters for list-style read ops (#4572)
* fix(privacy): world-only post-filters for list-style read ops find_orphans, get_recent_salience, find_anomalies, and find_experts now route remote responses through a shared keep-list visibility filter (dropPrivateOnlyRows / findWorldVisibleSlugs in private-visibility.ts): fail-closed on soft-deleted pages and mid-read purges, aggregate counts and derived statistics adjusted and re-sorted so nothing about the filtered rows is reconstructible. Local trusted callers unchanged. Pinned by new curated probes in the trust-boundary suite (local positive controls, count-coherence assertions, soft-delete arm). * test(privacy): registry-driven remote privacy sweep (dispatch-surface guard) Seeds a two-source private corpus and dispatches EVERY non-localOnly op through dispatchToolCall in both caller shapes (scalar + federated), asserting the full response envelope — including _meta — carries no private sentinel. Fail-closed maintenance contract: new ops break the suite until classified; localOnly ops must deny over non-stdio transports; publish-gated ops must deny naming their gate. Includes discrimination anchors for both previously-fixed leak shapes and cross-source positive/isolation controls. * chore: bump version and changelog (v0.46.30.0) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: post-ship sync for v0.46.30.0 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
9dadfb9730 |
docs: post-release audit for v0.46.29.0 (#4567)
KEY_FILES.md: entries for the wave's new modules (facts-fence restoreHiddenFactRows merge, wsl-paths, chunkers/def-types, minions/detached-stderr, embedding-input-limit, postgres-engine/forward-reference-bootstrap peel, ai/providers/ claude-cli-scratch, mcp/resolve-ipc-binding) and current-state refreshes (orphans islanded default + find_orphans mode contract, skill-trigger-index symlink follow, doctor upgrade_errors + schema-column diff, mode.ts kof=/sal=/rec=/ipat= knob parts + cache-hit limit, resolve-IPC engine-uniform wiring). search-modes.md: cache hits honor the resolved limit. TODOS.md: megawave follow-ups #4477/#4478/#4479/#4480 shipped in v0.46.29.0 — marked done. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
492b552823 |
v0.46.29.0 fix: the community wave — 38 contributor PRs + 49 verified fixes + the fence-merge data-loss closure (#4567)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
e5dc5a3d6a |
fix(files): give the transcribable audio formats a MIME_TYPES entry (#4536)
`getMimeType` backs `files upload-raw`'s size routing:
const isMedia = mimeType?.startsWith('video/') || mimeType?.startsWith('audio/') || mimeType?.startsWith('image/');
const needsCloud = stat.size >= SIZE_THRESHOLD || isMedia;
MIME_TYPES carries `.mp3`, `.mp4`, `.m4a` and `.wav`, but not `.ogg`,
`.flac`, `.webm`, `.mpga` or `.mpeg` — five of the nine extensions
`transcription.ts` declares supported (AUDIO_EXTENSIONS) and that
`inbox-folder.ts` already classifies as `audio/*` / `video/*`. For those
five `getMimeType` returns null, `isMedia` is falsy, and a voice memo
under 100 MB takes the "stays in git" branch: `copyFileSync` into the
brain repo's `<page>/.raw/` sidecar with `metadata.storage = 'git'`,
instead of the cloud upload every other media file is routed to.
`files upload` records the same files with `mime_type` NULL and calls
`storage.upload` with no content type.
Add the five extensions with their registered types: `audio/ogg`
(RFC 5334), `audio/flac` (RFC 9639), `audio/mpeg` for `.mpga`,
`video/webm`, `video/mpeg`.
test/files.test.ts kept a private copy of MIME_TYPES and getMimeType,
with a comment inviting the switch once they are exported ("If they ever
get exported, switch to direct imports"). Its twelve getMimeType tests
therefore exercised the duplicate and stayed green whatever src did —
they could not have caught this gap. Export getMimeType and import it,
the same seam `formatFileSizeKb` already uses, and add a drift guard
that fails if any extension in AUDIO_EXTENSIONS stops resolving to an
`audio/`- or `video/`-prefixed type.
|
||
|
|
2c2bfec797 |
docs(changelog): credit the two v0.46.25.0 fixes landed from #4265 and #4269 (#4424)
CONTRIBUTING.md states every accepted contribution is credited in
CHANGELOG.md. Both fixes landed in the v0.46.25.0 backlog release
(squashed into
|
||
|
|
4e4677b1b9 |
fix(sync): record import status-"error" results as failures instead of checkpointing them as done (#2683 residual) (#4496)
* fix(sync): failed imports with status "error" are recorded as failures and never checkpointed (#2683 residual) The incremental import dispatch and the rename arm branch on status "imported" and the two "skipped" shapes, but an ImportResult with status "error" — importImageFile decode/embed failures, and importFile frontmatter-gate results that reach the importer directly — matched no branch: - Incremental site: the result fell into the final else and was checkpointed as DONE — the run reported synced, the bookmark advanced, and the failed file was never re-attempted (silent data loss). Fixed by an explicit status === "error" branch that pushes the path into failedFiles, feeding the #1939 failure ledger exactly like a thrown import error. - Rename arm: the failure was not even recorded, AND markCompleted(to) still ran (reconcileFailed only covers the stale-row reconcile), so the resume filter skipped the rename forever — a permanently unimported destination. Fixed by recording the failure and gating the success sentinel + checkpoint on a new importErrored flag; a THROWN destination import (which was already recorded) now also suppresses the checkpoint, same defect class. Two regression tests in test/sync-incremental-image-2683.test.ts: garbage bytes as broken.heic under GBRAIN_EMBEDDING_MULTIMODAL=true (incremental add), and a git-mv of markdown onto a .heic name (rename arm). Both fail on the unfixed dispatch (verified) and assert the second sync still reports the failure instead of up_to_date-ing past it. * chore(ratchet): sync.ts +18 for the #2683-residual status-error failure recording |
||
|
|
6e17806d4e |
fix(guardrails): count registration EVENTS with a pre-import baseline so side-effect and same-id registrations are accepted (#3688 residual) (#4505)
loadGuardrailProvidersFromEnv counted `providers.size` deltas with the
baseline captured AFTER `await import(target)`. Two false rejections
followed, both throwing the fail-closed GuardrailLoadError ("loaded
but registered no guardrail provider") against modules whose
guardrails were in fact registered and active:
- A module registering via TOP-LEVEL SIDE EFFECT (calling
registerGuardrailProvider at import time) registers DURING the
import — the after-import baseline counted it as zero.
- A module REPLACING an already-registered id (explicitly supported:
registerGuardrailProvider is "register or replace, by id") keeps
providers.size constant, so even a pre-import size baseline reads
the load as zero.
Fix: registerGuardrailProvider increments a monotonic
registrationEvents counter (only for accepted calls — the malformed-
provider guard still returns early), and the loader measures the
event delta from a PRE-import baseline. Only modules that register
nothing at all still trip the zero-provider guard.
Two regression tests in test/guardrails-env-load.test.ts (side-effect
module accepted; same-id replacement accepted); both fail on the
unfixed loader (verified: 8 pass / 2 fail pristine, 10/10 fixed).
Typecheck clean.
|
||
|
|
bad77b18af |
fix(frontmatter): ignore multimodal image assets (#4515)
Frontmatter validation is a Markdown-only operation, but multimodal mode makes the markdown sync strategy admit images. Keep binary assets out of bulk scans and reject explicit non-Markdown targets before any read or rewrite. Preserve explicit README and other Markdown metafile validation, and add regression coverage for git, fallback-walker, and single-file paths. Co-authored-by: Forge (Ron) <forge@zsimovan.dev> |
||
|
|
eb247ad8f4 |
fix(doctor): don't assert 'supervisor not running' when --fast never attempted the check that could prove it (#4520)
Fixes #4518. `gbrain doctor --fast` could permanently report `supervisor: not running` for a supervisor that is demonstrably alive, on the documented multi-queue pattern (distinct --pid-file per named queue, e.g. `--queue cron --pid-file ~/.gbrain/supervisor-cron.pid` alongside `--queue default --pid-file ~/.gbrain/supervisor-default.pid`). Root cause: the check reads a single un-scoped DEFAULT_PID_FILE (`~/.gbrain/supervisor.pid`). Any install using per-queue --pid-file values never writes that path, so `pidfileRunning` is always false for that install shape. The intended fallback — a DB singleton-lock lookup added specifically by #1849 to catch exactly this pidfile-path mismatch class — requires `engine`, which cli.ts hard-codes to `null` under `--fast` (`if (args.includes('--fast')) { ... runDoctor(null, ...) }`) before ever attempting a connection. So the #1849 fix is structurally unreachable under `--fast`, and the check falls back to asserting "not running" on evidence (an empty pidfile check) it never actually completed. Fix: track when the DB-lock fallback was skipped specifically because of --fast (not a "DB is actually down" case — see the added test that confirms a real DB-down scenario, i.e. engine null WITHOUT --fast, still correctly warns). When that's the situation, downgrade to an 'ok' check that says the pidfile check came back inconclusive under --fast, rather than asserting a liveness verdict the run structurally couldn't determine. Tests: 3 new cases (`test/doctor-fast-supervisor.test.ts`) — no supervisor ever observed → no check at all (unaffected baseline); audit events exist but no default-path pidfile under --fast → ok/ inconclusive, not the false "not running" warn (the #4518 regression case itself); same fixture without --fast → still warns (confirms the fix is --fast-specific, not a blanket engine-null suppression that would swallow a real DB-down signal) — 0 fail. 133 existing doctor/ self-upgrade/categories/supervisor-pidfile tests — 0 fail, unchanged. `bun run typecheck`, `bun run check:module-size`, `bun run verify` (54/54) all clean. module-size-limits.tsv: doctor.ts 4422->4443 (new branch + comment explaining the --fast/DB-lock interaction). No schema migration. |
||
|
|
01aab110d0 |
fix(cycle): extract_atoms rollup no longer counts transient errors as a halt (#4483)
TRANSIENT_EXTRACT_ERROR_RE's own doc comment says transient provider/ infra failures (timeouts, rate limits, 5xx, network) are "retryable, never counted" — but the extract_rollup_7d halt_delta/round_completed_delta computation used failures.length, which includes transient entries unconditionally. On a brain doing a heavy backlog drain against a rate-limited provider, this made the extract_atoms halt rate spike even though every hit was self-healing (retried next run), tripping doctor's extract_health WARN as if the extractor were genuinely failing. Adds a separate hardFailureCount that excludes transient per-item errors and transient (rate_limit-class) whole-run aborts, while `failures` itself stays unchanged for CLI/receipt reporting. Reviewed with Codex CLI (bounded exec, medium effort): 0 Critical/ Warning, 2 Suggestions (missing branch coverage for the non-transient thrown-error path; an ambiguous comment) — both addressed. A related but distinct issue (facts.conversation and propose-takes intentionally count expected budget/deadline-cap hits as halts too, which the extract_health check can't distinguish from real failures) is filed separately as garrytan/gbrain#4482 — out of scope here per a design consult with a second model, to keep this PR to the one self-contradicting implementation bug. |
||
|
|
2454ca3119 |
docs(code): correct chat_usage_log migration number in usage.ts comment (v136→v140, post-renumber)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
43701db059 |
docs: post-release audit for v0.46.28.0 (#4475)
- KEY_FILES.md: entries for the megawave's new core modules (embed-retry, search/private-visibility, entity-identity + ops, ai/chat-usage + get_usage); timeline-dedup-repair entry updated to the md5(summary) canonical index shape (migration v138); model-config resolveModel chain updated to the tier-above-default precedence (#3873); stale schema-embedded.ts name refreshed to schema-embedded.generated.ts (2 sites). - RETRIEVAL.md: pipeline diagram gains the exact-lookup tier; new section for the private-visibility and CRAG confidence seams (current-state). - TODOS.md: marked #1663 remainder, #2544 second half, #4117 output_root done; trimmed #4119 to its unshipped arms; updated the #4198 adjacency note; filed megawave follow-ups #4477 #4478 #4479 #4480; schema-embedded rename in the parity-test TODO. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> |