Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(reindex): managed brains re-chunk through the projection repairs (#5377, C-NEW-5)
time-attack10272c3b01cb
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 76fde9f524..b935a5fd35 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`). Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.-- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.+- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.diff --git a/docs/wave9/sg.md b/docs/wave9/sg.mdindex 2ae2bb6c64..986506eb09 100644--- a/docs/wave9/sg.md+++ b/docs/wave9/sg.md@@ -10,6 +10,7 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md- **Bundled-size skill packs adopt in one publication (#5476, A-NEW-4).** One canonical adoption may now write up to 128 files (one SKILL.md per skill plus skillpack.json, the persistence bundle bound) instead of 64, so the 75-skill bundled set adopts. A pack declaring 128 or more skills is refused at inventory as an action instead of failing after it. When skill files change after inventory, the conflict lists the changed paths and an exact `gbrain apply-migrations --migration 0.53.0 --accept-reviewed-inventory <source>=<digest> --yes` acceptance command.- **Portable canonical skills list their usable tools (#5150).** A shared skill published without `tools:` now inherits the caller's available brain tools as `usable_tools` (list, detail, and the v1 compatibility catalog), matching host-repository skills; `tools: []` still permits none. Revisions published before this release re-read their SKILL.md on `get_skill`; `list_skills` keeps them empty until republished.- **`put_skill` refuses an empty SKILL.md (A-NEW-5).** An empty or whitespace-only entry point is `invalid_params` instead of publishing a blank skill.+- **`gbrain reindex --markdown` works on managed brains (#5377, C-NEW-5).** It used to fail every page with "cannot mutate a managed brain through the legacy writer", while doctor, upgrade and post-upgrade kept prescribing it. On a managed brain it now runs the projection repairs (`gbrain repair safe-chunks`, then `contextual-mode` unless `--no-embed`): no page revision, journal request or canonical file changes. `--type` is refused on managed brains with the repair commands.## Upgrade-note rows@@ -21,3 +22,4 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md| 0.53.0 migration: re-inventory, 128-file pack adoption, reviewed acceptance (#5476) | Brains adopting shared skills with >63 skills or edited packs | `gbrain apply-migrations --migration 0.53.0 --dry-run --json` shows per-source stages | Don't pass `--accept-reviewed-inventory`; the conflict stays until reviewed || Canonical skills without `tools:` inherit brain tools (#5150) | Clients reading `usable_tools` for shared skills | `gbrain call get_skill '{"name":"<skill>"}'` | Declare `tools:` in the skill to narrow it || Empty SKILL.md refused (A-NEW-5) | Editors publishing placeholder skills | none | Write a non-empty SKILL.md |+| Managed `reindex --markdown` delegates to projection repairs (#5377) | Managed brains with chunker or contextual-mode drift | doctor calibration hint (`gbrain reindex --markdown`) now works | Run `gbrain repair safe-chunks` / `contextual-mode` directly for per-kind control |diff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex aae3ef7895..1de7bacc99 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -34,6 +34,8 @@ import { resolve } from 'path';import { runSlidingPool } from '../core/worker-pool.ts';import { resolveWorkersWithClamp } from '../core/sync-concurrency.ts';import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { loadConfig } from '../core/config.ts';interface ReindexOpts {/** Cap total pages reindexed. Useful for triage runs on huge brains. */@@ -89,7 +91,10 @@ USAGETARGETS (exactly one required)--markdown Re-chunk markdown pages whose chunker_version lags thecurrent chunker (or whose contextual-retrieval state is- unset when embedding is on).+ unset when embedding is on). On a managed brain it+ runs gbrain repair safe-chunks (and contextual-mode+ unless --no-embed) instead: no page writes; --type is+ refused there.--multimodal Re-embed image/PDF chunks through the multimodalembedding pipeline (Voyage batches).--aliases Backfill the free-text alias layer (page_aliases) for@@ -365,6 +370,8 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<Rreturn { pending, pendingAfter: pending, reindexed: 0, skipped: 0, failed: 0, dryRun: true, chunkerVersion: MARKDOWN_CHUNKER_VERSION, type };}+ if (await managedPersistenceEnabled(engine)) return reindexManaged(engine, opts, type, pending);+const reporter = createProgress(cliOptsToProgressOptions(getCliOptions()));reporter.start('reindex.markdown', target);@@ -494,3 +501,52 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<Rreturn result;}++/**+ * #5377: a managed brain cannot re-import through the legacy writer, so the+ * sweep delegates to the projection repairs: `safe-chunks` re-seals every page+ * chunked before the current chunker and `contextual-mode` stamps pages imported+ * without a contextual mode (skipped under --no-embed, which does not count+ * them as pending). Neither writes a page revision, journal request or+ * canonical file. `--type` cannot narrow those repairs, so it is refused with+ * the repair commands instead.+ */+async function reindexManaged(engine: BrainEngine, opts: ReindexOpts, type: string | null, pending: number): Promise<ReindexResult> {+ const base = { pending, dryRun: false, chunkerVersion: MARKDOWN_CHUNKER_VERSION, type };+ const repairs = opts.noEmbed ? ['safe-chunks'] : ['safe-chunks', 'contextual-mode'];+ const redirect = repairs.map(kind => `gbrain repair ${kind} --apply${opts.noEmbed ? ' --no-embed' : ''}`).join(' && ');+ if (type) {+ const error = `--type cannot narrow a managed reindex; re-chunk every drifted page with: ${redirect}`;+ if (opts.json) process.stdout.write(JSON.stringify({ error, delegated_to: repairs }) + '\n');+ else process.stderr.write(`[reindex] ${error}\n`);+ setCliExitVerdict(2);+ return { ...base, pendingAfter: pending, reindexed: 0, skipped: 0, failed: 0 };+ }+ const { contextualModeRepair } = await import('../core/repair/contextual-mode.ts');+ const { safeChunksRepair } = await import('../core/repair/safe-chunks.ts');+ const { resolveRepairScope, runRepair } = await import('../core/repair/core.ts');+ const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, dryRun: false, sourceId: 'default',+ logger: { info: (msg: string) => process.stderr.write(`${msg}\n`), warn: (msg: string) => process.stderr.write(`${msg}\n`), error: (msg: string) => process.stderr.write(`${msg}\n`) } };+ const scope = await resolveRepairScope(engine);+ const stopped: string[] = [];+ let unsupported = 0;+ for (const handler of opts.noEmbed ? [safeChunksRepair] : [safeChunksRepair, contextualModeRepair]) {+ const run = await runRepair(ctx as Parameters<typeof runRepair>[0], handler, scope, { apply: true, limit: opts.limit, embed: !opts.noEmbed });+ if (run.stopped) stopped.push(run.stopped.message);+ unsupported += Object.values(run.residuals).reduce((sum, count) => sum + count, 0);+ }+ if (pending > 0) await refreshProjectionStatistics(engine);+ const pendingAfter = await countPending(engine, type, !!opts.noEmbed);+ const reindexed = Math.max(0, pending - pendingAfter);+ if (stopped.length) setCliExitVerdict(1);+ if (opts.json) {+ process.stdout.write(JSON.stringify({ pending, pending_after: pendingAfter, reindexed, skipped: 0, failed: 0, chunker_version: MARKDOWN_CHUNKER_VERSION, type,+ delegated_to: repairs, ...(unsupported ? { unsupported_pages: unsupported } : {}), ...(stopped.length ? { stopped } : {}) }) + '\n');+ } else {+ process.stderr.write(`[reindex] Managed brain: re-chunked through ${repairs.map(kind => `gbrain repair ${kind}`).join(' and ')} (no page writes). `+ + `reindexed=${reindexed} pending_before=${pending} pending_after=${pendingAfter}\n`);+ if (unsupported) process.stderr.write(`[reindex] ${unsupported} page(s) the projection repairs cannot rebuild (code without a source path, or another page kind) are left for their importer.\n`);+ for (const message of stopped) process.stderr.write(`[reindex] ${message}\n`);+ }+ return { ...base, pendingAfter, reindexed, skipped: 0, failed: 0 };+}diff --git a/test/reindex-managed-5377.test.ts b/test/reindex-managed-5377.test.tsnew file mode 100644index 0000000000..28017c980d--- /dev/null+++ b/test/reindex-managed-5377.test.ts@@ -0,0 +1,57 @@+/**+ * #5377: on a managed brain `reindex --markdown` cannot re-import through the+ * legacy writer. It delegates to the projection repairs (safe-chunks, then+ * contextual-mode), which change no page revision, journal or canonical file.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runReindex } from '../src/commands/reindex.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-reindex-managed-'));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++async function quiet<T>(fn: () => Promise<T>): Promise<{ result: T; stdout: string; stderr: string }> {+ const out = process.stdout.write.bind(process.stdout), err = process.stderr.write.bind(process.stderr);+ let stdout = '', stderr = '';+ (process.stdout.write as unknown as (chunk: unknown) => boolean) = (chunk: unknown) => { stdout += String(chunk); return true; };+ (process.stderr.write as unknown as (chunk: unknown) => boolean) = (chunk: unknown) => { stderr += String(chunk); return true; };+ try { return { result: await fn(), stdout, stderr }; } finally { process.stdout.write = out; process.stderr.write = err; }+}++test('managed reindex --markdown re-seals drifted pages without a page write (#5377)', () => withEnv({ GBRAIN_HOME: home }, async () => {+ _resetCliExitVerdictForTests();+ await importFromContent(engine, 'notes/a', '---\ntitle: A\ntype: note\n---\n\nAlpha body text for the reindex fixture.\n', { noEmbed: true, sourceId: 'default' });+ await engine.executeRaw("UPDATE pages SET chunker_version=1 WHERE slug='notes/a'");+ const [before] = await engine.executeRaw<{ knowledge_revision: string }>("SELECT knowledge_revision FROM pages WHERE slug='notes/a'");+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');++ const { result, stderr } = await quiet(() => runReindex(engine, ['--markdown', '--no-embed']));+ expect(stderr).not.toContain('legacy writer');+ expect(result.failed).toBe(0);+ expect(result.reindexed).toBe(1);+ expect(result.pendingAfter).toBe(0);+ expect(currentExitCode()).toBe(0);+ const [after] = await engine.executeRaw<{ knowledge_revision: string; chunker_version: number }>("SELECT knowledge_revision, chunker_version FROM pages WHERE slug='notes/a'");+ expect(after.chunker_version).toBe(MARKDOWN_CHUNKER_VERSION);+ expect(after.knowledge_revision).toBe(before.knowledge_revision);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests')).toEqual([]);+}));