Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrations): v0.28.0 re-chunk TODO names gbrain reindex --markdown (D-N5)
time-attackff0eb63e73c0
diff --git a/skills/migrations/v0.28.0.md b/skills/migrations/v0.28.0.mdindex 9a99db74e3..fee355dfc8 100644--- a/skills/migrations/v0.28.0.md+++ b/skills/migrations/v0.28.0.md@@ -48,21 +48,17 @@ You upgraded from v0.27 (or earlier) to v0.28. New surface area:gbrain doctor```-Expected: `takes_backfill_complete` and `takes_fence_chunk_leak` checks-both green. If either is red, follow the doctor's fix hint.+Expected: no failing checks. If one fails, follow the doctor's fix hint.### 2. Re-chunk pages with pre-v0.28 takes (one-time, cosmetic for fresh installs)For brains with existing fenced takes content in pre-v0.28 markdown:```bash-# Identify pages with takes content that's been chunked into content_chunks-gbrain doctor --check takes_fence_chunk_leak--# If the check is RED, re-import those pages so the new chunker rule applies.-# Run only on the affected slugs (the doctor output enumerates them):-gbrain extract takes --rebuild-gbrain sync # picks up the markdown delta if any+# Pages chunked before the fence strip keep an older chunker_version;+# reindex re-chunks exactly those pages. Preview, then run:+gbrain reindex --markdown --dry-run+gbrain reindex --markdown```Fresh installs (no pre-v0.28 takes content): nothing to do.diff --git a/src/commands/migrations/v0_28_0.ts b/src/commands/migrations/v0_28_0.tsindex 1efbc2ed9b..6a76ac547a 100644--- a/src/commands/migrations/v0_28_0.ts+++ b/src/commands/migrations/v0_28_0.ts@@ -12,8 +12,8 @@* pre-existing fenced takes tables in markdown populate the* takes table without blocking the foreground upgrade.* Falls back to inline run on PGLite (no Minion worker).- * C. Re-chunk — emit a pending-host-work TODO for `gbrain re-chunk- * --where pages-with-takes` (Codex P0 #3 fix: pages with+ * C. Re-chunk — emit a pending-host-work TODO for `gbrain reindex+ * --markdown` (Codex P0 #3 fix: pages with* pre-v0.28 chunks still contain the fenced takes content;* the chunker strip only applies to NEW imports). Re-chunk* is heavy + per-page-disruptive, so we queue a TODO instead@@ -21,7 +21,8 @@* D. Record — runner-owned ledger write (handled by apply-migrations.ts).** No content mutation. No data loss. Operator runs `gbrain doctor` after- * upgrade to verify takes_backfill_complete + takes_fence_chunk_leak checks.+ * upgrade, then `gbrain reindex --markdown` for pages chunked before the+ * fence strip.*/import { existsSync, mkdirSync, appendFileSync, readFileSync } from 'node:fs';@@ -96,9 +97,10 @@ async function phaseBBackfill(if (!engine) return { name: 'backfill', status: 'skipped', detail: 'no_brain_configured' };try {- // Inline run on both engines for v0.28.0 simplicity. Larger brains can run- // `gbrain extract takes --rebuild` later; the migration's job is to get- // the table populated for upgrade-time doctor checks.+ // Inline run on both engines for v0.28.0 simplicity. Re-running this+ // backfill is `gbrain apply-migrations --migration 0.28.0`; the+ // migration's job is to get the table populated for upgrade-time doctor+ // checks.const { extractTakes } = await import('../../core/cycle/extract-takes.ts');const result = await extractTakes(engine, { source: 'db' });@@ -162,7 +164,7 @@ function phaseCRechunkTodo(opts: OrchestratorOpts): OrchestratorPhaseResult {ts: new Date().toISOString(),skill: 'skills/migrations/v0.28.0.md',reason: 'Pages with pre-v0.28 chunks still contain fenced takes content. Re-chunk so the new chunker strip rule is applied (Codex P0 #3 fix).',- command: "gbrain extract takes --rebuild # forces re-chunk via reimport pipeline; see migration doc for the precise sweep command in your env",+ command: 'gbrain reindex --markdown',_key: key,};appendFileSync(pendingHostWorkPath(), JSON.stringify(entry) + '\n');diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex f7f4ab000a..e3c019aa5f 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -104,8 +104,7 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {// v0.28: strip fenced takes blocks BEFORE chunking. Takes are retrieval-// accessible only via the takes table; their content must not appear in- // content_chunks where the per-token allow-list cannot reach. The- // takes_fence_chunk_leak doctor check verifies this invariant.+ // content_chunks where the per-token allow-list cannot reach.//// v0.32.2: also strip private facts (Codex R2-#1). World facts stay so// search retains its public-knowledge surface; private rows are filtereddiff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex 9fd7bcbb4c..2b0aaca362 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -8,9 +8,9 @@* timeline; parse fence; batch upsert** Source-of-truth contract: markdown is canonical. The takes table is a- * derived index. `gbrain extract takes --rebuild` deletes all takes for- * the affected pages first, then re-inserts. Without --rebuild, ON CONFLICT- * (page_id, row_num) DO UPDATE keeps the table in sync incrementally.+ * derived index. The `rebuild` option deletes all takes for the affected+ * pages first, then re-inserts. Without it, ON CONFLICT (page_id, row_num)+ * DO UPDATE keeps the table in sync incrementally.* On a managed brain the db path publishes each page's rows through the* persistence coordinator (the `takes` guard refuses any other writer).*diff --git a/test/migration-v0_28_0-rechunk-hint.test.ts b/test/migration-v0_28_0-rechunk-hint.test.tsnew file mode 100644index 0000000000..14cef8a9a6--- /dev/null+++ b/test/migration-v0_28_0-rechunk-hint.test.ts@@ -0,0 +1,49 @@+/**+ * D-N5 (fix wave 9) — the v0.28.0 migration queues a re-chunk TODO in+ * pending-host-work.jsonl. Its `command` must be a real gbrain invocation+ * that runs on a brain, not a nonexistent `gbrain extract takes --rebuild`.+ *+ * The test runs the queued command (with --dry-run, so nothing is written)+ * against a fresh keyless PGLite brain and requires a clean exit.+ */++import { describe, test, expect } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import { __testing } from '../src/commands/migrations/v0_28_0.ts';++const CLI_ENTRY = join(process.cwd(), 'src/cli.ts');++function runCli(home: string, args: string[]): { out: string; status: number } {+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']) delete env[key];+ const r = spawnSync('bun', ['--no-env-file', 'run', CLI_ENTRY, ...args], { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'] });+ return { out: `${r.stdout ?? ''}${r.stderr ?? ''}`, status: r.status ?? -1 };+}++describe('D-N5 — v0.28.0 re-chunk TODO names a command that runs', () => {+ test('the queued command executes on a fresh brain', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-dn5-'));+ try {+ const command = await withEnv({ GBRAIN_HOME: home, HOME: home }, async () => {+ const result = __testing.phaseCRechunkTodo({ dryRun: false } as never);+ expect(result.status).toBe('complete');+ const lines = readFileSync(__testing.pendingHostWorkPath(), 'utf8').trim().split('\n');+ return (JSON.parse(lines[lines.length - 1]) as { command: string }).command;+ });+ expect(command.startsWith('gbrain ')).toBe(true);+ expect(command).not.toContain('#');++ const init = runCli(home, ['init', '--pglite', '--no-embedding', '--non-interactive']);+ expect(init.status, init.out).toBe(0);+ const argv = command.split(/\s+/).slice(1);+ const hint = runCli(home, [...argv, '--dry-run']);+ expect(hint.status, hint.out).toBe(0);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ }, 120000);+});