Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): keyless brains queue no embed-backfill; a queued one ends once as embed_backfill_skipped

garrytan515c0746d5ce
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 18e3b06066..975600ea67 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -118,6 +118,8 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="embedding-dimensions"></a>**`gbrain import` fails with `expected N dimensions, not M`?** Run `gbrain doctor`. It will print the exact `gbrain config set ...` or `gbrain migrate embeddings` command to repair the mismatch (`migrate embeddings` re-embeds through the provider: effect `paid`, ask the user first). You should not need to delete `~/.gbrain`. Fresh `gbrain init --pglite` auto-detects your embedding provider from API keys: set `VOYAGE_API_KEY` (or `OPENAI_API_KEY` / another provider key) in the environment — or in `~/.gbrain/config.json`, which init also reads — before running init, or pass `--embedding-model <provider>:<model>` explicitly. With multiple keys set, init fires an interactive picker (non-TTY auto-picks the Voyage default when its key is present). With no keys at all, init continues keyless (keyword-only search) with a loud notice; add a key later and re-run `gbrain init --force --embedding-model voyage:voyage-4` to enable embeddings (effects: `credentials` and `paid`, since every page is embedded through the provider; it needs the brain's writer lock, so stop a running `gbrain serve` first; pages and facts are kept), or pass `--no-embedding` up front to make keyless explicit. `gbrain config get embedding_disabled` reports whether embedding is off and which plane says so (the config file and the database setting; `true` on either turns it off); `gbrain config set embedding_disabled true|false` and `gbrain config unset embedding_disabled` change both, and the `init --force --embedding-model` enable path clears both. See [`docs/integrations/embedding-providers.md`](../integrations/embedding-providers.md) for the full provider matrix and [`docs/operations/headless-install.md`](../operations/headless-install.md) for Docker/CI sequencing.
+<a id="embed-backfill-skipped"></a>**A sync job or `embed-backfill` job reports `embed_backfill_skipped` (reason `embedding_disabled`)?** Nothing is wrong: the brain is keyless by choice (`embedding_disabled`), so sync queues no embed-backfill and a backfill already queued ends on its first attempt without reading a page. Search stays keyword-only. The notice appears once per brain state (the first skip after the brain became keyless); its fix is the optional step that turns embedding on and names the provider key it needs (effects `credentials` and `paid`: ask the user first).
+
**`gbrain doctor` warns `default_source_local_path`?** Your `default` source has no `local_path` AND that null pointer is provably breaking write-through (the repo fallback is another source's own working tree, or file-backed default pages have no resolvable root). A null `local_path` on its own is the designed fallback topology and reports ok. The repair is a pointer update, never a file move: `gbrain sources set-path default <path>` prints the prior value before changing it and refuses a path that nests inside or swallows another source's tree (exit 6; `--force` bypasses). **Say to your agent:** *"Run a brain health check and fix what you find"* — the maintain skill runs `gbrain doctor` and applies the printed repair.
**A Gmail, Calendar or GitHub connector source still has an old `local_path`?** Connector sources sync from their provider, so autopilot ignores their `local_path`: once a connector has synced (or tried to) at least once, autopilot syncs it on every interval and runs its database phases with no checkout. A connector that has never synced stays idle until you run `gbrain sync --source <id>` once; autopilot prints that command the first time it skips one. To remove the stale pointer, run `gbrain sources set-path <id> --clear` (connector sources only; it refuses a filesystem source and a connector bound to a canonical owner). `config.syncEnabled=false` still opts a source out. **Say to your agent:** *"My Gmail source points at an old folder. Clear it and keep it syncing."*
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 6e752b2fd0..2e0a9c8320 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1192,6 +1192,8 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):
console.log(` → embed-backfill not queued (${sub.engineKind} has no recognized persistent worker); run: gbrain embed --stale --source ${id}`);
} else if (sub.status === 'stalled') {
console.log(` → embed-backfill not queued: the last ${sub.failures} runs failed on the same blocked pages with nothing embedded. See: gbrain doctor --only embed_backfill_stalled`);
+ } else if (sub.status === 'embedding_disabled') {
+ console.log(' → embed-backfill not queued: embedding is disabled on this brain (keyless by choice; keyword search works).');
} else { sub satisfies never; }
} catch (err) {
// Federation flip already succeeded; embed-backfill is a follow-up nicety.
diff --git a/src/core/embed-backfill-submit.ts b/src/core/embed-backfill-submit.ts
index 63b6a78f5e..a8c36e3925 100644
--- a/src/core/embed-backfill-submit.ts
+++ b/src/core/embed-backfill-submit.ts
@@ -42,7 +42,10 @@
* (`gbrain sources status`, webhook response body, sync completion banner).
*/
import type { BrainEngine } from './engine.ts';
+import { cliRenderContext, noticeBlock, renderNotice, type Notice, type RenderedNotice } from './agent-output.ts';
import { getCompanyBrainProfile } from './company-brain/profile.ts';
+import { loadConfig } from './config.ts';
+import { embeddingsDisabled } from './embedding-disabled.ts';
import { opError } from './ops/contract.ts';
import { readFix } from './ops/op-fix.ts';
import { embedBackfillWorkerSurface } from './minions/embed-backfill-admission.ts';
@@ -64,7 +67,9 @@ export type SubmitEmbedBackfillResult =
| { status: 'spend_capped'; spend24hUsd: number; spendCapUsd: number }
/** #6803: the last EMBED_BACKFILL_STALL_LIMIT backfills failed identically with nothing embedded, and nothing has changed since. */
| { status: 'stalled'; failures: number; remaining: number; blocked: number; lastFailedAt: string }
- | { status: 'no_worker_surface'; engineKind: 'pglite' | 'unknown' };
+ | { status: 'no_worker_surface'; engineKind: 'pglite' | 'unknown' }
+ /** The brain is keyless by choice: nothing to embed. `notice` is set only the first time for this brain state. */
+ | { status: 'embedding_disabled'; notice: Notice | null };
export type SubmitEmbedBackfillStatus = SubmitEmbedBackfillResult['status'];
@@ -135,6 +140,40 @@ async function readIntConfig(
return Number.isFinite(n) && n > 0 ? n : def;
}
+export const EMBED_BACKFILL_SKIP_REPORTED_KEY = 'embed.backfill_skip_reported';
+
+/**
+ * GBRA-133 (latency 6.9): a brain keyless by choice (`init --no-embedding`)
+ * runs no embed-backfill. Every automatic submitter and the handler stop here
+ * instead of draining each stale chunk against no embedding model (one failure
+ * per page, three attempts, the worker held for minutes). Returns null when
+ * embedding is on. The embed_backfill_skipped notice is returned once per brain
+ * state: the first skip records it under EMBED_BACKFILL_SKIP_REPORTED_KEY, and
+ * a check that finds embedding on clears the record, so a brain that turns
+ * keyless again is told again.
+ */
+export async function keylessEmbedBackfill(engine: BrainEngine): Promise<{ notice: Notice | null } | null> {
+ const reported = await engine.getConfig(EMBED_BACKFILL_SKIP_REPORTED_KEY).catch(() => null);
+ if (!await embeddingsDisabled(engine)) {
+ if (reported !== null) await engine.unsetConfig(EMBED_BACKFILL_SKIP_REPORTED_KEY).catch(() => undefined);
+ return null;
+ }
+ if (reported === 'embedding_disabled') return { notice: null };
+ await engine.setConfig(EMBED_BACKFILL_SKIP_REPORTED_KEY, 'embedding_disabled').catch(() => undefined);
+ const { embeddingEnablement } = await import('./readiness.ts');
+ const enable = embeddingEnablement({ engine: engine.kind, ...(loadConfig() ?? {}), embedding_disabled: true });
+ return { notice: { code: 'embed_backfill_skipped', kind: 'info',
+ why: 'Embedding is disabled on this brain (keyless by choice), so no embed-backfill runs and search stays keyword-only; nothing is failing.',
+ fix: { ...enable, why: `Keyless is a valid choice and needs nothing. To turn on semantic search instead: ${enable.why}` } } };
+}
+
+/** A job's report of the keyless notice: one block on stderr, and the wire form its result carries. */
+export function reportKeylessNotice(notice: Notice): RenderedNotice {
+ const rendered = renderNotice(notice, cliRenderContext());
+ process.stderr.write(`${noticeBlock(rendered)}\n`);
+ return rendered;
+}
+
export async function submitEmbedBackfill(
engine: BrainEngine,
sourceId: string,
@@ -145,6 +184,8 @@ export async function submitEmbedBackfill(
// a row so the undrainable job cannot also cooldown-block a later attempt.
const surface = embedBackfillWorkerSurface(engine);
if (surface.status === 'no_worker_surface') return surface;
+ const keyless = await keylessEmbedBackfill(engine);
+ if (keyless) return { status: 'embedding_disabled', notice: keyless.notice };
if (await getCompanyBrainProfile(engine, sourceId)) throw opError('source_profile_no_backfill', 'This source profile disables automatic embedding backfill. Enable enrichment only through a separate explicit action.',
`Source ${sourceId} uses the company-brain import profile, which never queues embedding backfill; keyword search keeps working. Embedding it is a separate action the user approves; do not edit the stored profile.`,
{ docs: 'docs/guides/company-brain-ingestion.md#what-stays-opt-in',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5a5436d9dc..f40bfe271c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -774,4 +774,5 @@ export const NOTICE_CODES = {
fence_normalized: { kind: 'coaching', summary: 'A write\'s facts or takes fence was rewritten losslessly (rows and classes named, never values): the stored page differs from what was sent, so re-read it with get_page before editing; remember and takes_add write rows that never need it.' },
write_capacity_low: { kind: 'info', summary: 'A cumulative write cap (request ids or receipt bytes) is at or past 80% or runs out within `persistence.capacity.warn_days`; writes still work. Write and sync receipts carry it at most once an hour per process per scope; sync status, doctor and autopilot cycle output every time. Mute on receipts with `gbrain notices mute write_capacity_low`; doctor still reports it.' },
write_capacity_backpressure: { kind: 'degraded', summary: 'A cumulative write cap passed `persistence.capacity.background_pause_pct`, so background producers (maintenance, conversation facts, autopilot phases and catch-up syncs) pause while interactive writes keep the rest; shown once when the pause starts.' },
+ embed_backfill_skipped: { kind: 'info', summary: 'The brain is keyless by choice (`embedding_disabled`), so no embed-backfill was queued or run (reason `embedding_disabled`) and search stays keyword-only. Reported once per brain state; the fix is the optional step that turns embedding on (names the provider key it needs).' },
} as const satisfies Record<string, NoticeEntry>;
diff --git a/src/core/github-source.ts b/src/core/github-source.ts
index b3b53c8016..6e6ff9bb32 100644
--- a/src/core/github-source.ts
+++ b/src/core/github-source.ts
@@ -1472,6 +1472,8 @@ async function runExtractAndEmbed(
process.stderr.write(`[github] large sync (${totalChanges} pages); embeds deferred to embed-backfill job ${sub.jobId} — or ${drainHint}\n`);
} else if (sub.status === 'cooldown' || sub.status === 'spend_capped' || sub.status === 'no_worker_surface' || sub.status === 'stalled') {
process.stderr.write(`[github] large sync (${totalChanges} pages); embed-backfill not queued (${sub.status}) — ${drainHint}\n`);
+ } else if (sub.status === 'embedding_disabled') {
+ process.stderr.write(`[github] large sync (${totalChanges} pages); embed-backfill not queued: embedding is disabled on this brain (keyless by choice)\n`);
} else { sub satisfies never; }
} catch (err) {
process.stderr.write(`[github] embed-backfill submission failed: ${err instanceof Error ? err.message : String(err)} — ${drainHint}\n`);
diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.ts
index 7228350204..8d4c0c8c71 100644
--- a/src/core/google/google-source.ts
+++ b/src/core/google/google-source.ts
@@ -664,6 +664,8 @@ async function runExtractAndEmbed(
const sub = await submitEmbedBackfill(deps.engine, deps.sourceId, { reason: 'google_sync_defer' });
if (sub.status === 'submitted') {
process.stderr.write(`[google] large sync (${totalChanges} pages); embeds deferred to embed-backfill job ${sub.jobId} — or ${drainHint}\n`);
+ } else if (sub.status === 'embedding_disabled') {
+ process.stderr.write(`[google] large sync (${totalChanges} pages); embed-backfill not queued: embedding is disabled on this brain (keyless by choice)\n`);
} else {
process.stderr.write(`[google] large sync (${totalChanges} pages); embed-backfill not queued (${sub.status}) — ${drainHint}\n`);
}
diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.ts
index 7d8d1156f0..c18e7775a0 100644
--- a/src/core/minions/handlers/embed-backfill.ts
+++ b/src/core/minions/handlers/embed-backfill.ts
@@ -58,6 +58,8 @@ import { parseUsdLimit, usdLimitToCap, resolveSpendPosture } from '../../spend-p
import { recordMinionJobSpend } from '../../minion-spend.ts';
import { embedBackfillLockId, EMBED_BACKFILL_LOCK_TTL_MIN } from '../../embed-backfill-lock.ts';
+import { keylessEmbedBackfill, reportKeylessNotice } from '../../embed-backfill-submit.ts';
+import type { RenderedNotice } from '../../agent-output.ts';
const DEFAULT_MAX_USD_PER_JOB = 10;
@@ -69,7 +71,12 @@ export interface EmbedBackfillJobData {
}
export interface EmbedBackfillResult {
- status: 'success' | 'already_in_progress' | 'budget_exhausted' | 'aborted';
+ status: 'success' | 'already_in_progress' | 'budget_exhausted' | 'aborted' | 'skipped';
+ /** Set when status === 'skipped': the brain is keyless by choice, so nothing was read or embedded. */
+ outcome?: 'embed_backfill_skipped';
+ reason?: 'embedding_disabled';
+ /** The embed_backfill_skipped notice, on the first skip for this brain state only. */
+ notice?: RenderedNotice;
sourceId: string;
embedded: number;
chunksProcessed: number;
@@ -229,6 +236,12 @@ export function makeEmbedBackfillHandler(
): Promise<EmbedBackfillResult> {
const { sourceId, batchSize } = parseParams(job.data);
+ const keyless = await keylessEmbedBackfill(engine);
+ if (keyless) {
+ return { status: 'skipped', outcome: 'embed_backfill_skipped', reason: 'embedding_disabled', sourceId, embedded: 0, chunksProcessed: 0,
+ pagesProcessed: 0, invalidated: 0, spentUsd: 0, ...(keyless.notice ? { notice: reportKeylessNotice(keyless.notice) } : {}) };
+ }
+
// D2: per-source lock at handler entry. The submit-side cooldown (D19)
// prevents most contention but this is the run-side safety net.
const lockKey = embedBackfillLockId(sourceId);
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index 9e38a28f95..bf9f0bd320 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -154,12 +154,17 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
const autoEmbed = job.data.auto_embed_backfill !== false;
let embedJobId: number | null = null;
let embedSkipReason: string | null = null;
+ let embedNotice: import('../../agent-output.ts').RenderedNotice | null = null;
const { syncProducedEmbeddableContent } = await import('../../sync-embed-backfill.ts');
if (autoEmbed && sourceId && result.status !== 'up_to_date' && result.status !== 'dry_run' && syncProducedEmbeddableContent(result)) {
try {
const { isFederatedV2Enabled } = await import('../../feature-flags.ts');
- if (await isFederatedV2Enabled(engine)) {
- const { submitEmbedBackfill } = await import('../../embed-backfill-submit.ts');
+ const { keylessEmbedBackfill, reportKeylessNotice, submitEmbedBackfill } = await import('../../embed-backfill-submit.ts');
+ const keyless = await keylessEmbedBackfill(engine);
+ if (keyless) {
+ embedSkipReason = 'embedding_disabled';
+ if (keyless.notice) embedNotice = reportKeylessNotice(keyless.notice);
+ } else if (await isFederatedV2Enabled(engine)) {
const submission = await submitEmbedBackfill(engine, sourceId, {
reason: typeof job.data.embed_reason === 'string'
? (job.data.embed_reason as string)
@@ -169,6 +174,9 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
embedJobId = submission.jobId;
} else if (submission.status === 'cooldown' || submission.status === 'spend_capped' || submission.status === 'no_worker_surface' || submission.status === 'stalled') {
embedSkipReason = submission.status;
+ } else if (submission.status === 'embedding_disabled') {
+ embedSkipReason = submission.status;
+ if (submission.notice) embedNotice = reportKeylessNotice(submission.notice);
} else {
submission satisfies never;
}
@@ -198,6 +206,6 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
throw new UnrecoverableError(`Managed sync of source ${sourceId ?? 'default'} is ${result.status === 'blocked_by_failures' ? 'blocked' : 'stopped'}`
+ ` (${drain?.stop_reason ?? result.status}${drain?.remaining != null ? `, ${drain.remaining} entries left` : ''}). ${next?.why ?? ''}${next?.command ? ` Next: ${next.command}` : ''}`.trim());
}
- return { ...result, ...drained, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason };
+ return { ...result, ...drained, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason, ...(embedNotice ? { notice: embedNotice } : {}) };
};
}
diff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.ts
index c8a606721a..e605d253a6 100644
--- a/src/core/sync-embed-backfill.ts
+++ b/src/core/sync-embed-backfill.ts
@@ -7,7 +7,8 @@
import type { BrainEngine } from './engine.ts';
import { syncFailureJsonFields, type ManagedSyncFailure } from './persistence/sync-failures.ts';
import { syncHoldJsonFields } from './persistence/sync-holds.ts';
-import { submitEmbedBackfill } from './embed-backfill-submit.ts';
+import { keylessEmbedBackfill, submitEmbedBackfill } from './embed-backfill-submit.ts';
+import { cliRenderContext, renderNotice, type Notice, type RenderedNotice } from './agent-output.ts';
import { resolveWorkerBackedSyncEmbedMode } from './embedding.ts';
import {
embedBackfillManualDrainCommand,
@@ -136,7 +137,9 @@ export type SyncEmbedBackfillOutcome =
}
| { status: 'skipped'; reason: 'cooldown'; command: string }
| { status: 'skipped'; reason: 'spend_capped'; command: string; spend_cap_usd: number }
- | { status: 'skipped'; reason: 'stalled'; command: string; failures: number };
+ | { status: 'skipped'; reason: 'stalled'; command: string; failures: number }
+ /** The brain is keyless by choice; `notice` (embed_backfill_skipped) only on the first skip for this brain state. */
+ | { status: 'skipped'; reason: 'embedding_disabled'; notice?: RenderedNotice };
export async function resolveSyncEmbedBackfill(
engine: BrainEngine,
@@ -146,6 +149,8 @@ export async function resolveSyncEmbedBackfill(
autoSubmitDisabled: boolean;
},
): Promise<SyncEmbedBackfillOutcome> {
+ const keyless = await keylessEmbedBackfill(engine);
+ if (keyless) return keylessOutcome(keyless.notice);
const command = embedBackfillManualDrainCommand(sourceId);
if (embedBackfillWorkerSurface(engine).status === 'no_worker_surface') {
return { status: 'manual_drain_required', command, reason: 'no_worker_surface' };
@@ -171,12 +176,18 @@ export async function resolveSyncEmbedBackfill(
return { status: 'manual_drain_required', command, reason: 'no_worker_surface' };
case 'stalled':
return { status: 'skipped', reason: 'stalled', command, failures: submitted.failures };
+ case 'embedding_disabled':
+ return keylessOutcome(submitted.notice);
default:
submitted satisfies never;
throw new Error('unreachable embed-backfill submission result');
}
}
+function keylessOutcome(notice: Notice | null): SyncEmbedBackfillOutcome {
+ return { status: 'skipped', reason: 'embedding_disabled', ...(notice ? { notice: renderNotice(notice, cliRenderContext()) } : {}) };
+}
+
export function formatSyncEmbedBackfillOutcome(
outcome: SyncEmbedBackfillOutcome,
sourceName?: string,
@@ -188,6 +199,12 @@ export function formatSyncEmbedBackfillOutcome(
case 'manual_drain_required':
return `embed-backfill not queued; manual drain required: \`${outcome.command}\`${source}`;
case 'skipped': {
+ if (outcome.reason === 'embedding_disabled') {
+ const enable = outcome.notice?.fix?.command;
+ return outcome.notice
+ ? `embed-backfill skipped${source}: embedding is disabled on this brain (keyless by choice; keyword search works)${enable ? `. To turn on semantic search: \`${enable}\`` : ''}`
+ : `embed-backfill skipped (embedding disabled)${source}`;
+ }
if (outcome.reason === 'stalled') {
return `embed-backfill skipped${source}: the last ${outcome.failures} runs failed on the same blocked pages with nothing embedded; `
+ `see \`gbrain doctor --only embed_backfill_stalled\` (manual drain: \`${outcome.command}\`)`;
diff --git a/test/e2e/s-keyless-embed-backfill-postgres.test.ts b/test/e2e/s-keyless-embed-backfill-postgres.test.ts
new file mode 100644
index 0000000000..4faf01b4dd
--- /dev/null
+++ b/test/e2e/s-keyless-embed-backfill-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-keyless-embed-backfill.test.ts'));
diff --git a/test/pathological/s-keyless-embed-backfill.test.ts b/test/pathological/s-keyless-embed-backfill.test.ts
new file mode 100644
index 0000000000..67ec9c632e
--- /dev/null
+++ b/test/pathological/s-keyless-embed-backfill.test.ts
@@ -0,0 +1,129 @@
+/**
+ * Latency finding 6.9 (GBRA-133): on a brain that is keyless by choice
+ * (`init --no-embedding`), every sync job auto-submitted an embed-backfill.
+ * The backfill drained every stale chunk against a gateway with no embedding
+ * model, logged "This brain has no explicit embedding model" per page (30k
+ * lines at 10k pages), failed its honesty gate and retried, holding the
+ * concurrency-1 worker for ~90 s while the next sync jobs waited behind it.
+ *
+ * Protects: on a keyless brain a sync job queues no embed-backfill (its result
+ * says embed_skip_reason embedding_disabled); a backfill already queued (an
+ * older build, or an explicit submit) ends once on its first attempt with
+ * outcome embed_backfill_skipped and reason embedding_disabled, without
+ * touching a page; the embed_backfill_skipped notice (keyless is a valid
+ * choice, and the step that turns embedding on) is reported once per brain
+ * state, not on every sync. Real worker, 1,000 pages. PGLite always, Postgres
+ * when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { buildGatewayConfig } from '../../src/core/ai/build-gateway-config.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { MinionWorker } from '../../src/core/minions/worker.ts';
+import { makeSyncHandler } from '../../src/core/minions/handlers/sync.ts';
+import { makeEmbedBackfillHandler } from '../../src/core/minions/handlers/embed-backfill.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { expectUnitNotAborted, pathologicalArms } from './harness.ts';
+
+const PAGES = 1000;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();
+
+function writeNotes(root: string, from: number, to: number): void {
+ for (let i = from; i < to; i++) writeFileSync(join(root, 'notes', `n-${i}.md`), `---\ntype: note\ntitle: Note ${i}\n---\n# Note ${i}\n\nBody of example note ${i}.\n`);
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', `notes ${from}-${to}`);
+}
+
+/** Runs the queue on a real worker until every listed job is terminal. */
+async function runJobs(engine: BrainEngine, ids: number[]): Promise<void> {
+ const queue = new MinionQueue(engine);
+ const worker = new MinionWorker(engine, { pollInterval: 25, concurrency: 1 });
+ worker.register('sync', makeSyncHandler(engine));
+ worker.register('embed-backfill', makeEmbedBackfillHandler(engine));
+ const running = worker.start();
+ try {
+ for (let i = 0; i < 4_800; i++) {
+ const statuses = await Promise.all(ids.map(async id => (await queue.getJob(id))?.status));
+ if (statuses.every(status => status === 'completed' || status === 'failed' || status === 'dead')) break;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ } finally { worker.stop(); await running; }
+}
+
+/** Every line written to stderr and console while `run` runs. */
+async function captureOutput<T>(run: () => Promise<T>): Promise<{ value: T; lines: string[] }> {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ const original = { error: console.error, warn: console.warn, log: console.log };
+ const record = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ process.stderr.write = ((chunk: unknown) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ Object.assign(console, { error: record, warn: record, log: record });
+ try { return { value: await run(), lines }; } finally { process.stderr.write = write; Object.assign(console, original); }
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`keyless embed-backfill (${backend})`, () => {
+ test('keyless item: a 1k-page sync job queues no embed-backfill, a queued one ends once skipped, and the notice is reported once', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-keyless-backfill-'));
+ const root = join(home, 'repo');
+ try {
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ // A keyless brain as `gbrain init --no-embedding` leaves it, and the worker's gateway as the CLI builds it.
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.setConfig('embedding_disabled', 'true');
+ configureGateway(buildGatewayConfig({ engine: engine.kind, embedding_disabled: true } as never));
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ writeNotes(root, 0, PAGES);
+ const sourceId = 'keyless-example';
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ const queue = new MinionQueue(engine);
+ // A sync job submitted without options, then a backfill queued for the stale chunks it left (an older build's
+ // auto-submit or an explicit submit; on PGLite the inline-worker submit `jobs submit --follow` uses).
+ const sync = await queue.add('sync', { sourceId, noPull: true, concurrency: 1 });
+ const first = await captureOutput(async () => {
+ await expectUnitNotAborted(() => runJobs(engine, [sync.id]));
+ const queued = await queue.add('embed-backfill', { sourceId, batchSize: 500, reason: 'sync_handler' }, {}, { allowPgliteInlineWorker: true });
+ await expectUnitNotAborted(() => runJobs(engine, [queued.id]));
+ return queued;
+ });
+ const queued = first.value;
+ const backfill = (await queue.getJob(queued.id))!;
+ expect({ status: backfill.status, started: backfill.attempts_started, failed: backfill.attempts_made }).toEqual({ status: 'completed', started: 1, failed: 0 });
+ expect(backfill.result).toMatchObject({ status: 'skipped', outcome: 'embed_backfill_skipped', reason: 'embedding_disabled', sourceId,
+ embedded: 0, chunksProcessed: 0, pagesProcessed: 0 });
+ expect(first.lines.filter(line => /no explicit embedding model/i.test(line))).toEqual([]);
+ const syncJob = (await queue.getJob(sync.id))!;
+ expect(syncJob.status).toBe('completed');
+ expect(syncJob.result).toMatchObject({ embed_job_id: null, embed_skip_reason: 'embedding_disabled' });
+ const [pages] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [sourceId]);
+ expect(pages!.n).toBe(PAGES);
+ const backfills = await engine.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE name='embed-backfill'");
+ expect(backfills.map(row => Number(row.id))).toEqual([queued.id]);
+ const notices = (lines: string[]) => lines.filter(line => line.includes('embed_backfill_skipped'));
+ expect(notices(first.lines)).toHaveLength(1);
+ const notice = [backfill.result, syncJob.result].map(result => (result as { notice?: Record<string, any> }).notice).find(Boolean)!;
+ expect(notice).toMatchObject({ code: 'embed_backfill_skipped', kind: 'info', why: expect.stringMatching(/keyless/i),
+ fix: { next: expect.any(String), why: expect.stringMatching(/valid choice/i) } });
+
+ // The next sync on the same keyless brain reports nothing new.
+ writeNotes(root, PAGES, PAGES + 5);
+ const again = await queue.add('sync', { sourceId, noPull: true, concurrency: 1 });
+ const second = await captureOutput(() => runJobs(engine, [again.id]));
+ expect((await queue.getJob(again.id))!.result).toMatchObject({ embed_job_id: null, embed_skip_reason: 'embedding_disabled' });
+ expect((await queue.getJob(again.id))!.result).not.toHaveProperty('notice');
+ expect(notices(second.lines)).toEqual([]);
+ expect((await engine.executeRaw("SELECT id FROM minion_jobs WHERE name='embed-backfill'")).length).toBe(1);
+ } finally { resetGateway(); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 600_000);
+ });
+}