Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): report facts longer than the embedding input as partially embedded (#6975)
time-attackdd579535333e
diff --git a/docs/GBRAIN_VERIFY.md b/docs/GBRAIN_VERIFY.mdindex f2653f466d..a8026de847 100644--- a/docs/GBRAIN_VERIFY.md+++ b/docs/GBRAIN_VERIFY.md@@ -254,6 +254,9 @@ gbrain doctor --json**Expected:** the `fact_take_vectors` check is `ok`. On a keyless brain(embeddings disabled) it reports "not applicable" and stays `ok`.+`details.facts.partially_embedded` counts facts longer than the 8000-character+embedding input: their vector covers only the start of the fact. They count as+current, so nothing re-embeds them or spends on them again (#6975).**If it warns** (code `stale_vectors`): its `details` count, per source, factsand takes with no vector for their current text under the brain's embeddingdiff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 0a0b5a031c..23a3a780a5 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -20,7 +20,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/loop-facts.ts` — `loop_facts_drift` (#5869): counts closed commitment loops whose fact is still active and retirable (`loopFactDrift`) and names `gbrain repair loop-facts` (explicit-only). Read-only; health unknown when the query fails.- `src/commands/doctor/checks/ontology-facts.ts` — `ontology_facts_fenced` (#6264; wave check, host-only): counts ontology observations the pre-fix `extract_facts` fence step moved onto an entity page's Facts table, restorable ones by state (`fenced`, `retired`) plus `excluded` (withdrawn, consolidated, duplicate; never a finding), through `classifyOntologyFacts`, and names `gbrain repair ontology-facts`. Read-only; an inspection error reports health unknown.- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle`, `chronicle_config_invalid` and `auto_chronicle_default_on` (#5876), registered after `unlinked_facts`, config-plane only (no provider calls). `auto_chronicle`: off by choice is ok with `severity: info`, `readiness: disabled_by_choice`; an invalid word warns `auto_chronicle_invalid`; when on it reads `core/chronicle/ledger-stats.ts` and warns `judge_llm_unavailable` (pending pages, no chat provider) or the top failure reason with that reason's fix, else reports ok with 24 h use of the daily limit, the largest writer's share, 7-day outcomes and spend, and `gbrain dream --phase chronicle`. Every warn carries `details.fix` (an Action: argv/consent/actor) and `fix_hint`. `chronicle_config_invalid` warns on an out-of-range stored `chronicle.*` value. `auto_chronicle_default_on` is ok/info with `ask_user` and keep/opt-out decisions until `gbrain config set auto_chronicle` acknowledges. Test: `test/auto-chronicle-surfaces-5876.test.ts`.-- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model; warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.+- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model, plus `facts.partially_embedded` (current vectors of facts over `EMBED_MAX_CHARS`, `partiallyEmbeddedFact`; reported, never re-embedded, #6975); warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.- `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and each source's repair command from the hold router (`holdRepairSteps`: `gbrain repair frontmatter --source <id>`, `gbrain repair fences --source <id>` for `invalid_fence` holds, both for a mixed source; with fence holds the details add `fences` and `auto_repair`, and the banner line names the fence repair through the wave entry's `bannerHow`); `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`; the doctor scan passes `frontmatterOnly`, so each file's head through its closing fence is validated when `frontmatterScanHead` proves the findings equal, else the whole file (`test/brain-writer-frontmatter-scan-head.test.ts`). Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry, #6188 D7) names sources whose cursor stopped on a fence receipt (typed or the message an older gbrain stored): the next sync recovers them with no command, `gbrain sync --source <id> --no-pull` does it now, the malformed fences the stored census knows and whether the next maintenance run repairs them, the read-only `gbrain repair fences` preview and the pause command `gbrain config set fences.repair.enabled false`; never an applying command. Tests: `test/doctor-frontmatter-holds.test.ts`, `test/persistence-sync-fence-holds.test.ts`.- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `bannerHow` when a finding's details change the banner's parenthetical, `registration` inline-in-doctor.ts or from this table). `fence_integrity` (#6188, `repair`, registered inline) counts `details.total`; its banner line says "repaired automatically by the next maintenance run" while one is active (from `details.auto_repair`), else why not, with `gbrain repair fences` as the preview; a fence-only `git_held_files` finding gets the same wording, a mixed one adds it to the frontmatter preview. `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 034f38c888..7cca73e141 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-migration-retention.ts` — fail-closed retained-vector rebuildability check shared by migration preflight, direct apply, schema transition, pinned-column repair and invalidation/config transactions. Transaction-local SHARE locks freeze source/page/vector/withdrawal/config eligibility during the census and mutation. Sealed importer text chunks can be embedded and oversized chunks healed without regenerating their source projection; unsealed unsupported media still refuses. Width changes protect archived, skipped, deleted and unrebuildable retained page vectors; same-width checks match the shared false-stamp predicate, signature gate and current-space test. Archived pending work, including same-target content drift, metadata-only restamping, NULL vectors and chunkless pages, refuses before authorization or provider work; correct target-stamped archived vectors, including grandfathered NULL hashes, are retained controls. Companion retention checks follow actual schema/pinned-width changes and the same-target persisted migration marker; the guard returns the locked companion-clear decision consumed by the writer, ignoring a different target's completed-clear flag. Schema-only work leaves takes untouched. Existing fact eligibility and deliberate expiry/supersession/audit/withdrawal policy remain unchanged. Unknown registry, width or census fails closed. The source census includes archive state, but embed leases are not archive coordination. Synthetic two-engine regressions cover preservation refusals, real imported-image migration, same-target companion preservation, retarget/first-clear refusal and fail-closed metadata. Completion counts remain archive-visible; refusal never restores a source automatically.- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker. Each provider attempt reserves its maximum input price under the acquired leases and a `FOR UPDATE` on the marker row, and records a pending entry keyed by attempt id; `settle(usage)` takes the same lock and replaces the reservation with the reported usage (refund or overshoot). Idempotent per (`authorization_generation`, attempt id): a repeated or stale-generation settle is a no-op, so a crash before settlement keeps the maximum. Missing usage keeps the maximum. Usage above the reservation debits actual, adds `overshoot_usd` and sets `halted`, which refuses further dispatch until an explicit `--max-cost-usd` renewal. `authorizeMigrationBudget(..., worstCase)` throws `MigrationBudgetRefusal` (`embedding_budget_below_worst_case`, with cap, worst case, retained debits, the filled `--max-cost-usd` command and the `write-refusals.md` anchor) before writing any state when the cap is below debits + worst case. Refusal copy prints the operator's cap, never a remainder. Resume preserves every debit; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.- `src/core/embedding-migration-worst-case.ts` — `planMigrationWorstCase(engine, plan, { rerankerModel })`: Σ per-request maximum input from `embed-batch-plan.ts` over what the run sends (target probe, the drain's two probes, stale chunks per page (including content drift: a stored text hash that no longer matches) split by `healOversizedChunks` at the target chunk size over the complete page (a split re-indexes siblings, so every healed chunk of that page counts) and wrapped with `wrapChunkTextsForStoredMode`, the chunks projection recovery and the chunkless heal will create — replayed through `readProjectionSnapshot` + `preparePageProjection` at the current chunk size then the target-size heal, and directly at the target size, keeping the larger ceiling, replacing those pages' existing chunks — stale facts in 100-row per-source batches, three smoke-check queries, the reranker probe when switching), priced with operator overrides. `usd` is null only when the embedding model is unpriced; an unpriced reranker lands in `unpriced_models` and the embedding bound is still enforced. Owns the migration and reranker probe texts. Computed at plan time for the printed estimate and again under the migration locks for the refusal.-- `src/core/facts/embedding-identity.ts` — active fact eligibility and stale model/text/width census shared by migration and fact repair. Legacy identity stays unknown. Both engine writers accept explicit `embedding_model` and compute the exact text hash; duplicate vector selection requires matching caller identity. `embed-facts.ts` installs under source-incarnation, row-version, withdrawal and configuration guards, retaining the outer migration invocation budget when nested.+- `src/core/facts/embedding-identity.ts` — active fact eligibility and stale model/text/width census shared by migration and fact repair; `partiallyEmbeddedFact` flags facts whose UTF-16 length exceeds `EMBED_MAX_CHARS` (#6975). Legacy identity stays unknown. Both engine writers accept explicit `embedding_model` and compute the exact text hash; duplicate vector selection requires matching caller identity. `embed-facts.ts` installs under source-incarnation, row-version, withdrawal and configuration guards, retaining the outer migration invocation budget when nested.- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts` and `cycle/budget-meter.ts`.diff --git a/llms-full.txt b/llms-full.txtindex 59110b83bb..5242404d66 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10528,6 +10528,9 @@ gbrain doctor --json**Expected:** the `fact_take_vectors` check is `ok`. On a keyless brain(embeddings disabled) it reports "not applicable" and stays `ok`.+`details.facts.partially_embedded` counts facts longer than the 8000-character+embedding input: their vector covers only the start of the fact. They count as+current, so nothing re-embeds them or spends on them again (#6975).**If it warns** (code `stale_vectors`): its `details` count, per source, factsand takes with no vector for their current text under the brain's embeddingdiff --git a/src/commands/doctor/checks/vector-coverage.ts b/src/commands/doctor/checks/vector-coverage.tsindex 6d0a1c56e3..7f5eebfd47 100644--- a/src/commands/doctor/checks/vector-coverage.ts+++ b/src/commands/doctor/checks/vector-coverage.ts@@ -10,7 +10,8 @@*/import { loadConfig } from '../../../core/config.ts';import { AUDIT_ROW_SOURCES } from '../../../core/facts/audit-sources.ts';-import { eligibleFactEmbedding, staleFactEmbedding } from '../../../core/facts/embedding-identity.ts';+import { eligibleFactEmbedding, partiallyEmbeddedFact, staleFactEmbedding } from '../../../core/facts/embedding-identity.ts';+import { EMBED_MAX_CHARS } from '../../../core/ai/embed-batch-plan.ts';import { takesAutoEmbedEnabled } from '../../../core/embed-takes.ts';import type { Check } from '../../doctor.ts';import { agentFix } from '../check-fix.ts';@@ -40,9 +41,11 @@ async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {try {const sources = (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).filter(s => !ctx.orphanRatioSourceId || s.id === ctx.orphanRatioSourceId);- const factRows = await engine.executeRaw<{ source_id: string; missing: number; stale: number }>(- `SELECT f.source_id, count(*) FILTER (WHERE f.embedding IS NULL)::int AS missing, count(*)::int AS stale- FROM facts f WHERE ($1::text IS NULL OR f.source_id = $1) AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}+ const factRows = await engine.executeRaw<{ source_id: string; missing: number; stale: number; partial: number }>(+ `SELECT f.source_id, count(*) FILTER (WHERE f.embedding IS NULL)::int AS missing,+ count(*) FILTER (WHERE ${staleFactEmbedding})::int AS stale,+ count(*) FILTER (WHERE NOT ${staleFactEmbedding} AND ${partiallyEmbeddedFact})::int AS partial+ FROM facts f WHERE ($1::text IS NULL OR f.source_id = $1) AND ${eligibleFactEmbedding}GROUP BY f.source_id`,[ctx.orphanRatioSourceId ?? null, [...AUDIT_ROW_SOURCES], model, dims]);const bySource: SourceVectors[] = [];@@ -55,7 +58,12 @@ async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {if (row.facts_stale || row.takes_stale) bySource.push(row);}const sum = (key: keyof Omit<SourceVectors, 'source_id'>) => bySource.reduce((n, r) => n + r[key], 0);- const facts = { missing: sum('facts_missing'), other_model: sum('facts_stale') - sum('facts_missing'), stale: sum('facts_stale') };+ const partiallyEmbedded = factRows.filter(r => sources.some(s => s.id === r.source_id)).reduce((n, r) => n + Number(r.partial), 0);+ const facts = { missing: sum('facts_missing'), other_model: sum('facts_stale') - sum('facts_missing'), stale: sum('facts_stale'),+ partially_embedded: partiallyEmbedded };+ const partialNote = partiallyEmbedded+ ? ` ${partiallyEmbedded} fact(s) are partially embedded: longer than ${EMBED_MAX_CHARS} characters, so their vector covers only the start of the fact. They stay current and are never re-embedded or charged again.`+ : '';const takes = { missing_or_changed: sum('takes_missing'), other_model: sum('takes_stale') - sum('takes_missing'), stale: sum('takes_stale') };const takesFix = await takesAutoEmbedEnabled(engine) ? 'gbrain embed --stale' : 'gbrain takes embed';const factSources = bySource.filter(r => r.facts_stale).map(r => r.source_id);@@ -64,7 +72,7 @@ async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {...factSources.map(id => `gbrain embed --facts --stale --source ${id} --dry-run --json`),];if (facts.stale === 0 && takes.stale === 0) {- checks.push({ name: 'fact_take_vectors', status: 'ok', message: `Every active fact and take has a ${model} vector for its current text.`,+ checks.push({ name: 'fact_take_vectors', status: 'ok', message: `Every active fact and take has a ${model} vector for its current text.${partialNote}`,details: { applicable: true, model, dims, facts, takes, by_source: [] } });return checks;}@@ -73,7 +81,7 @@ async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {status: 'warn',message: `${facts.stale} active fact(s) and ${takes.stale} active take(s) have no ${model} (${dims}d) vector for their current text ` +`(facts: ${facts.missing} missing, ${facts.other_model} from another model or text; takes: ${takes.missing_or_changed} missing or claim changed, ${takes.other_model} from another model). ` +- `Vector dedup, consolidation and semantic take search skip them. Fix: ${fix.join('; ')}`,+ `Vector dedup, consolidation and semantic take search skip them. Fix: ${fix.join('; ')}${partialNote && `.${partialNote}`}`,details: { code: 'stale_vectors', applicable: true, model, dims, facts, takes, by_source: bySource,cause: 'facts and takes without a current-model vector', fix, docs: VECTOR_COVERAGE_DOCS },fix: factSources.lengthdiff --git a/src/core/facts/embedding-identity.ts b/src/core/facts/embedding-identity.tsindex 28603a281b..1c02b4c7f5 100644--- a/src/core/facts/embedding-identity.ts+++ b/src/core/facts/embedding-identity.ts@@ -1,5 +1,6 @@import type { BrainEngine } from '../engine.ts';import { AUDIT_ROW_SOURCES } from './audit-sources.ts';+import { EMBED_MAX_CHARS } from '../ai/embed-batch-plan.ts';// #6960: one anti-join per fingerprint, each an equality on fact_hash, so the// planner hashes or index-probes the fingerprint once per fact. A single@@ -23,6 +24,15 @@ export const eligibleFactEmbedding = `${retainedFactEmbedding}export const staleFactEmbedding = `(f.embedding IS NULL OR f.embedding_model IS DISTINCT FROM $3OR f.embedded_text_hash IS DISTINCT FROM md5(f.fact) OR vector_dims(f.embedding)<>$4::int)`;+/**+ * #6975: the fact is longer than the text embed() sends (EMBED_MAX_CHARS UTF-16 code units),+ * so its vector covers only a prefix. md5(fact) stays the freshness key: the vector is current+ * and nothing re-embeds or charges for it; doctor reports it as partially embedded. UTF-16+ * length is code points plus one per astral character; octet_length bounds it from above.+ */+export const partiallyEmbeddedFact = `(octet_length(f.fact) > ${EMBED_MAX_CHARS}+ AND length(f.fact) + length(regexp_replace(f.fact, '[^\\U00010000-\\U0010FFFF]', '', 'g')) > ${EMBED_MAX_CHARS})`;+export async function countStaleFactEmbeddings(engine: Pick<BrainEngine, 'executeRaw'>, model: string, dimensions: number, sourceId?: string) {const [row] = await engine.executeRaw<{ count: number; chars: string }>(`SELECT count(*)::int AS count,COALESCE(sum(length(f.fact)),0)::text AS chars FROM facts fdiff --git a/test/e2e/fact-embedding-truncation-6975-postgres.test.ts b/test/e2e/fact-embedding-truncation-6975-postgres.test.tsnew file mode 100644index 0000000000..f3d8818b24--- /dev/null+++ b/test/e2e/fact-embedding-truncation-6975-postgres.test.ts@@ -0,0 +1,2 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';+await registerPostgresTests(() => import('../fact-embedding-truncation-6975.test.ts'));diff --git a/test/fact-embedding-truncation-6975.test.ts b/test/fact-embedding-truncation-6975.test.tsnew file mode 100644index 0000000000..0c00aeddfe--- /dev/null+++ b/test/fact-embedding-truncation-6975.test.ts@@ -0,0 +1,91 @@+/**+ * #6975: embed() sends at most EMBED_MAX_CHARS (8000) UTF-16 code units of a fact, but the+ * vector is stamped with md5 of the whole fact. md5(fact) stays the freshness key (no stamp+ * change, no re-embed, no extra spend); doctor's fact_take_vectors reports such facts as+ * partially embedded instead of claiming full coverage. Both backends (Postgres through the+ * e2e twin).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { EMBED_MAX_CHARS } from '../src/core/ai/embed-batch-plan.ts';+import { embedStaleFacts } from '../src/core/embed-facts.ts';+import { factTakeVectorsEntry } from '../src/commands/doctor/checks/vector-coverage.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { readFactsEmbeddingDim } from '../src/core/embedding-dim-check.ts';+import { testBackends } from './helpers/test-backends.ts';++const SOURCE = 'truncation-6975';+const MODEL = 'openai:text-embedding-3-small';+const LONG = 'a'.repeat(EMBED_MAX_CHARS + 1);+// Exactly the cap, with characters a misparsed astral range would count.+const EXACT = 'a'.repeat(EMBED_MAX_CHARS - 3) + 'U1\\';+// 8000 code points but 8001 UTF-16 code units: embed() cuts it too.+const ASTRAL = 'a'.repeat(EMBED_MAX_CHARS - 1) + '\u{1F600}';+let calls: string[][] = [];+let DIMS = 0;++const doctor = async (engine: BrainEngine) =>+ (await factTakeVectorsEntry.run({ engine, orphanRatioSourceId: SOURCE, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[])[0];++for (const backend of testBackends()) describe(`fact embedding truncation (${backend})`, () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ if (backend === 'postgres') {+ const { setupDB, getEngine } = await import('./e2e/helpers.ts');+ await setupDB();+ engine = getEngine();+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SOURCE]);+ DIMS = (await readFactsEmbeddingDim(engine)).dims!;+ await engine.setConfig('embedding_model', MODEL);+ await engine.setConfig('embedding_dimensions', String(DIMS));+ });+ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1', [SOURCE]);+ await engine.executeRaw('DELETE FROM sources WHERE id = $1', [SOURCE]);+ if (backend === 'pglite') await engine.disconnect();+ });+ beforeEach(async () => {+ calls = [];+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test-key' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ calls.push([...values]);+ return { values, usage: { tokens: values.length }, warnings: [], embeddings: values.map(() => Array(DIMS).fill(0.25)) };+ }) as never);+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1', [SOURCE]);+ });++ test('a fact over the input cap embeds once, reports partially embedded, and stays fresh', async () => {+ for (const fact of [LONG, EXACT, ASTRAL, 'Alice example joined Acme example.']) {+ await engine.insertFact({ fact, kind: 'fact', confidence: 1, source: 'notes', visibility: 'world', notability: 'medium' }, { source_id: SOURCE });+ }+ const first = await embedStaleFacts(engine, { sourceId: SOURCE, yes: true, maxCostUsd: 1 });+ expect(first).toMatchObject({ embedded: 4, failures: 0, remaining: 0, stopped: 'complete' });+ expect(calls.flat().map(v => v.length).sort((x, y) => x - y)).toEqual([34, EMBED_MAX_CHARS - 1, EMBED_MAX_CHARS, EMBED_MAX_CHARS]);++ const check = await doctor(engine);+ expect(check).toMatchObject({ status: 'ok', details: { facts: { stale: 0, partially_embedded: 2 } } });+ expect(check.message).toContain('2 fact(s) are partially embedded');++ calls = [];+ const second = await embedStaleFacts(engine, { sourceId: SOURCE, yes: true, maxCostUsd: 1 });+ expect(second).toMatchObject({ total_stale: 0, embedded: 0, cost_usd: 0 });+ expect(calls).toEqual([]);+ expect(await doctor(engine)).toMatchObject({ status: 'ok', details: { facts: { partially_embedded: 2 } } });+ });++ test('facts without a current vector are stale, not partially embedded', async () => {+ await engine.insertFact({ fact: LONG, kind: 'fact', confidence: 1, source: 'notes', visibility: 'world', notability: 'medium' }, { source_id: SOURCE });+ expect(await doctor(engine)).toMatchObject({ status: 'warn', details: { facts: { stale: 1, missing: 1, partially_embedded: 0 } } });+ expect(calls).toEqual([]);+ });+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 6a6ec317ac..6647e24452 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2451,6 +2451,7 @@"facts": {"missing": 0,"other_model": 0,+ "partially_embedded": 0,"stale": 0},"model": "voyage:voyage-4",