Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge PR 4 lane E (embed once per content version) into capy/wave-b-pr4

garrytan54c1881011f5
diff --cc docs/architecture/key-files/providers.md
index aec9a3f82e,1d76f6106b..e49198acfa
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@@ -26,7 -26,7 +26,8 @@@ Current behavior and load-bearing invar
- `src/core/embedding-state.ts` — #6696 B3 derived embedding state: every chunk, and every live page with no chunk row, in one of `embedded | pending | keyword_only | quarantined | empty | deleted_page_chunks | chunkless_healable` against the ACTIVE embedding column (no stored status). The classifier SQL lives once in `engine-sql/chunks.ts` (`chunkEmbeddingState` reuses `staleChunkWhere`, `chunklessPageState` reuses `chunklessPagesWhere`) behind `BrainEngine.readEmbeddingStateCounts` / `listEmbeddingStateRows`. `readEmbeddingState(engine, { mode, sourceIds })`: `full` is exact; `ops` reads only index-backed counts (the partial index `WHERE <active column> IS NULL`, the frontmatter GIN, the purge index; `embedded` is a planner estimate) and is `status: 'unknown', reason: 'no_covering_index'` without that index, never a scan. `unsearchable` sums pending, quarantined, empty and chunkless_healable (pending drops out on a brain keyless by choice). `embeddingStateFix` builds each state's protocol fix from existing commands. Consumers: doctor `embedding_state`, `gbrain pages unsearchable`, lane B's `get_brain_health`. Tests: `test/embedding-state.test.ts`.
- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`. Wave B: a segmented page is embedded by `page-body/segmented-embedding.ts` (vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here, `gbrain embed` and the post-commit embedding effect (`data.occurrence_ids` limits an append's effect to the new occurrences).
+- `src/core/content-drift-sweep.ts` — the content-drift sweep (#4246) as a resumable pass: `runContentDriftSweep(engine, { sourceId?, signal?, deadline?, stopped?, assertOwned?, timeBudgetMs?, batchRows? })` runs `engine-sql/chunks.ts` `invalidateContentDriftBatch` (5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config row `embed.content_drift_sweep.<column>.<all|source:id>` with the batch under a `FOR UPDATE` lock on that row, so concurrent runs share one pass. A run stops at its 60 s budget, the job deadline or an abort; a completed pass restarts after `embed.content_drift.pass_interval_hours` (default 24) unless it fit in one batch. A failed batch is returned as `state: 'failed'` with the error and recorded as `last_error` (cleared by the next committed batch); a missing v133/v221 column is `unsupported`; an `assertOwned` throw propagates. `embedAllStale` (`EmbedResult.content_drift`), `embedStaleForSource` (`contentDrift`) and the embed, embed-backfill and cycle embed results carry the status; doctor `content_drift_sweep` reads the saved rows.
+ - `src/core/page-embedding-lease.ts` — one provider call per chunk content version (gbrain-evals#180, N14). Every path that embeds a page's vector-less chunks holds the page's embedding lease from reading which chunks lack a vector through its install: the post-write embedding effect (`persistence/effects.ts`, inline and segmented), the `gbrain embed --stale` drain (`src/commands/embed.ts`), `embedStaleForSource` and `embedStalePages` (`embed-stale.ts`), and every segmented install (`embedSegmentedRows` in `page-body/segmented-embedding.ts`). `acquirePageEmbeddingLease` takes a `gbrain_cycle_locks` row `embed-page:<page id>` with plain statements (TTL 2 minutes, refreshed every 30 s while held, no process-liveness takeover), waiting with backoff while another path holds it; an effect renews its claim in `whileWaiting`. Callers bind it with `await using`, so leaving the scope releases it. The holder then keeps only the chunks still without a vector (inline: `stillPendingChunks` over the fresh `getChunks` read; segmented: `vectorlessChunkIndexes`), so a drain whose listing predates an effect's install sends nothing for them. `pageEmbeddingLeaseProbe.contended` is the test seam. Forced probes (effect first on a segmented page after `append_page`, drain first on an inline page; both engines): `test/embed-once-per-content-version.serial.test.ts`.
- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete: an unsealed page only in the `reimport` class (`page-state/projection-class.ts`; `sealable`, `protected` and `archived` are counted, never candidates), a sealed one with no `embedding_image` chunk or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true` (`incomplete_sealed`); `ocr_required` counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root; a page with no recorded `source_path` is located by its slug, which is the lower-cased repo-relative path, and counted in `missingSourcePath`) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes through `importManagedFile` (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records `source_path`. Reports candidates, rebuilt, unchanged, missing source files (`missing_samples`: up to 5 `source:slug: no file at <path tried>` lines, the first printed) and failures; the explicit `--images` CLI (`runEmbedStaleImagesCli`) counts an all-missing, nothing-rebuilt sweep as failures (`sweepFoundNoFiles`), so it never exits 0 as a quiet success. `runStaleImageSweepFirst` is the sweep a plain `gbrain embed --stale` (no `--slugs`) runs before its text drain when multimodal embedding is on, and `foldImageSweep` folds it into the `EmbedResult` as `images`: import failures count toward the run's failures, fileless pages are reported once on stderr (`missingFile`, first sample) and leave the exit code to the text run; a text-only install skips it and keeps the `--images` hint. Pinned by `test/embed-stale-images.test.ts` and `test/embed-stale-images-managed-6529.test.ts` (both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.
- `src/core/embed-budget-stop.ts` — the loud time-budget stop for `gbrain embed --stale`. `noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})` counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, sets `reason: 'time_budget'`, `remaining_stale` and `resume_command` (`gbrain embed --stale --catch-up [--source X] [--include-null-signature]`) on the result; `skip` covers dry runs, `--catch-up` and caller aborts. `embedBudgetStopVerdict(result)` is the stdout verdict `runEmbed` prints; `src/cli/commands/embed.ts` maps the reason to `BUDGET_STOP_EXIT_CODE` (failures still win with 1). Called from every budget exit in `embedAllStale` (readiness-phase deadline returns and the main drain). Pinned by `test/embed.serial.test.ts` ("time-budget stop is loud").
diff --cc src/core/behavior-change-notice.ts
index f3dbaeb083,6e69d424ea..c258f36341
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -1019,9 -1019,8 +1019,11 @@@ export const BEHAVIOR_CHANGES: Readonly
// #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.
{ since: '0.60.326.0', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },
{ since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },
+ // #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.
+ { since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },
+ { since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },
+ // PR 4 E (one provider call per chunk content version, gbrain-evals#180). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A page\'s new chunks now go to the embedding provider once per content version. The post-write embedding effect, `gbrain embed --stale`, the embed-backfill job and phase-end embeds each hold a per-page lease (a `gbrain_cycle_locks` row named `embed-page:<page id>`, refreshed while held, expiring within 2 minutes after a holder dies) from reading which chunks lack a vector through installing them; a path that reaches a page another path is embedding waits for it, then embeds only the chunks still missing a vector. Before, a stale drain that ran while a write\'s embedding effect was in flight sent the same chunks twice (paid twice on a paid provider). Live `embed-page:` rows can show in the `gbrain status` lock list while an embed runs.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --cc src/core/embed-stale.ts
index 57ba9947b3,c51621d1b3..38176b38d4
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@@ -34,8 -34,8 +34,9 @@@ import
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
import { resolveStaleEmbedConcurrency } from './embed-concurrency.ts';
import { AbortError } from './abort-check.ts';
+import { contentDriftSweepLine, runContentDriftSweep, type ContentDriftSweepStatus } from './content-drift-sweep.ts';
import { meterPageBatch, spendGrant } from './page-embedding-budget.ts';
+ import { acquirePageEmbeddingLease, stillPendingChunks } from './page-embedding-lease.ts';
import { chunkGenerationFilter, chunkVisibleFilter } from './search/safe-chunks.ts';
import { embedSegmentedPage, embedSegmentedRows, readSegmentedEmbedPage, type SegmentedEmbedOpts } from './page-body/segmented-embedding.ts';