Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(release): wave 9 follow-ups CHANGELOG entry, BEHAVIOR_CHANGES rows; key-files split and function-size baseline after the master merge

garrytand4571b91a820
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12f0dbf4d2..949951ec26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,62 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.107.0] - 2026-10-07
+
+**Wave 9 follow-ups: managed brains get receipts for every fact and take they write, old "Date:" facts can be cleaned up for free, and a handful of quiet overwrites and false "done" reports stop.**
+
+Every fresh `gbrain init` brain is managed: each write is supposed to carry a receipt saying who wrote it and when. Facts pulled from meeting notes and transcripts, facts absorbed from a fence during sync, and several takes paths skipped that receipt, and on managed brains email-thread facts were simply switched off. They all write through receipts now, batched so a big brain doesn't burn through its writer's limits. Facts an older parser credited to a "Date" or "Attendees" speaker can be previewed and retired without any model call. A removed take's number is never handed to a new take, a concept you edit by hand mid-cycle is no longer overwritten, `takes rebuild` works while `gbrain serve` is running, and eval judges on Gemini and GPT finally turn thinking off where the model allows it.
+
+### How to use it
+
+```bash
+gbrain extract-conversation-facts --source-id <id> --dry-run # preview what a managed run would extract
+gbrain repair conversation-labels --source <id> # preview label-misattributed facts (no model calls)
+gbrain repair conversation-labels --source <id> --apply --expect <hash> --yes
+gbrain extract-conversation-facts --slugs <a,b> --dry-run # exactly the named pages
+gbrain takes rebuild <slug> # now also while gbrain serve owns a PGLite brain
+gbrain doctor --only conversation_label_facts,conversation_outcomes_stale
+```
+
+### What you see
+
+| Where | What changed |
+|---|---|
+| Conversation facts on managed brains | Meetings, transcripts and email threads are extracted and published in receipted batches: up to 25 pages per request, at most 10 of them with facts, at most 8 MiB. A crash after the batch was accepted replays it on the next run with no model call; a page that changed meanwhile is skipped and retried; a page that keeps failing is blocked until it changes. Single emails, prose notes and undated pages are recorded as not extractable for good instead of rescanned every run. |
+| Writer capacity | A managed extraction stops with `maintenance_backpressure` (exit 12) before the writer passes 80% of its outstanding requests, reserved receipt bytes or permanent request ids, and names a `--limit` that fits. On a 50,000-page brain a full backfill uses about 1.5% of the writer's lifetime request ids. |
+| Fence facts, takes and supersession on managed brains | The cycle's `## Facts` reconcile and its deleted-page expiry, `gbrain extract takes --source db`, `gbrain takes rebuild` and `gbrain repair take-supersession` publish receipted requests. A page already in sync writes nothing. |
+| `gbrain repair conversation-labels` | New, explicit-only. Lists facts the parser before v0.60.74 took from `**Date:**`, `**Attendees:**` and similar labels, by class with a hash; `--apply` expires them (kept in history), records prose pages as not extractable and prints the capped re-extract commands for the rest. Facts dated 1970-01-01 are the default set; the rest sit behind `--include-ambiguous`. It never runs from `repair --all`, doctor remediation or an upgrade. |
+| Doctor | `conversation_label_facts` counts what the repair would retire; `conversation_outcomes_stale` counts pages last processed by an older extractor version (nothing reruns on its own). |
+| Take numbers | `gbrain takes remove` leaves a struck `(removed)` placeholder row, and every new take number comes from one page-wide allocator, so `slug#N` links never start pointing at a different claim. |
+| Concepts (unmanaged brains) | A dream-cycle concept whose file holds an edit the database hasn't imported yet is deferred (`revision_conflict`) and published after sync imports it; a failed file write holds the concept instead of reporting success. |
+| Worker shutdown | An `UnrecoverableError` thrown while a worker shuts down dead-letters with its own message instead of being re-queued for another (possibly paid) run; other errors are still handed back, now keeping the handler's message. |
+| `gbrain jobs supervisor stop` | A recycled worker pid no longer reads as still running, a run that crossed the weekly audit boundary no longer reports a false `drained`, a run with no `started` record reports `unverified`, and a stale PID file whose pid now belongs to another process is never signaled (`stale_pid_file`). |
+| `gbrain takes rebuild` | Works while `gbrain serve` owns a PGLite brain (it used to hang on the lock); same JSON and exit codes as a local rebuild. |
+| Eval judges | With `thinking: off`, Gemini 2.5 Flash sends `thinkingBudget: 0` and GPT-5.1+ sends `reasoningEffort: none`. Models that can't turn reasoning off (Gemini 2.5 Pro and 3.x, gpt-5/-mini/-nano, o-series, gpt-6) run at their lowest setting with a 32,000-token reply cap, and the takes-quality and cross-modal preflights price that cap instead of underestimating it 8-16x. |
+
+### Things to watch
+
+- **Managed brains now extract email threads.** Nothing runs on its own: the backfill stays opt-in (`cycle.conversation_facts_backfill`) and spend stays under `--max-cost-usd` (default $5) and the backfill's $1 per run / $5 total caps. A two-message thread is one segment, about $0.006 on Haiku 4.5.
+- **Managed extraction needs the source's owner on this host** once a page actually needs work; the backfill phase skips a managed source another host owns and says so in its summary.
+- **Take numbering is page-wide:** the first take on a page whose facts fence holds rows 1-5 is #6. Existing rows are never renumbered.
+- **Scripts:** a shutdown hand-back's `error_text` is `worker_shutdown: <message>` (match the prefix); the supervisor PID file has a second line on Linux (read the first); judge budgets that passed before can refuse earlier.
+- **Not fixed here:** stall detection for subagent turns, receipts for the pages/timeline/alias derived writers, production fail-closed receipt enforcement, and the judge-panel refresh. See TODOS.md.
+
+### Itemized changes
+
+- `src/core/facts/conversation-publication.ts`: `managed_maintenance_conversation_facts` batch requests with per-page generation identity, replay of accepted batches, resubmission of failed ones from their stored entries, blocking after a deterministic failure or three failed batches; outcome rows stay private under `facts.default_visibility=world`; the run's preflight, embedding signature, capacity check and batch index resolve at its first page with managed work. The `replaceDerivedFactsForPage` managed path is gone.
+- `maintenance_backpressure` (exit 12) also guards reserved receipt bytes and permanent request ids; the up-front check counts the run's planned batches.
+- `src/core/cycle/extract-facts.ts`: `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire`; `src/core/cycle/extract-takes.ts`: `managed_maintenance_takes_reextract`; `src/core/repair/take-supersession.ts`: `managed_maintenance_take_reproject`.
+- `test/receipt-coverage.test.ts` lists every coordinated write site with its receipt status; the managed-connector contract harness refuses an unreceipted facts or takes write.
+- Conversation outcome rows record `extractor_version=<n>`. A conversation page whose completion marker was expired is extracted again; re-extraction keeps facts an open loop or a superseding fact references, as expired history.
+- `src/core/repair/conversation-labels.ts` (`managed_maintenance_conversation_label_retire`, batches of 25 pages), with the CLI write wait on a replayed batch.
+- `conversation_facts_backfill` reports a managed source this host doesn't own as skipped (`sources_skipped_not_owner`), not failed.
+- `nextFreeRowNum` for every new take row; `takes remove` writes the reservation row.
+- `publishClassicConcept` rechecks the file under the lock and writes with `expectedFileBytes`; `concept_write_through_failed`.
+- Worker shutdown error matrix; supervisor stop pairs exits with spawns by pid and kernel start time.
+- `takes_rebuild` is a local-only operation delegated to the resident owner.
+- `src/core/ai/thinking-off.ts`: a per-model thinking capability table that `chat()`, the judge estimates and the fence-repair model tier all read.
+
## [0.60.106.0] - 2026-10-07
**Fix wave 12: one bad link no longer stops extraction, cut-off model answers stop counting as real ones, and paid loops stop paying.**
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 3c80b423a1..ccd9db8e05 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -30,7 +30,7 @@ boundary and add its link here rather than raising the cap.
| [Agent operator contract](key-files/agent-contract.md) | `agent-output.ts`, error registry + docs, notice ledger, `isCallable`, `--json` guard, contract scanner |
| [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` |
| [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` and `src/commands/doctor/` |
-| [Commands (2/6, continued)](key-files/commands-2-continued.md) | `src/commands/dream-retriage.ts` through `src/commands/embed.ts` |
+| [Commands (2/6, continued)](key-files/commands-2-continued.md) | `doctor/checks/routing-federation.ts`, `dream-retriage.ts` through `embed.ts` |
| [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `src/commands/frontmatter-install-hook.ts` |
| [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `src/commands/pglite-repair.ts` |
| [Commands (4/6, continued)](key-files/commands-4-continued.md) | `src/commands/protocol.ts` through `src/commands/reindex-search-vector.ts`, `init-mode-picker.ts`, `src/core/embedding-migration-cli.ts` |
@@ -43,7 +43,7 @@ boundary and add its link here rather than raising the cap.
| [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/rss-default.ts` |
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
-| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `src/core/persistence/connector-*.ts`, `src/core/connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, database-write, attribution, purge-deleted and loop-fact retirement |
+| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `src/core/persistence/connector-*.ts`, `src/core/connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, database-write, attribution, purge-deleted and loop-fact retirement |
| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, the graduation doctor finding |
| [Managed sync and persistence stalls (key files cluster)](key-files/persistence-stalls.md) | `claim-phase.ts`, `pre-activation-release.ts`, `sync-concurrent-write.ts`, `worktree-manifest.ts`, `src/core/hardened-git.ts` |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 3ca3008143..75457a93cd 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -3,6 +3,8 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-2.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.
+
- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) through `requireConsent` (effect `paid`; `--yes`, `--max-usd`, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, `--json` never implying it); the budget (`--max-usd`, else the derived consent cap) soft-stops via the pass's `shouldStop` seam (estimate-based) and bounds the `--audit-rejects` half. `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).
- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter. Its help names the per-source patterns key `dream:patterns:source:<id>`; doctor `dream_paid_loop` reports that prefix as the key's `key_prefix`.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 482fdc2190..6047684ecc 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -53,5 +53,3 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/home-worktree.ts` — the `home_dir_in_worktree` check: walks up from the gbrain home looking for an enclosing `.git` (dir or linked-worktree file), warning that a `git add` from the worktree root could stage the brain; stops at $HOME. Both anchors (`GBRAIN_HOME`, `$HOME`) are `path.resolve()`d before the containment test, so a trailing-slash `HOME=/home/user/` (a common shell/launchd spelling) cannot make a brain inside a worktree grade ok. `isValidGitMarker` structurally validates a candidate before it counts (a `.git/` dir must contain HEAD; a `.git` file must start with `gitdir:` — git itself rejects anything else), and invalid candidates CONTINUE the walk so a valid repo higher up still warns. Cheap (stat + read, no subprocess) — runs on every doctor invocation including `--fast`.
- `src/commands/doctor/checks/integrations-memorable.ts` — `memorable_relay_health` (OPS category), the doctor surface for the optional third-party relay. Engine-free (file-plane reads only), pushed unconditionally so it survives `--fast`/`--scope`. Rung 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 failed → warn with the CLAMPED cause (the shared `clampRelayCause`; child text never lands in a doctor message verbatim) — EXCEPT the documented openclaw `no_decisive_steps` rejection, which becomes an ok-with-note (`expected_openclaw_rejection`, name-only capture refused until argument capture lands) held as a DEFERRED note that surfaces only after the codex rung below passes: on a mixed openclaw+codex host the rejection is the persistent last-relay state, and an early return would paint the check green while a trust-stale codex hook sits silently dead; receipts written but the child never reported → warn; codex hooks wired but no codex-harness receipt in the recent receipt window (tail-200 read) → warn (`codex_hooks_never_fired` — codex hooks fail silently on a stale trust entry); healthy → ok with structured details (`out_of_band_settable: true` always rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned by `test/doctor-memorable.test.ts`.
-
-- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index a801a85976..5fd0c39b78 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -4,6 +4,8 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Managed connector ingestion, connector item holds, sync checkpoint validation and the no-op kernel. Also the persistence verb types and errors, database-write and manual links, write attribution, purge-deleted and loop-fact retirement.
+- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.
+
- `src/core/fence-repair/refusal.ts` — #6188 the one fence check coordinated writers share. `scanCanonicalFences` decides from the strict parsers what the canonical projection refuses (a repeated marker outside code, any parser warning, a row number used twice on the page) and locates each defect from the raw-row view (`raw-rows.ts`, `schema.ts`), never from parser warning strings, which embed row text; reasons and messages come from `reasons.ts` (`FENCE_REASONS`, `fenceMessage`, `issueLocation`). `fenceOperationError` is the typed refusal (`invalid_fence`, wire `invalid_params`, or `take_row_collision` for a stored-row collision). `fenceFailureDetail` is the bounded, versioned `error_detail.fence` a failed receipt keeps through compaction; `fenceReceiptLocation` reads a receipt back from that detail, the message grammar or an older release's exact message, and never from an arbitrary `invalid_params`. `completeFenceLocation` names the section of a legacy receipt from the refused bytes. Tests: `test/fence-refusal.test.ts`, `test/fence-hold-surfaces.test.ts`, `test/persistence-sync-fence-holds.test.ts` (PGLite and Postgres).
- `src/core/fence-repair/{types,schema,raw-rows,reasons}.ts` — #6188 the shared fence vocabulary, all location-only. `types.ts`: `FenceIssue`, `FenceFix`, `FenceCtx`, `FenceReason`, `FixClass`. `schema.ts`: canonical columns, accepted widths (facts 9/10/14, takes 6/7/13), header aliases, enum and kind synonym tables (exported for the format reference), cell validity. `raw-rows.ts`: `extractRawRows` reads each fence leniently (markers outside code, header map or positional fallback, cells with source spans, a row's identity is its ordinal); a row is `accepted` exactly when the strict parser returns it. `reasons.ts`: `FENCE_REASONS` (tier, auto-retry, actor, fix template, docs anchor per reason; the registry's `invalid_fence.reasons`; templates a repair can clear name the read-only `gbrain repair fences` preview) and `fenceMessage`. Tests: `test/fence-repair-raw-rows.test.ts`, `test/fence-repair-reasons.test.ts`.
- `scripts/build-fence-format.ts` — #6188 renders the generated region of `docs/guides/fence-format.md` (between `BEGIN/END GENERATED fence-format`) from the fence constants: markers, the column tables and layouts from `schema.ts` (`COLUMNS`, `BASE_WIDTH`, `MIN_CELLS`, `CANONICAL_HEADER`, `ALLOWED`, `COLUMN_DEFAULTS`, `NAMED_COLUMNS`, `TOLERATED_TRAILING`, `HEADER_ALIASES`), holder outcomes computed with `isValidHolder`/`holderAlias`, the Tier 1 rule table from the synonym tables (bound to `FixClass` by `satisfies`), screen reasons grouped by tier and the gate table from `reasons.ts`. It parses both synthetic examples with the strict parsers and throws on any warning. `--check` exits 1 when the committed region is stale. Drift test: `test/fence-format-reference.test.ts` (the region, the examples, the reference's links, and one `fence-<reason>` row per reason in `write-refusals.md` with the reason table's tier and auto-retry and a link into the reference).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d0e3949a21..15e16066ab 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -60,5 +60,3 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres. #6099: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).
-
-- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index e53fc4debb..1fc8e31fe3 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -32,7 +32,7 @@ src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refa
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6195: multi-word weak n-gram norms and the weak-title arm call (logic in weakTitleHits)
src/core/cycle.ts runCycle 1279 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts); +2 fix wave 12 #6242: lease-set result and the maintenance-busy skip call (logic in skipBrainWidePhases and cycle/lock-set.ts)
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallback
-src/core/cycle/extract-facts.ts runExtractFacts 376 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer
+src/core/cycle/extract-facts.ts runExtractFacts 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/patterns.ts runPhasePatterns 310 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6177: budget sizing call, submitted-reflection slice and the last_run record (logic in cycle/patterns-plan.ts)
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1b6acaf91c..3fbccffa63 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -303,6 +303,13 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.106.0', text: 'A `gbrain dream` scoped to a source, including a bare `gbrain dream` on the default source, now also takes the brain-wide `gbrain-cycle` lease for synthesize, patterns, embed and the other brain-wide phases: while autopilot maintenance holds it, those phases are skipped as `maintenance_lock_busy` and the source phases still run, and autopilot maintenance skips its window while a dream holds it. `gbrain status --section locks --json` shows the holder.' },
{ since: '0.60.106.0', text: '`gbrain onboard --auto` (including cron runs), `doctor --remediate` and MCP `run_onboard` never submit a manual-only step: the schema-pack upgrade (`unify-types`) and the paid takes bootstrap (`extract-takes-from-pages`) are listed under `manual_only_skipped` with the command to run them yourself. A job of either kind an earlier run already queued still runs: find it with `gbrain jobs list --status waiting` and cancel it with `gbrain jobs cancel <id>` if you did not want it.' },
{ since: '0.60.106.0', text: '`gbrain reindex --markdown` asks before re-embedding (paid): without a terminal it exits 3 with an ask_user payload naming the page count, the estimate and the `--yes` command; `--yes` or `--max-usd <usd>` approves it, and `--dry-run`, `--no-embed` and a keyless brain never ask. A queued `reindex` job re-embeds only with the approval stored at submit time (`gbrain jobs submit reindex ... --yes`, or the search-mode switch prompt); one queued without it fails with `confirmation_required`.' },
+ { since: '0.60.107.0', text: 'Managed brains now extract conversation facts from meetings, transcripts and email threads through receipted batch requests (up to 25 pages each), and record single emails, prose notes and undated pages as not extractable for good. Nothing runs on its own: preview with `gbrain extract-conversation-facts --source-id <id> --dry-run`. A run stops with `maintenance_backpressure` (exit 12) before the writer passes 80% of its request or receipt capacity; `gbrain sources writer status --json` shows it.' },
+ { since: '0.60.107.0', text: 'Re-extracting a conversation page now keeps facts that an open loop or a superseding fact references, as expired history, instead of deleting them.' },
+ { since: '0.60.107.0', text: 'Take numbers are never reused: `gbrain takes remove` leaves a struck `(removed)` row in the page, and a new take gets one more than every facts or takes row number on the page, so the first take on a page whose facts fence holds rows 1-5 is #6. Deleting the placeholder by hand frees its number again.' },
+ { since: '0.60.107.0', text: 'On an unmanaged brain a dream-cycle concept whose file holds an edit the database has not imported is deferred (`revision_conflict`) and published after sync imports it, instead of being overwritten.' },
+ { since: '0.60.107.0', text: 'A job error during worker shutdown now records `worker_shutdown: <handler error>` instead of bare `worker_shutdown`, and an `UnrecoverableError` thrown then dead-letters at once instead of running again.' },
+ { since: '0.60.107.0', text: '`gbrain jobs supervisor stop` can now report `unverified` (exit 1) and `stale_pid_file` (exit 0, nothing signaled), and on Linux the supervisor PID file has a second line with the process start time; read only its first line.' },
+ { since: '0.60.107.0', text: '`thinking: off` calls on native Google and OpenAI routes (eval judges, the synthesize triage judge, fence repair\'s model tier) now send the model\'s thinking switch (`thinkingBudget: 0`, `reasoningEffort: none`) and, where reasoning cannot be turned off (Gemini 2.5 Pro and 3.x, gpt-5/-mini/-nano, o-series, gpt-6), a 32,000-token reply cap; `eval takes-quality --budget-usd` and `eval cross-modal --max-usd` price that cap, so a budget that passed before can refuse earlier.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 71cfbd5e16..8f252fcff8 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -350,9 +350,7 @@ export async function runPhaseConversationFactsBackfill(
// downgrading it to a per-source failure record.
throw err;
} else if (err instanceof OperationError && err.code === 'owner_unavailable') {
- // Managed source owned by another host (or not activated here): its extraction publishes only on its owner,
- // like the fence_repair phase's skip. Reported, not counted as a failure.
- sourcesNotOwned.push(src.id);
+ sourcesNotOwned.push(src.id); // its owner host extracts it (as fence_repair skips); reported, not a failure
perSourceResults[src.id] = zeroResult();
} else {
// Per-source failure: record + continue with next source.
@@ -428,8 +426,7 @@ export async function runPhaseConversationFactsBackfill(
const noPricing = [...new Map(Object.values(perSourceResults)
.flatMap((r) => r.budget_pricing ? [[r.budget_pricing.model, r.budget_pricing] as const] : [])).values()];
const summary = `${totals.facts_inserted} facts inserted across ${totals.sources_processed}/${sources.length} sources, ~$${totalSpent.toFixed(4)} spent` +
- noPricing.map((g) => `. ${noPricingMessage(g)}`).join('') +
- (sourcesNotOwned.length ? `. Skipped ${sourcesNotOwned.length} managed source(s) this host does not own (${sourcesNotOwned.join(', ')}); run the phase on their owner host` : '');
+ noPricing.map((g) => `. ${noPricingMessage(g)}`).join('') + notOwnedNote(sourcesNotOwned);
return {
phase: 'conversation_facts_backfill',
@@ -471,3 +468,7 @@ export async function runPhaseConversationFactsBackfill(
},
};
}
+
+function notOwnedNote(ids: string[]): string {
+ return ids.length ? `. Skipped ${ids.length} managed source(s) this host does not own (${ids.join(', ')}); run the phase on their owner host` : '';
+}