Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master (v0.60.60.0) into garrytan/6007-remote-bulk-writes; stamp v0.60.61.0

garrytanc1b2c7919a66
diff --cc .claude-plugin/plugin.json
index 1e0a30ca35,c7f9252be3..46ffb529f0
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --cc .codex-plugin/plugin.json
index 474042701e,af362d6a53..505c2fd5ad
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --cc .github/workflows/persistence-validation.yml
index 5b8f4d7352,d079f4160a..f603f30ee1
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@@ -160,6 -160,139 +160,140 @@@ jobs
path: .context/persistence-runtime-matrix.json
if-no-files-found: error
+ # Unit-lane suites whose PostgreSQL arm is gated on DATABASE_URL: the unit,
+ # serial and slow lanes unset it, so these arms run only here (both arms per
+ # file; the PGLite arm also runs in the unit lane). scripts/check-postgres-lane-coverage.ts
+ # fails a new DATABASE_URL-gated arm until it is listed here or wrapped in a
+ # test/e2e registerPostgresTests file. The two shards are balanced by measured runtime.
+ unit-postgres-arms:
+ name: Unit-lane PostgreSQL arms ${{ matrix.shard }}/2 / Bun ${{ matrix.bun }}
+ runs-on: ubicloud-standard-4-ubuntu-2404
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ shard: [1, 2]
+ bun: ['1.4.0', '1.4.2']
+ # Pull requests run the primary Bun version; pushes, schedules and
+ # manual runs keep every supported version.
+ exclude: ${{ fromJSON((github.event_name == 'pull_request' || github.event_name == 'merge_group') && '[{"bun":"1.4.0"}]' || '[]') }}
+ services:
+ postgres:
+ image: pgvector/pgvector:pg16
+ env:
+ POSTGRES_USER: gbrain_test
+ POSTGRES_PASSWORD: gbrain_test
+ POSTGRES_DB: gbrain_test
+ ports: ['5432:5432']
+ options: >-
+ --health-cmd "pg_isready -U gbrain_test -d gbrain_test"
+ --health-interval 5s --health-timeout 5s --health-retries 20
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: ${{ matrix.bun }}
+ - run: bun install --frozen-lockfile --ignore-scripts
+ - name: Require PostgreSQL arms of unit-lane suites
+ timeout-minutes: 20
+ shell: bash
+ env:
+ DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ SHARD: ${{ matrix.shard }}
+ run: |
+ : "${DATABASE_URL:?unit-lane PostgreSQL arms require the explicit test database}"
+ case "$SHARD" in
+ 1) files=(
+ test/attribution-backfill-history.test.ts
+ test/colon-slug-windows-5032.test.ts
+ test/decide/conflict-proposals-managed.test.ts
+ test/declared-lineage-visibility.test.ts
+ test/extract-endpoint-revision.serial.test.ts
+ test/graduation-digest.test.ts
+ test/graduation-drain.test.ts
+ test/graduation-inventory.test.ts
+ test/graduation-state.test.ts
+ test/grandfather-managed.test.ts
+ test/harness-skills-epoch.test.ts
+ test/links-attendance-blocked.test.ts
+ test/managed-cycle-pull-upstream.test.ts
+ test/managed-lint.test.ts
+ test/managed-maintenance-links.test.ts
+ test/managed-sync-drain.test.ts
+ test/pack-relation-direction-engine.test.ts
++ test/page-embedding-install-batch.test.ts
+ test/page-state-engine.test.ts
+ test/persistence-commit-durability.test.ts
+ test/persistence-deactivate.test.ts
+ test/persistence-file-import.test.ts
+ test/persistence-graph-publication.test.ts
+ test/persistence-managed-lifecycle.test.ts
+ test/persistence-managed-sync.test.ts
+ test/persistence-memory-mutations.test.ts
+ test/persistence-page-authority.test.ts
+ test/persistence-skill-bundles.serial.test.ts
+ test/shared-content-freshness.test.ts
+ test/shared-skills-writer-boundary.test.ts
+ test/source-retire-missing-checkout.test.ts
+ test/sync-legacy-holds.test.ts
+ test/takes-vector-lifecycle-5885.serial.test.ts
+ test/withdrawal-overlay-concurrency.test.ts
+ ) ;;
+ 2) files=(
+ test/alias-source-cascade-5094.test.ts
+ test/company-brain-policy.test.ts
+ test/company-brain-runtime.test.ts
+ test/derived-link-reconciliation.test.ts
+ test/doctor-frontmatter-holds.test.ts
+ test/embedding-completion-atomic.serial.test.ts
+ test/graduation-copy.test.ts
+ test/graduation-rollback.test.ts
+ test/graduation-target.test.ts
+ test/graduation-verify.test.ts
+ test/held-read-signals.test.ts
+ test/import-frontmatter-key-order-5158.test.ts
+ test/import-revision-concurrency.test.ts
+ test/managed-sweep-corpus-windows.test.ts
+ test/managed-sync-bulk.test.ts
+ test/managed-sync-chunker-version.test.ts
+ test/managed-sync-group-completion.test.ts
+ test/persistence-diagnostics.test.ts
+ test/persistence-git-subdir-origin.test.ts
+ test/persistence-history-fixture.test.ts
+ test/persistence-image-import.serial.test.ts
+ test/persistence-physical-root-device.test.ts
+ test/persistence-skill-crash.slow.test.ts
+ test/persistence-sync-cursor-options.test.ts
+ test/persistence-sync-holds.test.ts
+ test/persistence-writer-fences.test.ts
+ test/repair-embedding-effects.test.ts
+ test/repair-frontmatter.test.ts
+ test/shared-skills-catalog.test.ts
+ test/shared-skills-retention-capacity.test.ts
+ test/stats-health-source-scope.test.ts
+ test/sync-frontmatter-recovery.test.ts
+ test/sync-frontmatter-slug-conflict.test.ts
+ test/withdrawal-publication-file.test.ts
+ ) ;;
+ *) echo "::error::unknown shard $SHARD" >&2; exit 1 ;;
+ esac
+ # One bun process per file: *.serial.test.ts files require their own
+ # process, and a test that fails while its body keeps running would
+ # otherwise leak process.env into every later file (one such leak
+ # deleted DATABASE_URL for the rest of a shard and silently dropped
+ # those files' PostgreSQL arms).
+ failed=()
+ for file in "${files[@]}"; do
+ echo "::group::$file"
+ bun --no-env-file test --timeout=120000 "$file" || failed+=("$file")
+ echo "::endgroup::"
+ done
+ for file in ${failed[@]+"${failed[@]}"}; do
+ echo "::error file=$file::PostgreSQL arm failed. Reproduce: DATABASE_URL=<pgvector test database> GBRAIN_TEST_ALLOW_DATABASE_URL=1 bun test --timeout=120000 $file"
+ done
+ [ "${#failed[@]}" -eq 0 ]
+
invariants:
name: ${{ matrix.engine }} / Bun ${{ matrix.bun }}
# The soak uses 1.3-1.8 busy cores: the 2,500-write PGLite soak took 523s on
diff --cc BOOTSTRAP_FOR_AGENTS.md
index 2046e04357,a69acb9563..da91b4731d
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-runbook-stamp: 0.60.59.0 -->
-<!-- gbrain-runbook-stamp: 0.60.60.0 -->
++<!-- gbrain-runbook-stamp: 0.60.61.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --cc CHANGELOG.md
index 7b8c6fec05,5f09982178..e22a6204d1
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,63 -10,159 +10,216 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
- ## [0.60.59.0] - 2026-10-05
++## [0.60.61.0] - 2026-10-05
+
+**An agent connected to a remote brain can now save a stack of long pages in under a minute, and gbrain tells it how.**
+
+Agents writing to a brain over MCP (for example through `gbrain serve --http` on another machine) used to save pages one at a time, and each page cost several seconds of back-and-forth with the database. A large page also outlasted the reply's built-in wait, so the agent got "still pending" and had to keep asking. Writing 27 long research pages took about 15 minutes, followed by around 30 more calls to wire up links the pages already contained.
+
+Now the agent sends its pages in batches with `put_pages`, waits for the commit in the same reply with `wait_ms`, and the server links `[[wikilinks]]` between the pages by itself. The server also does far less database work per page and publishes a whole batch in one transaction. The instructions every MCP agent receives at connect time say all of this up front.
+
+Measured with 25 pages of 60 KB each, written over MCP to a Postgres brain 30 ms away (round trip), with embeddings and Git on:
+
+| | Before | Now |
+| --- | --- | --- |
+| 25 pages, one `put_page` at a time, with polling | nearly 5 minutes (about 11 s a page) | not needed |
- | 25 pages, 4 `put_pages` calls sent one after another | not available | 51 s, no polling |
++| 25 pages, 4 `put_pages` calls sent one after another | not available | 48 s, no polling |
+| One 60 KB `put_page` | 7.2 s reply saying "pending", then polls (about 11 s total) | committed in about 6 s, in the reply |
- | SQL statements on one page's publish path | 135 | 107 |
++| SQL statements on one page's publish path | 135 | 110 |
+| Backlinks between the pages you just wrote | about 30 manual `add_link` calls | built automatically after the commit |
+
- ## To take advantage of v0.60.59.0
++## To take advantage of v0.60.61.0
+
+`gbrain upgrade` should do this automatically. Remote agents pick up the new instructions the next time they connect.
+
+1. **Tell your agent** (or let the connect-time instructions do it): *"When you save more than three pages to gbrain, use put_pages with one request_id per batch and wait_ms 25000."*
+2. **Turn mention links off** if you don't want them: `gbrain config set mcp.remote_auto_links false`.
+3. **Verify:** `gbrain call put_pages '{"request_id":"<uuid>","pages":[{"slug":"notes/test-a","content":"# A"},{"slug":"notes/test-b","content":"# B\n\nSee [[notes/test-a]]."}],"wait_ms":25000}'` returns `"state": "committed"`, and `gbrain call get_links '{"slug":"notes/test-b"}'` shows the `mentions` link to `notes/test-a`.
+
+### Itemized changes
+
+#### Batch writes
+- New MCP tool `put_pages` (full surface): 1-50 complete pages, 8 MB of content at most, per call. Every page is an ordinary `put_page` write with the same fences, revision checks and receipts. The pages are accepted together, so queue capacity (request count and bytes) is reserved for the whole batch, or the call refuses with `queue_capacity` and accepts none.
+- One receipt per batch: the state of each page with its revision or its own error envelope, totals, `links`, and `next` (`done`, `poll` or `fix_pages`). A page refused for its own reason does not stop the others. A grant that cannot write refuses the whole call with one `permission_denied`.
+- Replaying the identical call with the same `request_id` never writes twice. `put_pages` with only `request_id` reports progress without resending content. A replay with different pages refuses with `idempotency_conflict` and names the changed pages.
+- Every page needs `put_page` permission; bound clients get each page's slug fenced like `put_page`.
+
+#### Waiting for the commit
+- `put_page` and `put_pages` accept `wait_ms` (0-30000, counted from arrival; default 5000 for `put_page`, 25000 for `put_pages`). It is not part of the write's identity, so a replay with a different wait is still the same write. Out-of-range values refuse with `invalid_write_wait` before anything is accepted.
+- A pending receipt's `retry_after_ms` comes from the server's recent publishing pace instead of a fixed 1 s.
+- `get_write_request` states its poll cadence and final states; a pending `put_page` names `wait_ms` and `put_pages`.
+
+#### Faster publishing
+- A `put_pages` batch publishes up to 8 pages per database transaction, with file-safe recovery: if one page fails, the group rolls back, every file is restored, and the pages publish one at a time so each failure stays with its own page.
+- Fewer database round trips per write: claiming, admission, recovery records and completion each take fewer statements, a page's own writes skip repeated reads, and a batch's shared admission reads run once.
+- Connector writes wait for a pending withdrawal rewrite of the same page before reading its file, so a sync right after a `forget` no longer fails with `source_changed`.
+
+#### Links for remote writes
+- Remote `put_page`, `put_pages`, `capture` and `edit_page` writes queue a `links` effect after the commit. It turns `[[wikilinks]]` and markdown links in the page body into plain `mentions` links to pages that already exist in the same source, are visible to the writer and sit inside its slug grant. Typed, frontmatter and timeline edges stay off for untrusted writes. A batch links its pages to each other once its last page commits.
+- On by default; `mcp.remote_auto_links false` turns it off. Receipts report `auto_links.mention_links` and the effect's `added`/`removed` counts.
+
+#### Agent guidance
+- The connect-time instructions put the prompt-critical lines first, so harnesses that read only the first 2,048 characters still see them: `context_pack` at session start, `put_page` replaces the whole page, and the writing guidance (`put_pages`, `wait_ms`, following `next`).
+- `put_page`, `add_link` and `add_timeline_entry` descriptions say when links and timeline entries come from the page itself.
+- The simple HTTP transport's 413 reply tells the agent to split the request and names `GBRAIN_HTTP_MAX_BODY_BYTES`.
+
+### For contributors
+- New e2e coverage: Postgres statement budgets per write phase, two-connection page-guard tests, grouped `put_page` publication (happy path and per-member failure), and the remote links effect on both engines.
+- The initialize-instructions and served-schema budgets grew for the write guidance; a new test pins the prompt-critical lines inside the first 2,048 characters.
+
+ ## [0.60.60.0] - 2026-10-05
+
+ **Ask your brain a question that chains relationships, like "who founded the companies Alice invested in?", and search now walks those links step by step and returns the founders with the path that connects them.**
+
+ Until now, search understood one relationship per question. "Who invested in Acme?" worked. "Who founded the companies Alice invested in?" did not: it needs two steps (Alice's investments, then each company's founders), and search would hand back pages that merely mentioned Alice. Now a question that chains two or three relationships (founded, invested in, advises, works at, attended) is read into a short plan and answered by walking the typed links in your brain. Each answer arrives with the chain of links that supports it, and the pages along the way come with it. No AI model is involved: the reading is a fixed grammar, so the same question always gets the same plan.
+
+ ### How to use it
+
+ It is on by default in the `balanced` and `tokenmax` search modes. Ask in plain English through `search`, `query`, `recall` or `think`. To name the chain yourself, use `gbrain graph-query <slug> --hop invested_in:object --hop founded:subject`, or the `hops` parameter of the `traverse_graph` tool. To turn the planner off: `gbrain config set search.relational_planner false`.
+
+ ### The numbers that matter
+
+ Measured on a held-out set of 125 chained questions the planner was never developed on, run by an independent custodian:
+
+ | What we measured | Before | Now |
+ | --- | --- | --- |
+ | Chained questions where every needed page is in the top 10 | 0% (eval settings), 1.1% (shipped defaults) | 27.0%, 28.1% |
+ | Questions better / worse | | 24 better, 0 worse |
+ | Answers the chain returns that are correct | | 83% |
+ | Wrong pages ranked above the first right one | 3.31 per question | 0.09 |
+ | Ordinary questions that set it off by mistake | | 0 of 627 |
+
+ ### Things to watch
+
+ | Change | What to do |
+ | --- | --- |
+ | Reworded questions are often not recognized: the planner read 70% of plainly worded chained questions and 21% of reworded ones | when a chained question comes back without `relational_plan`, call `traverse_graph` with explicit `hops` |
+ | Chains walk relationships that are true today: an advisory role or job that ended is skipped | ask "formerly advised" or "used to work at" to walk ended ones |
+ | Search cache keys for `balanced` and `tokenmax` change | cached results refill on their own |
+ | Added search time on a chained question | about 15 ms on a 240-page brain, up to about 55 ms on a 100,000-link graph |
+
+ ## To take advantage of v0.60.60.0
+
+ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+ 1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
+ 2. **Nothing else to migrate.** There is no schema change; the planner turns on through the search mode defaults.
+ 3. **Verify:**
+ ```bash
+ gbrain search modes --json | grep relational_planner
+ gbrain search "Who founded the companies that <a person in your brain> invested in?" --json
+ ```
+ 4. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor` and `~/.gbrain/upgrade-errors.jsonl` if it exists.
+
+ ### Itemized changes
+
+ - **Planner** (`src/core/search/relational-plan.ts`): `parseRelationalPlan` turns a 2-3 relation question into anchor-outward typed hops, or returns `not_applicable` (single relation, left to `parseRelationalQuery`) or `unsupported` with a reason (coordination, negation, dates, counting, quoted names, more than one entity). Tense markers before a relation that can end set that hop's status ("formerly advised" walks ended roles).
+ - **Executor** (`src/core/search/relational-chain.ts`, `readChainHop` in `src/core/search/read-enrichment.ts`, `BrainEngine.relationalChainHop`): one bounded query per hop (50 frontier pages, 100 links per page, 10 paths per page), links oriented by each relation's page-type signature, read scope applied to every endpoint, origin and degree contributor, the temporal-edge validity predicate on every hop, path-local cycles cut, hub weighting at half-degree 32 (`src/core/search/hub-dampening.ts`).
+ - **Search**: chain rows carry a `relational` field (role, seed, hop, path count, up to three evidence edges) through fusion, lean rows and recall; up to `search.relational_chain_slots` (default 10) chain rows lead page 1; `meta.relational_plan` and a `relational_chain` notice report the outcome; a chain error is audited and falls back to the one-hop path.
+ - **Agent surface**: `traverse_graph` takes optional `hops` (full MCP surface only, so the starter list stays inside its size budget); `gbrain graph-query --hop link_type:toward`.
+ - **Config**: `search.relational_planner` (on in `balanced` and `tokenmax`), `search.relational_orient_onehop` (off; one-hop walks that also read links written on the other page), `search.relational_chain_slots`.
+ - **Records**: `docs/eval/decisions/p7-heldout-2026-10-05/` (held-out verdict), `docs/eval/decisions/p7-dev-2026-10-04/` (development verdict), `docs/guides/multi-hop.md`.
+
+ ## [0.60.59.0] - 2026-10-05
+
+ **Every test CI claims to run now proves it ran, by name; red nightly runs open an issue instead of going unseen; PR CI goes green about 30% sooner on about 20% less compute; and `gbrain eval run-all` stops reporting success for work it skipped.**
+
+ This is a test, eval and CI fix wave. For you it makes two eval commands honest. For anyone changing gbrain, CI stops crying wolf: flaky tests are fixed at the root, red nightly runs open an issue instead of going unseen, coverage that never executed now executes, and pull-request CI is faster.
+
+ ### What changes for you
+
+ - **`gbrain eval run-all` tells the truth.** A bare run runs only the suites it can run (BrainBench). Naming a suite it does not run (`--suites longmemeval,replay`) exits 1 with `eval_suite_unwired` and the per-suite commands as the fix, and a failed suite exits 1 instead of 0.
+ - **`gbrain eval takes-quality` prices every model the canonical pricing table knows.** The private six-model allowlist is gone. An unpriced model warns and runs; under a `--budget-usd` cap it refuses with `no_pricing` and the `gbrain pricing set` command to register its rate.
+
+
+ ### What changes for contributors
+
+ | Pull-request CI (`test.yml` + `e2e.yml`) | Before | Now |
+ | --- | --- | --- |
+ | Time to green | 1010-1067 s | 696-874 s (median 743 s) |
+ | Ubicloud vCPU-minutes per run | 899-940 | 739-755 |
+ | Critical path | Selected E2E | a unit shard (Test) |
+ | Selected E2E shard max / mean | 904 / 721 s (4 workers) | 365-451 / 323-345 s (8 workers) |
+ | Unit shard max / mean | 762 / 542 s | 614-732 / 544-567 s |
+ | Tests that ran in no lane | 55 PostgreSQL arms and 12 dead opt-in gates (the compile smoke among them) | 0 (one allowlisted arm with a TODO) |
+
+ Before: the three baseline runs of the master tree on 2026-10-04. Now: the three acceptance runs of this branch on the re-mined weights. Both sets of run ids are in `docs/test-audit/2026-10-04/baseline.md`, and every run executes the baseline's test identities or declares the change in `expected-deltas.tsv`.
+
+ ### Things to watch
+
+ | Change | What to do |
+ | --- | --- |
+ | Test opt-ins under the old names stop the run with the rename command | `GBRAIN_BASH32_REQUIRE` → `GBRAIN_TEST_BASH32_REQUIRE`, `GBRAIN_PERF_BUDGET_MULTIPLIER` → `GBRAIN_TEST_PERF_BUDGET_MULTIPLIER`, `GBRAIN_SKIP_SUBPROCESS_TESTS` → `GBRAIN_TEST_SKIP_SUBPROCESS`, `GBRAIN_REQUIRE_LAUNCHD` → `GBRAIN_TEST_REQUIRE_LAUNCHD`, `GBRAIN_SKIP_LAUNCHD_E2E` → `GBRAIN_TEST_SKIP_LAUNCHD`, `GBRAIN_ENFORCE_E5_BUDGET` → `GBRAIN_TEST_ENFORCE_E5_BUDGET`, `GBRAIN_REQUIRE_COMPILE` → `GBRAIN_TEST_REQUIRE_COMPILE`. Under the old names the test preload deleted them, so they never worked. |
+ | A new `*.serial.test.ts` file needs a row in `scripts/serial-files.tsv` | run `bash scripts/check-test-isolation.sh --as-parallel <file>` first; if it passes and the file touches no process-wide state, name it `*.test.ts` instead |
+ | A test file with a `DATABASE_URL`-gated arm needs a Postgres lane | `bun run check:postgres-lanes` names the file and the workflow list to add it to |
+ | A stale generated artifact fails `verify` | `bun run regen:all` regenerates everything and lists what changed |
+ | `docs/TESTING.md` has a 120 KB cap that only goes down | move subsystem detail next to its code instead of growing the file |
+ | E2E narrowing is retired | doc-only changes skip E2E; every other change runs the whole E2E corpus |
+ | Removed modules | `src/core/chunkers/semantic.ts`, `src/core/chunkers/llm.ts`, `src/core/search/keyword.ts` and `src/core/search/vector.ts` had no importer (use `src/core/search/hybrid.ts`); the forward-reference bootstrap facade (import `src/core/engine-sql/bootstrap.ts`); `scripts/check-exports-count.sh` (`test/public-exports.test.ts` owns the contract); the skillopt judge and reflect evals |
+ | The eval ledger `.gbrain-evals/eval-results.jsonl` is local | it is gitignored; `--record` modes keep appending to your local copy |
+
+ ## To take advantage of v0.60.59.0
+
+ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+ 1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
+ 2. **Nothing else to migrate.** There is no schema change.
+ 3. **Verify:**
+ ```bash
+ gbrain doctor --json
+ ```
+ 4. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor` and `~/.gbrain/upgrade-errors.jsonl` if it exists.
+
+ ### Itemized changes
+
+ #### Fixes
+
+ - `gbrain eval run-all`: bare runs run wired suites only; `eval_suite_unwired` (exit 1, with `gbrain errors eval_suite_unwired`); a failed suite exits 1.
+ - `gbrain eval takes-quality`: canonical pricing for every model, registered overrides first; unpriced models warn and run; `no_pricing` under a user cap.
+ - Scale harness: the `find_orphans` known answer reads the op's maximum page and compares with `total_orphans`.
+
+ #### Flakes fixed at the root
+
+ - `test/physical-root-walk.test.ts` pins the `sources add` walk against a subdirectory vanishing mid-walk, with a two-brain `.git` reservation case (B1); a leaked `check-update --refresh-cache` child in the self-upgrade breadcrumb test; facts-queue tests wait on queue counters instead of fixed sleeps; the child-readiness test requires the confirmed timeout message (tini contract documented); a `persistence-deactivate` race where an `await` inside a `.rejects` matcher let Postgres reject before the handler attached and leaked env into later files; the gateway baseline is restored after `gateway-chat.test.ts`, folded from community PR #5907, contributed by @nezovskii. Thank you.
+ - `waitFor` deadlines scale with `GBRAIN_TEST_WAIT_MULTIPLIER` (1 to 4; coverage lanes set 2), capped at 50 s.
+ - Verify's fallback watchdog (hosts without `timeout`) no longer leaves orphaned `sleep` processes holding the caller's pipes.
+
+ #### Every claimed test now runs
+
+ - Executed-test receipts: every Bun invocation in CI writes a receipt and a JUnit report; `scripts/ci-executed-counts.ts` compares runs by (lane, file, test, backend arm) and fails on an undeclared drop or an incomplete run. Verify records each check as pass, fail, timeout or skip (`GBRAIN_CHECK_SKIPPED:`) and keeps its logs on failure. A red job's step summary lists the failing tests with a reproduce command.
+ - 55 unit-file PostgreSQL arms that ran in no lane run in persistence-validation's `unit-postgres-arms` job, one Bun process per file; `check:postgres-lanes` keeps it that way.
+ - 12 dead opt-in gates renamed under `GBRAIN_TEST_*`; the compiled self-update smoke runs unconditionally; `check:test-env-opt-ins` fails on a test gated on a name the preload strips.
+ - The agent-voice recipe's unit suite runs in CI (`bun run test:agent-voice`); `check:jsonb-params` and `check:image-decoders` run in `verify`; scripts/ is typechecked; guard self-test fixtures cover seven more guards; the privacy guard scans `evals/` and `docs/test-audit/`; `test/docs-repo-paths.test.ts` fails on a doc naming a missing repo path; the skill-refs allowlist fails on stale rows.
+ - Blind source pins in six suites (each passed with its behavior broken) are replaced by behavioral owners; probes are in `docs/test-audit/2026-10-04/implementation/lane-c.md`.
+
+ #### Red nightlies become issues
+
+ - `nightly-watch.yml` opens, updates, reopens and closes one `Nightly red: <workflow>` issue per scheduled workflow, with the failing jobs, the last green commit and the next step; `.github/nightly-known-red.tsv` holds at most three known-red or known-skipped rows, each owned by a TODO.
+ - A weekly `ci-health.yml` report lists first-attempt pass rates and the most-failing test files.
+ - Heavy Tests: the Docker image copies `patches/`; `postinstall.ts` exits 0 without `src/`; every heavy script runs and prints a rerun command per failure; the Claude door runs even when the Codex door fails.
+ - Missing provider secrets are a visible warning (Hermes, real-agent doors, publish-template, key-gated E2E), never a silent green.
+ - The scale tier runs under an out-of-process phase watchdog that names the stalled phase; the vectors phase prints one line per batch.
+
+ #### Faster and cheaper pull-request CI
+
+ - E2E selection is one rule: doc-only changes select nothing, everything else selects the whole corpus, read from the pull request files API on a shallow checkout and failing closed on a truncated list. Up to eight Selected E2E workers on 2 vCPU; the E2E backend matrix moves to its own two 4 vCPU shards and stops running a second time in Selected E2E; serial tests on 4 vCPU; the longmemeval slow file joins the unit shards; unit shards stay on 4 vCPU (2 vCPU raised the shard mean from 542 s to 608 s).
+ - 92 serial files that pass the isolation lint and touch no process-wide state rejoin the parallel lane; `scripts/serial-files.tsv` lists the remaining serial files with a class and reason.
+ - Shorter test waits through production-default seams (connector fixture, maintenance publish wait, effect renewal interval), and `test/helpers/brain-template.ts` clones initialized disk brains instead of replaying migrations.
+ - Shard weights re-mined from this branch's green run; `check:weight-coverage` fails on stale entries and warns on unweighted shares.
+ - `merge_group` triggers (inert until the merge queue is enabled) use the PR profile; a version-only `package.json` diff no longer widens the native test scope; dependency audit blocks only when dependencies change or on master, schedules and dispatches; Semgrep uploads SARIF weekly.
+
+ #### Docs and tooling
+
+ - `bun run regen:all` regenerates every generated artifact; `check:regen-all` in verify.
+ - `docs/TESTING.md` opens with a quick start, drops the test inventories and moves subsystem detail beside its code (120 KB ratchet cap).
+ - Removed: unreferenced chunkers and search modules, the forward-reference facade, dead test seams, finished one-off scripts, a broken benchmark, the skillopt judge and reflect evals, a fixture naming a real person, and the exports-count and pagetype-exhaustive guards.
+
## [0.60.58.0] - 2026-10-04
**A managed Postgres brain far from its database catches up a sync backlog about 2.7 times faster again, and every write to it costs fewer round trips (#5984).**
diff --cc VERSION
index ae212c0527,9de3247158..7a4ccfd46d
--- a/VERSION
+++ b/VERSION
@@@ -1,1 -1,1 +1,1 @@@
- 0.60.59.0
-0.60.60.0
++0.60.61.0
diff --cc openclaw.plugin.json
index a72d6fae10,fd40c92f71..717405494a
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --cc package.json
index 2c9b75fa42,174875d294..3796550629
--- a/package.json
+++ b/package.json
@@@ -212,7 -218,7 +218,7 @@@
"bun": ">=1.4.0"
},
"license": "MIT",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.56",
"@hono/node-server": "^2.0.5",
diff --cc plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 687283823e,d1c953c0ed..040d31fa5d
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-coding",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 06e6fb6a5c,49ffc220b2..6024bfc254
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-coding",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-coding/README.md
index 3faa255e3f,5a8afad3e3..9c43944f8f
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-plugin-tree-stamp: 0.60.59.0 -->
-<!-- gbrain-plugin-tree-stamp: 0.60.60.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.61.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --cc plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 5d4d60283b,44057234f2..65276a7068
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-daily",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index a8a00f9f2a,57658ab0b8..2bfc9cbada
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-daily",
- "version": "0.60.59.0",
- "version": "0.60.60.0",
++ "version": "0.60.61.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-daily/README.md
index 0c99a92bb2,7f0a523f89..63189ca6d1
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-plugin-tree-stamp: 0.60.59.0 -->
-<!-- gbrain-plugin-tree-stamp: 0.60.60.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.61.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --cc plugin/README.md
index df9b1f1cc1,89f4fe9918..23568a9c88
--- a/plugin/README.md
+++ b/plugin/README.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-plugin-tree-stamp: 0.60.59.0 -->
-<!-- gbrain-plugin-tree-stamp: 0.60.60.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.61.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --cc scripts/module-size-limits.tsv
index f2ba3d5fff,ee3778a527..e6e0a2dd86
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -16,14 -16,14 +16,14 @@@ src/commands/sync.ts 510 ratchet refact
src/core/cycle.ts 3250 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts)
src/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)
- src/core/engine.ts 2683 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured)
+ src/core/engine.ts 2693 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
+src/core/operations.ts 337 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)
- src/core/pglite-engine.ts 2983 ratchet +4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured)
- src/core/postgres-engine.ts 2920 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured)
+ src/core/pglite-engine.ts 2987 ratchet +4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate
+ src/core/postgres-engine.ts 2924 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
- src/core/types.ts 2125 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +1 GBRA-49: temporal annotation field on link rows
+ src/core/types.ts 2202 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop)
src/core/minions/queue.ts 2523 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack
src/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
diff --cc src/core/ops/persistence.ts
index a4b4b6aa3d,48e0675c63..7a782beae0
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@@ -135,7 -135,7 +135,7 @@@ export const persistenceOperations: Ope
name: 'get_write_request',
idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Read your write\'s receipt by request_id (after write_pending or a lost reply). Poll at retry_after_ms until it is final.',
- description: 'Read the receipt of your write by request_id (after write_pending or a lost reply).',
++ description: 'Read your write\'s receipt by request_id (after write_pending or a lost reply). Poll at retry_after_ms until final.',
params: { request_id: requestParam },
scope: 'write', mutating: false, area: 'pages',
cliHints: { name: 'write-request', positional: ['request_id'] },
diff --cc templates/bootstrap/template-repo/README.md
index ef0860fb41,4a1519b218..80c335eaf5
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@@ -1,6 -1,6 +1,6 @@@
# gbrain agent workspace — template
- <!-- gbrain-template-stamp: 0.60.59.0 -->
-<!-- gbrain-template-stamp: 0.60.60.0 -->
++<!-- gbrain-template-stamp: 0.60.61.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --cc test/e2e/persistence-statement-budget.test.ts
index 3d092599bb,0000000000..4ebbab29d0
mode 100644,000000..100644
--- a/test/e2e/persistence-statement-budget.test.ts
+++ b/test/e2e/persistence-statement-budget.test.ts
@@@ -1,199 -1,0 +1,199 @@@
+/**
+ * #6007: SQL statements one remote put_page of a new ~60 KB page issues on
+ * Postgres, per phase of the coordinated write path, counted at the socket by
+ * the env-gated wire trace (src/core/sql-trace.ts). Each round trip is one
+ * record; `execute` and `simple` records are statements, `describe` records
+ * are the extra round trip a statement pays the first time a pooled
+ * connection prepares it (reported, not budgeted: which connection runs a
+ * statement is not deterministic).
+ *
+ * Phases come from the transaction each statement runs in (begin..commit on
+ * one connection, labelled by its signature statement) and, for statements
+ * outside a transaction, from known consumer-scan and effect statements or
+ * the statement's position between the transactions.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { hasDatabase } from './helpers.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+
+interface TraceRecord { t: number; ms: number; conn: number; kind: string; sql: string }
+type Phase = 'admission' | 'claim' | 'prepare' | 'recovery_record' | 'publication' | 'completion' | 'consumer_scan' | 'wait_poll' | 'effects' | 'other';
+const CRITICAL: Phase[] = ['admission', 'claim', 'prepare', 'recovery_record', 'publication', 'completion'];
+
+/**
- * Per-phase statement budgets, about 10% above the measured counts (#6007
- * measured admission 25, claim 5, prepare 19, recovery record 6, publication
- * 46, completion 6: 107 on the critical path, and an 8-statement receipt; the
++ * Per-phase statement budgets, about 10% above the measured counts (#6007 on
++ * v0.60.60.0 measured admission 27, claim 5, prepare 19, recovery record 6,
++ * publication 47, completion 6: 110 on the critical path, and an 8-statement receipt; the
+ * code before #6007 measured 29, 5, 21, 9, 61, 10: 135, and 10). The claim
+ * counts only the transaction that claimed this write; another tick's empty
+ * claim attempt is a consumer scan.
+ */
+const BUDGET: Record<string, number> = {
+ admission: 28, claim: 6, prepare: 21, recovery_record: 7, publication: 50, completion: 7, critical_path: 118, receipt: 9,
+};
+
+const SCAN = [
+ /^SELECT \( EXISTS/, /^SELECT EXISTS \(SELECT 1 FROM persistence_requests r/, /FROM persistence_brain WHERE singleton=1/,
+ /persistence_host_bindings h JOIN persistence_source_bindings/, /r\.recovery IS NOT NULL AND NOT\(r\.worktree_id/,
+ /FROM persistence_effects e JOIN persistence_worktrees w ON w\.id=e\.worktree_id WHERE e\.recovery IS NOT NULL/,
+ /FROM persistence_topology_changes c/, /FROM persistence_worktree_refreshes f JOIN/, /^WITH expired AS/, /page_projection_jobs/,
+];
+const statementKinds = new Set(['execute', 'simple']);
+const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+
+function classify(records: TraceRecord[]) {
+ const sorted = records.filter(r => r.kind !== 'connect').sort((a, b) => a.t - b.t);
+ const open = new Map<number, TraceRecord[]>();
+ const groups: { records: TraceRecord[]; begin: number; end: number }[] = [];
+ const standalone: TraceRecord[] = [];
+ for (const record of sorted) {
+ const text = flat(record.sql).toLowerCase();
+ const group = open.get(record.conn);
+ if (text === 'begin' && record.kind === 'simple') { open.set(record.conn, [record]); continue; }
+ if (!group) { standalone.push(record); continue; }
+ group.push(record);
+ if (text === 'commit' || text === 'rollback') {
+ open.delete(record.conn);
+ groups.push({ records: group, begin: group[0]!.t, end: record.t });
+ }
+ }
+ for (const group of open.values()) groups.push({ records: group, begin: group[0]!.t, end: group[group.length - 1]!.t });
+ const labelled = groups.map(group => {
+ const text = group.records.map(r => flat(r.sql)).join('\n');
+ let phase: Phase = 'other';
+ if (/INSERT INTO persistence_requests/.test(text)) phase = 'admission';
+ else if (/SET publication_started=true|UPDATE persistence_requests SET state=\$2,outcome/.test(text)) phase = 'publication';
+ else if (/UPDATE persistence_requests SET recovery=\$3/.test(text)) phase = 'recovery_record';
+ else if (/UPDATE persistence_requests (r )?SET recovery=NULL/.test(text)) phase = 'completion';
+ // A claim transaction that claimed nothing is another consumer tick's empty attempt, not this write's claim.
+ else if (/FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w\.id=r\.worktree_id WHERE r\.state='queued'/.test(text)) phase = /SET state='running'/.test(text) ? 'claim' : 'consumer_scan';
+ else if (/persistence_effects/.test(text)) phase = 'effects';
+ return { ...group, phase };
+ });
+ const anchor = (phase: Phase, edge: 'begin' | 'end') => {
+ const found = labelled.filter(group => group.phase === phase);
+ return found.length ? (edge === 'begin' ? Math.min(...found.map(g => g.begin)) : Math.max(...found.map(g => g.end))) : undefined;
+ };
+ const admissionBegin = anchor('admission', 'begin') ?? Infinity;
+ const claimEnd = labelled.filter(g => g.phase === 'claim' && /SET state='running'/.test(g.records.map(r => r.sql).join('\n'))).map(g => g.end)[0]
+ ?? standalone.find(r => /^UPDATE persistence_requests SET state='running'/.test(flat(r.sql)) && statementKinds.has(r.kind))?.t
+ ?? anchor('claim', 'end') ?? Infinity;
+ const publicationBegin = anchor('publication', 'begin') ?? Infinity;
+ const publicationEnd = anchor('publication', 'end') ?? Infinity;
+ const phaseOf = (record: TraceRecord): Phase => {
+ const text = flat(record.sql);
+ if (SCAN.some(pattern => pattern.test(text))) return 'consumer_scan';
+ if (/^SELECT state,error_code,error_message,completed_at,updated_at,blocked_reason,outcome FROM persistence_requests/.test(text)) return 'wait_poll';
+ if (/^UPDATE persistence_requests SET state='running'/.test(text) || /FOR UPDATE OF r SKIP LOCKED\) RETURNING/.test(text)) return 'claim';
+ if (/persistence_effects/.test(text) && record.t > publicationEnd) return 'effects';
+ if (record.t < admissionBegin) return 'admission';
+ if (record.t > claimEnd && record.t < publicationBegin) return 'prepare';
+ if (record.t > publicationEnd) return /^SELECT \* FROM persistence_requests WHERE id=\$1::uuid$/.test(text) ? 'completion' : 'effects';
+ return 'other';
+ };
+ const counts = new Map<string, { statements: number; describes: number }>();
+ const add = (phase: string, record: TraceRecord) => {
+ const entry = counts.get(phase) ?? { statements: 0, describes: 0 };
+ if (statementKinds.has(record.kind)) entry.statements++; else if (record.kind === 'describe') entry.describes++;
+ counts.set(phase, entry);
+ };
+ for (const group of labelled) {
+ // A transaction that starts after the publication commit and is not the completion belongs to post-commit effects.
+ const phase = group.phase === 'other' && group.begin > publicationEnd ? 'effects' : group.phase;
+ for (const record of group.records) add(phase, record);
+ }
+ for (const record of standalone) add(phaseOf(record), record);
+ const result: Record<string, { statements: number; describes: number }> = Object.fromEntries(counts);
+ result.critical_path = CRITICAL.reduce((sum, phase) => ({
+ statements: sum.statements + (counts.get(phase)?.statements ?? 0), describes: sum.describes + (counts.get(phase)?.describes ?? 0),
+ }), { statements: 0, describes: 0 });
+ return result;
+}
+
+const d = hasDatabase() ? describe : describe.skip;
+d('#6007 put_page statement budget (Postgres)', () => {
+ test('one remote put_page of a new 60 KB page stays within its per-phase statement budget', async () => {
+ const fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-statement-budget-'));
+ const trace = join(fixtureDir, 'trace.jsonl');
+ const root = join(fixtureDir, 'brain'); mkdirSync(root);
+ _resetWriteThroughCacheForTest();
+ await withEnv({ GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'statement-budget', GBRAIN_HOME: join(fixtureDir, 'home') }, async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine: PostgresEngine = pg.engine;
+ try {
+ await engine.setConfig('sync.repo_path', root);
+ await claimWorktree(engine, 'default', root);
+ const registration: LocalRegistration = await registerLocalWriter(engine, 'stdio', {
+ sourceIds: ['default'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'],
+ });
+ const dispatch = async (name: string, params: Record<string, unknown>) => {
+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params, {
+ remote: true, config: { engine: 'postgres', embedding_disabled: true }, sourceId: 'default',
+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] },
+ logger: { info() {}, warn() {}, error() {} },
+ }));
+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, unknown>;
+ };
+ const body = Array.from({ length: 600 }, (_, i) => `Paragraph ${i}: ${'measured canonical text '.repeat(4)}`).join('\n\n');
+ expect(Buffer.byteLength(body)).toBeGreaterThan(55_000);
+ const settle = async () => {
+ for (let i = 0; i < 200; i++) {
+ const [row] = await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_effects WHERE state IN ('queued','running')");
+ if (row!.n === 0) break;
+ await Bun.sleep(25);
+ }
+ await Bun.sleep(400);
+ };
+ const now = () => performance.timeOrigin + performance.now();
+ const measured: { put: Record<string, { statements: number; describes: number }>; receipt: { statements: number; describes: number } }[] = [];
+ const windows: { put: [number, number]; receipt: [number, number] }[] = [];
+ for (let i = 0; i < 5; i++) {
+ await settle();
+ const requestId = randomUUID();
+ const started = now();
+ const result = await dispatch('put_page', { slug: `notes/budget-${i}`, content: `---\ntitle: Budget ${i}\ntype: note\n---\n\n${body}`, request_id: requestId });
+ const finished = now();
+ expect(result.state).toBe('committed');
+ await settle();
+ const receiptStart = now();
+ const receipt = await dispatch('get_write_request', { request_id: requestId });
+ const receiptEnd = now();
+ expect(receipt.state).toBe('committed');
+ windows.push({ put: [started, finished], receipt: [receiptStart, receiptEnd] });
+ }
+ await Bun.sleep(1300);
+ const records = readFileSync(trace, 'utf8').trim().split('\n').map(line => JSON.parse(line) as TraceRecord);
+ // The first two writes warm the pool's prepared statements; the last three are measured.
+ for (const window of windows.slice(2)) {
+ const inWindow = (range: [number, number]) => records.filter(r => r.t >= range[0] && r.t <= range[1]);
+ const receiptRecords = inWindow(window.receipt).filter(r => r.kind !== 'connect' && !SCAN.some(p => p.test(flat(r.sql))) && !/persistence_effects e/.test(r.sql));
+ measured.push({ put: classify(inWindow(window.put)), receipt: {
+ statements: receiptRecords.filter(r => statementKinds.has(r.kind)).length, describes: receiptRecords.filter(r => r.kind === 'describe').length } });
+ }
+ console.log(`[statement-budget] ${JSON.stringify(measured.map(m => ({ ...Object.fromEntries(Object.entries(m.put).map(([k, v]) => [k, `${v.statements}+${v.describes}d`])), receipt: `${m.receipt.statements}+${m.receipt.describes}d` })))}`);
+ for (const m of measured) {
+ for (const [phase, budget] of Object.entries(BUDGET)) {
+ const value = phase === 'receipt' ? m.receipt.statements : m.put[phase]?.statements ?? 0;
+ expect({ phase, statements: value }).toEqual({ phase, statements: Math.min(value, budget) });
+ }
+ }
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await pg.close();
+ }
+ });
+ rmSync(fixtureDir, { recursive: true, force: true });
+ }, 120_000);
+});
diff --cc test/fixtures/goldens/cli/tools-json.json
index fdfad2b7bd,e60ce55bb7..3c6f861c73
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@@ -2,8 -2,8 +2,8 @@@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 201277,
- "stdoutSha256": "e8bcc29a6c49a893186e6ec00819734105c0e89eb9c6521e87496e9ff7952c34",
- "stdoutBytes": 199133,
- "stdoutSha256": "b42f35c3d886837625a537154830f9938b921618548b83498e4d8df0285c868c",
++ "stdoutBytes": 201809,
++ "stdoutSha256": "4c55031c6c5cafb895a97fbdfd92034de6e9ce7accc89ade34dd049fb031c0ec",
"toolNames": [
"remember",
"entity",
@@@ -827,72 -821,7 +827,72 @@@
"scope": "write"
},
{
- "description": "Read the receipt of your write by request_id (after write_pending or a lost reply).",
+ "description": "Write up to 50 complete Markdown pages (8 MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id UUID per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned `next`. Needs put_page permission.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
+ "name": "put_pages",
+ "parameters": {
+ "pages": "array?",
+ "request_id": "string",
+ "source_id": "string?",
+ "wait_ms": "number?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "pages": {
+ "description": "1-50 pages; omit to read the batch status.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "allow_empty": {
+ "description": "Allow emptying a non-empty page.",
+ "type": "boolean"
+ },
+ "content": {
+ "description": "Complete markdown with frontmatter.",
+ "type": "string"
+ },
+ "expected_revision": {
+ "description": "Revision read; omit to create.",
+ "type": "string"
+ },
+ "slug": {
+ "description": "Page slug.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "slug",
+ "content"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "request_id": {
+ "description": "Batch UUID; reuse it to replay or poll.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Write source.",
+ "type": "string"
+ },
+ "wait_ms": {
+ "description": "Hold the reply up to this many ms (0-30000, from arrival) for commits. Default 25000. Not part of the write.",
+ "type": "number"
+ }
+ },
+ "required": [
+ "request_id"
+ ],
+ "type": "object"
+ },
+ "scope": "write"
+ },
+ {
- "description": "Read your write's receipt by request_id (after write_pending or a lost reply). Poll at retry_after_ms until it is final.",
++ "description": "Read your write's receipt by request_id (after write_pending or a lost reply). Poll at retry_after_ms until final.",
"idempotent": true,
"local_only": false,
"mutating": false,
diff --cc test/mcp-schema-budget.test.ts
index c7fc353057,f1b31d27e8..4ae7cee38e
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@@ -44,10 -40,10 +44,10 @@@ import { cl100kAvailable, estimateToken
const SERVED_STARTER_MAX_CHARS = 25_000;
const SERVED_STARTER_MAX_TOKENS = 5_700;
- /** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; 26,178 with #6007's put_page wait_ms param and write guidance on top of master's v0.60.57.0 get_backlinks growth). */
-/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured). */
-const SERVED_STARTER_MAX_JSON_CHARS = 26_000;
++/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,172 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need). */
+const SERVED_STARTER_MAX_JSON_CHARS = 26_200;
/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */
-const INSTRUCTIONS_MAX_CHARS = 4_628;
+const INSTRUCTIONS_MAX_CHARS = 4_868; // #6007: +240 for the issue-required write guidance (put_pages, wait_ms)
const DESCRIPTION_HARD_CAP = 1_200;
const PARAM_DESCRIPTION_HARD_CAP = 200;