mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 10:22:34 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89579780e0 | ||
|
|
cf2deedfc6 |
+1
-22
@@ -365,12 +365,6 @@ async function main() {
|
||||
if (def.required && params[key] === undefined) {
|
||||
if (queryHasAlt && key === 'query') continue;
|
||||
const cliName = op.cliHints?.name || op.name;
|
||||
// #2822: when the missing param is the op's stdin-fed one, the usage
|
||||
// line alone is misleading (the positionals may all be present — the
|
||||
// pipe was just empty). Name the real problem.
|
||||
if (op.cliHints?.stdin === key) {
|
||||
console.error(`Error: required "${key}" is missing — stdin was empty or not piped. Pipe content on stdin or pass --${key.replace(/_/g, '-')}.`);
|
||||
}
|
||||
const positional = op.cliHints?.positional || [];
|
||||
const usage = positional.map(p => `<${p}>`).join(' ');
|
||||
console.error(`Usage: gbrain ${cliName} ${usage}`);
|
||||
@@ -767,10 +761,6 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
const params: Record<string, unknown> = {};
|
||||
const positional = op.cliHints?.positional || [];
|
||||
let posIdx = 0;
|
||||
// #2822: track which params came from positionals so a later flag that
|
||||
// silently discards one (`gbrain put CONTENT --slug foo` — CONTENT was
|
||||
// parsed as the slug) gets a stderr warning instead of vanishing.
|
||||
const positionallySet = new Set<string>();
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
@@ -788,20 +778,13 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
if (paramDef?.type === 'boolean') {
|
||||
params[key] = true;
|
||||
} else if (i + 1 < args.length) {
|
||||
if (positionallySet.has(key) && params[key] !== args[i + 1]) {
|
||||
console.error(`Warning: ${arg} overrides the positional <${key}> value ${JSON.stringify(params[key])}.`);
|
||||
}
|
||||
params[key] = args[++i];
|
||||
if (paramDef?.type === 'number') params[key] = Number(params[key]);
|
||||
}
|
||||
} else if (posIdx < positional.length) {
|
||||
const key = positional[posIdx++];
|
||||
const paramDef = op.params[key];
|
||||
if (params[key] !== undefined && params[key] !== (paramDef?.type === 'number' ? Number(arg) : arg)) {
|
||||
console.error(`Warning: positional <${key}> overrides the earlier --${key.replace(/_/g, '-')} value ${JSON.stringify(params[key])}.`);
|
||||
}
|
||||
params[key] = paramDef?.type === 'number' ? Number(arg) : arg;
|
||||
positionallySet.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -813,11 +796,7 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
}
|
||||
// #2822: empty/whitespace-only stdin (cron with no input, broken pipe)
|
||||
// stays UNSET so the required-param check rejects the call instead of
|
||||
// silently writing an empty page (0 chunks, invisible to search and
|
||||
// embed --stale).
|
||||
if (stdinContent.trim().length > 0) params[op.cliHints.stdin] = stdinContent;
|
||||
params[op.cliHints.stdin] = stdinContent;
|
||||
}
|
||||
|
||||
return params;
|
||||
|
||||
+14
-1
@@ -1,5 +1,5 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
|
||||
import { embedBatch, currentEmbeddingSignature, resolveEmbeddingModelLabel } from '../core/embedding.ts';
|
||||
import type { ChunkInput } from '../core/types.ts';
|
||||
import { chunkText } from '../core/chunkers/recursive.ts';
|
||||
import { createProgress, type ProgressReporter } from '../core/progress.ts';
|
||||
@@ -581,11 +581,16 @@ async function embedPage(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label each (re)embedded chunk with the model that actually
|
||||
// produced its vector. Preserved chunks (not re-embedded this pass) keep
|
||||
// their existing model so a mixed-model page isn't relabeled wholesale.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: embeddingMap.get(c.chunk_index),
|
||||
model: embeddingMap.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
|
||||
@@ -717,12 +722,16 @@ async function embedAll(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: stamp the resolved embedding model on (re)embedded chunks;
|
||||
// preserve the existing model on chunks left untouched.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
// Preserve ALL chunks, only update embeddings for stale ones
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: embeddingMap.get(c.chunk_index) ?? undefined,
|
||||
model: embeddingMap.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(page.slug, updated, pageOpts));
|
||||
@@ -1012,11 +1021,15 @@ async function embedAllStale(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label the re-embedded (stale) chunks with the resolved
|
||||
// model; preserve the existing model on the non-stale chunks.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const merged: ChunkInput[] = existing.map(c => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
model: staleIdxToEmbedding.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
}));
|
||||
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
|
||||
|
||||
@@ -48,7 +48,6 @@ const FRONTMATTER_RULE_NAMES: Record<ParseValidationCode, string> = {
|
||||
NESTED_QUOTES: 'frontmatter-nested-quotes',
|
||||
NON_STRING_FIELD: 'frontmatter-non-string-field',
|
||||
EMPTY_FRONTMATTER: 'frontmatter-empty',
|
||||
MULTI_FRONTMATTER: 'frontmatter-multi',
|
||||
};
|
||||
|
||||
/** Codes whose lint findings are fixable by `gbrain frontmatter validate --fix`. */
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput } from './types.ts';
|
||||
import { embedBatchWithBackoff } from '../commands/embed.ts';
|
||||
import { resolveEmbeddingModelLabel } from './embedding.ts';
|
||||
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
|
||||
import { AbortError } from './abort-check.ts';
|
||||
|
||||
@@ -200,11 +201,17 @@ export async function embedStaleForSource(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// #1717: label re-embedded chunks with the model that produced the
|
||||
// vector; preserved chunks keep their existing model. Without this,
|
||||
// upsertChunks falls back to DEFAULT_EMBEDDING_MODEL for every chunk
|
||||
// (the same mislabel the embed.ts paths fixed).
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
const merged: ChunkInput[] = existing.map((c) => ({
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
embedding: staleIdxToEmbedding.get(c.chunk_index) ?? undefined,
|
||||
model: staleIdxToEmbedding.has(c.chunk_index) && embedModelLabel ? embedModelLabel : c.model,
|
||||
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
|
||||
// Carry through per-chunk metadata. upsertChunks writes these as
|
||||
// EXCLUDED.<col> (not COALESCE), so omitting them here resets image
|
||||
|
||||
@@ -113,6 +113,21 @@ export async function embedBatch(
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the embedding model label (`provider:model`) to stamp onto
|
||||
* `content_chunks.model`, so each chunk records the model that actually
|
||||
* produced its vector instead of the engine's hardcoded default (#1717).
|
||||
* Returns undefined if the gateway is unconfigured; callers then fall back
|
||||
* to the chunk's existing model rather than mislabeling it.
|
||||
*/
|
||||
export function resolveEmbeddingModelLabel(): string | undefined {
|
||||
try {
|
||||
return gatewayGetModel();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Currently-configured embedding model (short form without provider prefix). */
|
||||
export function getEmbeddingModelName(): string {
|
||||
return gatewayGetModel().split(':').slice(1).join(':') || 'text-embedding-3-large';
|
||||
|
||||
+12
-23
@@ -8,7 +8,7 @@ import { chunkText } from './chunkers/recursive.ts';
|
||||
import { chunkCodeText, chunkCodeTextFull, detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';
|
||||
import { findChunkForOffset } from './chunkers/edge-extractor.ts';
|
||||
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
|
||||
import { embedBatch, embedMultimodal, currentEmbeddingSignature, resolveEmbeddingModelLabel } from './embedding.ts';
|
||||
import { slugifyPath, slugifyCodePath, isCodeFilePath } from './sync.ts';
|
||||
import type { ChunkInput, PageInput, PageType } from './types.ts';
|
||||
import { computeEffectiveDate } from './effective-date.ts';
|
||||
@@ -301,17 +301,6 @@ export async function importFromContent(
|
||||
// silently fabricated a duplicate at (default, slug) — causing later
|
||||
// bare-slug subqueries (getTags, deleteChunks, etc.) to crash with 21000.
|
||||
const sourceId = opts.sourceId;
|
||||
// #2822: reject empty/whitespace-only content before any work happens. An
|
||||
// empty page writes 0 chunks — invisible to search AND to `embed --stale`
|
||||
// (nothing to embed), so the mistake never surfaces. Empty content is
|
||||
// always a caller bug (empty piped stdin, bad shell substitution). Thrown
|
||||
// (not returned) so every wrapper site surfaces the message, matching the
|
||||
// ContentSanityBlockError flow.
|
||||
if (content.trim().length === 0) {
|
||||
throw new Error(
|
||||
`Content for "${slug}" is empty; refusing to write an empty page (0 chunks would be invisible to search and embed --stale).`,
|
||||
);
|
||||
}
|
||||
// Reject oversized payloads before any parsing, chunking, or embedding happens.
|
||||
// Uses Buffer.byteLength to count UTF-8 bytes the same way disk size would,
|
||||
// so the network path behaves identically to the file path.
|
||||
@@ -325,17 +314,7 @@ export async function importFromContent(
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseMarkdown(content, slug + '.md', { activePack: opts.activePack, validate: true });
|
||||
|
||||
// #2743: reject stacked frontmatter (the double-put corruption class —
|
||||
// already-serialized markdown re-wrapped in fresh frontmatter). gray-matter
|
||||
// parses only the first block; the second would land verbatim in the body
|
||||
// and poison every subsequent round-trip. Only MULTI_FRONTMATTER rejects
|
||||
// here — the other validation codes keep their lint-only semantics.
|
||||
const multiFm = parsed.errors?.find(e => e.code === 'MULTI_FRONTMATTER');
|
||||
if (multiFm) {
|
||||
throw new Error(`MULTI_FRONTMATTER: ${multiFm.message} (slug "${slug}", line ${multiFm.line})`);
|
||||
}
|
||||
const parsed = parseMarkdown(content, slug + '.md', { activePack: opts.activePack });
|
||||
|
||||
// v0.42 (#1699 trust boundary): strip gate-owned markers from UNTRUSTED
|
||||
// input. parseMarkdown preserves every frontmatter key except type/title/
|
||||
@@ -737,8 +716,12 @@ export async function importFromContent(
|
||||
? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))
|
||||
: chunks.map((c) => c.chunk_text);
|
||||
const embeddings = await embedBatch(wrappedTexts);
|
||||
// #1717: label each chunk with the model that actually produced its
|
||||
// vector, not the engine's hardcoded default.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
chunks[i].embedding = embeddings[i];
|
||||
if (embedModelLabel) chunks[i].model = embedModelLabel;
|
||||
// token_count tracks the wrapped string length so cost reporting
|
||||
// reflects what we actually sent to the embedder.
|
||||
chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);
|
||||
@@ -1162,7 +1145,10 @@ export async function importCodeFile(
|
||||
const matched = existingByKey.get(key);
|
||||
if (matched && matched.embedding) {
|
||||
// Reuse the existing embedding verbatim. No API call, no cost.
|
||||
// #1717: carry the existing model label along with the reused vector
|
||||
// so the upsert doesn't relabel it with the engine default.
|
||||
chunks[i]!.embedding = matched.embedding as Float32Array;
|
||||
chunks[i]!.model = matched.model ?? undefined;
|
||||
chunks[i]!.token_count = matched.token_count ?? undefined;
|
||||
} else {
|
||||
needsEmbedIndexes.push(i);
|
||||
@@ -1174,9 +1160,12 @@ export async function importCodeFile(
|
||||
try {
|
||||
const textsToEmbed = needsEmbedIndexes.map((i) => chunks[i]!.chunk_text);
|
||||
const embeddings = await embedBatch(textsToEmbed);
|
||||
// #1717: stamp the model that produced these vectors.
|
||||
const embedModelLabel = resolveEmbeddingModelLabel();
|
||||
for (let j = 0; j < needsEmbedIndexes.length; j++) {
|
||||
const i = needsEmbedIndexes[j]!;
|
||||
chunks[i]!.embedding = embeddings[j]!;
|
||||
if (embedModelLabel) chunks[i]!.model = embedModelLabel;
|
||||
chunks[i]!.token_count = Math.ceil(chunks[i]!.chunk_text.length / 4);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
|
||||
+1
-46
@@ -11,8 +11,7 @@ export type ParseValidationCode =
|
||||
| 'NULL_BYTES'
|
||||
| 'NESTED_QUOTES'
|
||||
| 'NON_STRING_FIELD'
|
||||
| 'EMPTY_FRONTMATTER'
|
||||
| 'MULTI_FRONTMATTER';
|
||||
| 'EMPTY_FRONTMATTER';
|
||||
|
||||
export interface ParseValidationError {
|
||||
code: ParseValidationCode;
|
||||
@@ -332,50 +331,6 @@ function collectValidationErrors(
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 9. MULTI_FRONTMATTER (#2743) — a second ---…--- block right after the
|
||||
// closing fence is stacked frontmatter (the double-put corruption class:
|
||||
// already-serialized markdown re-wrapped in fresh frontmatter).
|
||||
// gray-matter parses only the first block and silently leaves the second
|
||||
// in the body. Heuristic: first non-empty line after the close is `---`,
|
||||
// a later `---` closes it, EVERY line between is frontmatter-shaped
|
||||
// (YAML `key:`, `- ` list item, `#` comment, indented continuation, or
|
||||
// blank — the issue's "stop at the first non-frontmatter character"
|
||||
// spec), and at least one is a `key:` line. A lone `---` stays a
|
||||
// markdown horizontal rule, and an hrule followed by prose — even
|
||||
// colon-prefixed prose like `Note: …` mixed with plain lines — is body
|
||||
// content, not a stacked block.
|
||||
let afterClose = closeLine + 1;
|
||||
while (afterClose < lines.length && lines[afterClose].trim().length === 0) afterClose++;
|
||||
if (afterClose < lines.length && lines[afterClose].trim() === '---') {
|
||||
let secondClose = -1;
|
||||
for (let i = afterClose + 1; i < lines.length; i++) {
|
||||
const trimmed = lines[i].trim();
|
||||
if (trimmed === '---') {
|
||||
secondClose = i;
|
||||
break;
|
||||
}
|
||||
const yamlShaped =
|
||||
trimmed.length === 0 ||
|
||||
/^[A-Za-z_][\w-]*\s*:/.test(trimmed) ||
|
||||
trimmed.startsWith('- ') ||
|
||||
trimmed === '-' ||
|
||||
trimmed.startsWith('#') ||
|
||||
/^\s/.test(lines[i]);
|
||||
if (!yamlShaped) break; // first non-frontmatter line → body prose, not a stacked block
|
||||
}
|
||||
if (
|
||||
secondClose > afterClose + 1 &&
|
||||
lines.slice(afterClose + 1, secondClose).some(l => /^\s*[A-Za-z_][\w-]*\s*:/.test(l))
|
||||
) {
|
||||
errors.push({
|
||||
code: 'MULTI_FRONTMATTER',
|
||||
message:
|
||||
'Stacked frontmatter: a second ---…--- block follows the frontmatter (double-put corruption); merge into a single frontmatter block',
|
||||
line: afterClose + 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-70
@@ -1,8 +1,4 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { join, resolve } from 'path';
|
||||
import { mkdtempSync, rmSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { parseOpArgs } from '../src/cli.ts';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
|
||||
@@ -24,70 +20,5 @@ describe('parseOpArgs', () => {
|
||||
source_id: 'gstack-code-repo-0e4763c9',
|
||||
});
|
||||
});
|
||||
|
||||
describe('positional/flag overwrite warning (#2822)', () => {
|
||||
const errors: string[] = [];
|
||||
const origError = console.error;
|
||||
const captureErrors = () => {
|
||||
console.error = (...args: unknown[]) => errors.push(args.join(' '));
|
||||
};
|
||||
afterEach(() => {
|
||||
console.error = origError;
|
||||
errors.length = 0;
|
||||
});
|
||||
|
||||
test('a flag that overwrites a positional value warns to stderr', () => {
|
||||
captureErrors();
|
||||
const params = parseOpArgs(operationsByName.query, ['positional text', '--query', 'flag text']);
|
||||
expect(params.query).toBe('flag text');
|
||||
expect(errors.some(e => e.includes('Warning') && e.includes('--query'))).toBe(true);
|
||||
});
|
||||
|
||||
test('a positional that overwrites an earlier flag value warns to stderr', () => {
|
||||
captureErrors();
|
||||
const params = parseOpArgs(operationsByName.query, ['--query', 'flag text', 'positional text']);
|
||||
expect(params.query).toBe('positional text');
|
||||
expect(errors.some(e => e.includes('Warning') && e.includes('<query>'))).toBe(true);
|
||||
});
|
||||
|
||||
test('no warning when flag and positional agree', () => {
|
||||
captureErrors();
|
||||
parseOpArgs(operationsByName.query, ['same', '--query', 'same']);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('gbrain put — empty non-TTY stdin rejects (#2822)', () => {
|
||||
const REPO = resolve(import.meta.dir, '..');
|
||||
const CLI = join(REPO, 'src', 'cli.ts');
|
||||
|
||||
const runPut = (input: string) => {
|
||||
// Isolated HOME so a regression can never write into a real brain.
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-put-empty-'));
|
||||
try {
|
||||
return spawnSync('bun', [CLI, 'put', 'inbox/empty-stdin-test'], {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
input,
|
||||
encoding: 'utf-8',
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' },
|
||||
});
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
test('empty stdin exits 1 and names the missing content param', () => {
|
||||
const res = runPut('');
|
||||
expect(res.status).toBe(1);
|
||||
expect(res.stderr).toContain('content');
|
||||
expect(res.stderr).toContain('stdin');
|
||||
}, 90_000);
|
||||
|
||||
test('whitespace-only stdin also exits 1', () => {
|
||||
const res = runPut(' \n\t\n');
|
||||
expect(res.status).toBe(1);
|
||||
expect(res.stderr).toContain('stdin');
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { embedStaleForSource } from '../src/core/embed-stale.ts';
|
||||
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
|
||||
import type { ChunkInput } from '../src/core/types.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
@@ -276,4 +277,49 @@ describe('embedStaleForSource', () => {
|
||||
// The stale text row actually got its embedding.
|
||||
expect(txtRow.embedded_at).not.toBeNull();
|
||||
});
|
||||
|
||||
// #1717: the backfill path must label re-embedded chunks with the model
|
||||
// that produced the vector, and preserve the existing label on chunks it
|
||||
// did not touch (before the fix, both were reset to the engine default).
|
||||
test('labels re-embedded chunks with the gateway model, preserves untouched labels (#1717)', async () => {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
env: { OPENAI_API_KEY: 'sk-test-embed-stale-1717' },
|
||||
});
|
||||
try {
|
||||
await engine.putPage('notes/model-label', {
|
||||
type: 'note',
|
||||
title: 'model-label',
|
||||
compiled_truth: '# model-label\n\nseeded',
|
||||
});
|
||||
await engine.upsertChunks('notes/model-label', [
|
||||
{
|
||||
chunk_index: 0,
|
||||
chunk_text: 'already embedded elsewhere',
|
||||
chunk_source: 'compiled_truth',
|
||||
embedding: new Float32Array(1536).fill(0.01),
|
||||
model: 'voyage:voyage-3',
|
||||
token_count: 4,
|
||||
},
|
||||
{
|
||||
chunk_index: 1,
|
||||
chunk_text: 'stale chunk needing embed',
|
||||
chunk_source: 'compiled_truth',
|
||||
token_count: 5,
|
||||
embedding: undefined, // stale
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await embedStaleForSource(engine, 'default', { embedFn: fakeEmbedFn });
|
||||
expect(result.embedded).toBe(1);
|
||||
|
||||
const after = await engine.getChunks('notes/model-label');
|
||||
const preserved = after.find((c) => c.chunk_index === 0)!;
|
||||
const reembedded = after.find((c) => c.chunk_index === 1)!;
|
||||
expect(reembedded.model).toBe('openai:text-embedding-3-large');
|
||||
expect(preserved.model).toBe('voyage:voyage-3');
|
||||
} finally {
|
||||
resetGateway();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,6 +37,8 @@ mock.module('../src/core/embedding.ts', () => ({
|
||||
// setPageEmbeddingSignature / invalidateStaleSignatureEmbeddings resolve to
|
||||
// null via the Proxy default, so the signature value is inert here.
|
||||
currentEmbeddingSignature: () => 'test:model:1536',
|
||||
// #1717: embed paths stamp this label on (re)embedded chunks.
|
||||
resolveEmbeddingModelLabel: () => 'openai:text-embedding-3-large',
|
||||
}));
|
||||
|
||||
// Import AFTER mocking.
|
||||
@@ -803,3 +805,34 @@ describe('embedAllStale --source threading (D7)', () => {
|
||||
expect((firstCallOpts as { sourceId?: string }).sourceId).toBe('media-corpus');
|
||||
});
|
||||
});
|
||||
|
||||
// #1717: content_chunks.model must record the model that actually produced
|
||||
// each vector, not the gateway/engine default.
|
||||
describe('content_chunks.model labeling (#1717)', () => {
|
||||
test('stamps the resolved embedding model on re-embedded chunks, preserves it on untouched chunks', async () => {
|
||||
let upserted: any[] | undefined;
|
||||
// Chunk 0 is stale (no embedded_at) → gets re-embedded this pass.
|
||||
// Chunk 1 is already embedded with a DIFFERENT model → must be preserved,
|
||||
// not relabeled to the current model.
|
||||
const chunks = [
|
||||
{ chunk_index: 0, chunk_text: 'a', chunk_source: 'compiled_truth', embedded_at: null, model: 'zeroentropyai:zembed-1', token_count: 1 },
|
||||
{ chunk_index: 1, chunk_text: 'b', chunk_source: 'compiled_truth', embedded_at: '2026-01-01', embedding: new Float32Array(1536), model: 'voyage:voyage-3', token_count: 1 },
|
||||
];
|
||||
const engine = mockEngine({
|
||||
getPage: async () => ({ slug: 'notes/x', compiled_truth: 'a', timeline: '', source_id: 'default' }),
|
||||
getChunks: async () => chunks,
|
||||
upsertChunks: async (_slug: string, c: any[]) => { upserted = c; },
|
||||
setPageEmbeddingSignature: async () => null,
|
||||
});
|
||||
|
||||
await runEmbedCore(engine, { slugs: ['notes/x'] });
|
||||
|
||||
expect(upserted).toBeDefined();
|
||||
const byIdx = Object.fromEntries(upserted!.map(c => [c.chunk_index, c]));
|
||||
// Re-embedded chunk carries the model that produced its vector (was
|
||||
// mislabeled with the default before the fix).
|
||||
expect(byIdx[0].model).toBe('openai:text-embedding-3-large');
|
||||
// Untouched chunk keeps its original model — no wholesale relabel.
|
||||
expect(byIdx[1].model).toBe('voyage:voyage-3');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -708,32 +708,3 @@ body unchanged
|
||||
expect(shortCircuited).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('importFromContent — empty content guard (#2822)', () => {
|
||||
test('empty string throws instead of writing an invisible 0-chunk page', async () => {
|
||||
const engine = mockEngine();
|
||||
await expect(importFromContent(engine, 'inbox/empty', '', { noEmbed: true })).rejects.toThrow(/empty/i);
|
||||
expect((engine as any)._calls.find((c: any) => c.method === 'putPage')).toBeUndefined();
|
||||
});
|
||||
|
||||
test('whitespace-only content throws', async () => {
|
||||
const engine = mockEngine();
|
||||
await expect(importFromContent(engine, 'inbox/ws', ' \n\t \n', { noEmbed: true })).rejects.toThrow(/empty/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('importFromContent — stacked frontmatter rejection (#2743)', () => {
|
||||
test('double-put shaped content (two ---…--- blocks) throws MULTI_FRONTMATTER', async () => {
|
||||
const engine = mockEngine();
|
||||
const md = '---\ntitle: outer\n---\n\n---\ntitle: inner\ntype: concept\n---\n\nreal body';
|
||||
await expect(importFromContent(engine, 'inbox/double', md, { noEmbed: true })).rejects.toThrow(/MULTI_FRONTMATTER/);
|
||||
expect((engine as any)._calls.find((c: any) => c.method === 'putPage')).toBeUndefined();
|
||||
});
|
||||
|
||||
test('normal content with horizontal rules in the body still imports', async () => {
|
||||
const engine = mockEngine();
|
||||
const md = '---\ntitle: ok\ntype: concept\n---\n\nprose before\n\n---\n\nprose after the rule';
|
||||
const result = await importFromContent(engine, 'inbox/hrule', md, { noEmbed: true });
|
||||
expect(result.status).toBe('imported');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,4 +73,21 @@ describe('importFromContent embedding_signature stamping (F1)', () => {
|
||||
await importFromContent(engine, 'concepts/unstamped', '# Unstamped\n\nbody content.', { noEmbed: true });
|
||||
expect(await signatureOf('concepts/unstamped')).toBeNull();
|
||||
});
|
||||
|
||||
// #1717: content_chunks.model must record the model that produced the
|
||||
// vector (the configured gateway model), not the engine's hardcoded
|
||||
// default. The gateway here is configured to openai:text-embedding-3-large,
|
||||
// which differs from DEFAULT_EMBEDDING_MODEL — so this fails without the
|
||||
// import-path model stamping.
|
||||
test('inline embed labels content_chunks.model with the configured model (#1717)', async () => {
|
||||
await importFromContent(engine, 'concepts/labeled', '# Labeled\n\nsome body content to chunk and embed.', {});
|
||||
const rows = await engine.executeRaw<{ model: string }>(
|
||||
`SELECT cc.model FROM content_chunks cc
|
||||
JOIN pages p ON p.id = cc.page_id
|
||||
WHERE p.slug = $1 AND p.source_id = 'default'`,
|
||||
['concepts/labeled'],
|
||||
);
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
for (const r of rows) expect(r.model).toBe('openai:text-embedding-3-large');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -256,56 +256,6 @@ body`;
|
||||
});
|
||||
});
|
||||
|
||||
describe('MULTI_FRONTMATTER (#2743)', () => {
|
||||
test('stacked frontmatter immediately after the close fence', () => {
|
||||
const md = `${fence}\ntitle: outer\n${fence}\n${fence}\ntitle: inner\ntype: concept\n${fence}\n\nbody`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('stacked frontmatter with a blank line between blocks (serializeMarkdown shape)', () => {
|
||||
const md = `${fence}\ntitle: outer\n${fence}\n\n${fence}\ntitle: inner\n${fence}\n\nbody`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('horizontal rules in the body are NOT flagged', () => {
|
||||
const md = `${fence}\ntitle: ok\n${fence}\n\nsome prose\n\n${fence}\n\nmore prose\n\n${fence}\n\nend`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('hrule pair at body start without YAML-shaped lines is NOT flagged', () => {
|
||||
const md = `${fence}\ntitle: ok\n${fence}\n\n${fence}\n\nplain prose between rules\n\n${fence}\n\nend`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('timeline sentinel form is NOT flagged', () => {
|
||||
const md = `${fence}\ntitle: ok\n${fence}\n\nbody text\n\n${fence}\n\n## Timeline\n- 2024-01-01: thing`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('body hrule + colon-prefixed prose (`Note: …`) mixed with plain lines is NOT flagged', () => {
|
||||
const md = `${fence}\ntitle: ok\ntype: concept\n${fence}\n\n${fence}\n\nNote: remember to follow up\n\nlots of plain prose here\n\n${fence}\n\nmore prose`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('fence pairing stops at the first non-frontmatter line (no far-fence pairing across prose)', () => {
|
||||
const md = `${fence}\ntitle: ok\n${fence}\n\n${fence}\n\n${'plain prose line\n'.repeat(40)}TODO: fix the widget\n${'more prose\n'.repeat(40)}${fence}\nend`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
|
||||
test('stacked block with list-valued keys is still flagged', () => {
|
||||
const md = `${fence}\ntitle: outer\n${fence}\n\n${fence}\ntitle: inner\ntags:\n - a\n - b\n${fence}\n\nbody`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
expect(parsed.errors!.map(e => e.code)).toContain('MULTI_FRONTMATTER');
|
||||
});
|
||||
});
|
||||
|
||||
test('error.line is set for line-bearing errors', () => {
|
||||
const md = `${fence}\ntype: concept\n${fence}\n# Heading inline\n\nbody\x00drop`;
|
||||
const parsed = parseMarkdown(md, undefined, { validate: true });
|
||||
|
||||
Reference in New Issue
Block a user