Compare commits

..
Author SHA1 Message Date
Garry TanandClaude Fable 5 52fffc7ecc fix(facts): seed phase B backfill row_nums past the DB max (#2044 class)
phaseBFenceFacts appended at fence-max+1 with no DB seeding, so on a
diverged page (stamped DB rows + missing fence at the resolved path —
the same divergence class the writeFactsToFence fix handles) the
post-rename UPDATE hit idx_facts_fence_key, the page failed, and the
already-renamed fence disagreed with the DB while the row_num-NULL
backlog persisted. Seed appended row_nums from MAX(fence max, DB max)
per (source_id, slug), mirroring the fence-write fix. Repro test added.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 11:46:22 -07:00
Garry TanandClaude Fable 5 039b97df36 fix(facts): route exit codes through setCliExitVerdict
The cli-exit-verdict-pin guard requires every exit-code write in src/
to go through setCliExitVerdict (raw process.exitCode assignments get
zeroed by the owned-verdict read on PGLite). Replace the two raw
assignments in the new facts command.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 10:50:45 -07:00
Garry TanandClaude Fable 5 2bb3424863 fix(facts): idempotent fence deposits + re-runnable fence-backfill command
Two fixes for the remote extract_facts deposit path:

#2044 — a second deposit to an already-fenced page could throw
idx_facts_fence_key and roll back the whole batch when fence and DB
row_nums diverged (e.g. legacy wrong-path fence writes). writeFactsToFence
now seeds the next row_num from MAX(fence max, DB max(row_num)) for the
(source_id, slug) pair, and insertFacts in BOTH engines adds
ON CONFLICT (source_id, source_markdown_slug, row_num) WHERE row_num IS
NOT NULL DO NOTHING so a residual collision skips one row instead of
failing the batch.

#1867 — row_num-NULL backlogs (remote deposits that predate the fence
backstop) had no remedy: the fence backfill lived only inside the one-shot
v0_32_2 migration, and the cycle guard pointed at `gbrain apply-migrations
--yes`, which never re-runs a completed migration. phaseBFenceFacts (already
idempotent on row_num IS NULL) is now exported and exposed as
`gbrain facts fence-backfill [--dry-run]`; the guard message points at it.
The backfill also routes page paths through resolvePageFilePath so
non-default sources fence into the same path the fence-write backstop uses.

Fixes #2044
Fixes #1867

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:45:53 -07:00
15 changed files with 352 additions and 314 deletions
+14 -12
View File
@@ -54,7 +54,7 @@ export function bigintToStringReplacer(_key: string, value: unknown): unknown {
}
// CLI-only commands that bypass the operation layer
export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'skillopt', 'quarantine', 'self-upgrade', 'advisor', 'watch', 'reindex-search-vector']);
export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'facts', 'cache', 'ze-switch', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'skillopt', 'quarantine', 'self-upgrade', 'advisor', 'watch', 'reindex-search-vector']);
// CLI-only commands whose handlers print their own --help text. These are
// excluded from the generic short-circuit so detailed per-command and
// per-subcommand usage stays reachable.
@@ -808,20 +808,12 @@ async function makeContext(engine: BrainEngine, params: Record<string, unknown>)
// 'default'. Wrapped in try/catch so a doctor / single-source brain that
// never set up sources still returns 'default' silently.
let sourceId: string | undefined;
// #2561: when the source resolved via a NON-explicit tier (path-match /
// brain default / sole-non-default / seed default), unqualified search-shaped
// reads span every `config.federated = true` source. Computed here (the
// trusted local boundary) and consumed by federatedSearchScope in
// operations.ts, which additionally gates on ctx.remote === false.
let localFederated: string[] | undefined;
try {
const { resolveSourceWithTier, localFederatedSourceIds } = await import('./core/source-resolver.ts');
const { resolveSourceId } = await import('./core/source-resolver.ts');
// params.source is set when a CLI flag was parsed for the op (rare; most
// CLI ops don't take --source). Falls through to env/dotfile/path-match.
const explicit = (params.source as string | undefined) ?? null;
const resolved = await resolveSourceWithTier(engine, explicit);
sourceId = resolved.source_id;
localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
sourceId = await resolveSourceId(engine, explicit);
} catch {
// Source resolution failed (e.g. sources table doesn't exist on a fresh
// pre-init brain). Leave sourceId unset; engine read methods fall through
@@ -842,7 +834,6 @@ async function makeContext(engine: BrainEngine, params: Record<string, unknown>)
// table). Matches dispatch.ts's auto-fill so the contract holds across
// every transport.
sourceId: sourceId ?? 'default',
...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
};
}
@@ -1000,6 +991,8 @@ const THIN_CLIENT_REFUSED_COMMANDS = new Set([
// hint pointing at the routable MCP tools; per-subcommand splits are
// a v0.31.x follow-up TODO.
'takes', 'sources',
// #1867: fence-backfill edits local .md fences + stamps the local DB.
'facts',
// v0.32 thin-client routing audit (Codex round 2 findings #2, #4):
// - `pages` purge-deleted is admin+localOnly (operations.ts:856-864)
// - `files` list / file_url MCP ops are localOnly (operations.ts:1769-1879)
@@ -1035,6 +1028,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
migrate: "migrate runs on the host's local engine. Run on the host machine.",
'apply-migrations': 'schema migrations run on the host. SSH and run there.',
'repair-jsonb': 'repair-jsonb operates on the local DB only.',
facts: 'facts fence-backfill edits local entity-page fences. Run on the host machine.',
integrity: 'integrity scans local files. Run on the host machine.',
serve: 'serve starts a server. Run on the host, not the thin client.',
dream: 'dream runs the autopilot cycle on the host. `gbrain remote ping` queues one. (Native `gbrain dream` thin-client routing planned for v0.31.2.)',
@@ -1864,6 +1858,13 @@ async function handleCliOnly(command: string, args: string[]) {
await runEdgesBackfill(engine, args);
break;
}
case 'facts': {
// #1867 — re-runnable fence-backfill for row_num-NULL legacy fact
// rows (idempotent v0_32_2 phase B, exposed as an operator command).
const { runFactsCommand } = await import('./commands/facts.ts');
await runFactsCommand(engine, args);
break;
}
case 'whoknows': {
// v0.33 (Issue #?): expertise + relationship-proximity routing.
// MCP op `find_experts` (read-scoped) backs the same code path; CLI
@@ -2344,6 +2345,7 @@ TOOLS
check-backlinks <check|fix> [dir] Find/fix missing back-links across brain
lint <dir|file> [--fix] Catch LLM artifacts, placeholder dates, bad frontmatter
orphans [--json] [--count] Find pages with no inbound wikilinks
facts fence-backfill [--dry-run] Fence legacy fact rows (row_num NULL) onto entity pages
salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience
anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)
transcripts recent [--days N] v0.29: recent raw .txt transcripts (local-only)
+48
View File
@@ -0,0 +1,48 @@
/**
* gbrain facts — fact-store maintenance surface (#1867).
*
* `fence-backfill` re-runs the v0_32_2 fence-backfill phase on demand.
* Remote `extract_facts` deposits that predate the fence-write backstop
* (and any legacy DB-only insert) leave `row_num IS NULL` rows that the
* cycle extract_facts guard refuses to reconcile past — previously the
* only remedy was the one-shot v0_32_2 migration, which the ledger marks
* complete and never re-runs. The phase is idempotent (only touches
* `row_num IS NULL` rows), so exposing it as a command is safe to re-run
* any time the backlog reappears.
*/
import type { BrainEngine } from '../core/engine.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { phaseBFenceFacts } from './migrations/v0_32_2.ts';
function printHelp(): void {
process.stderr.write(
`Usage: gbrain facts fence-backfill [--dry-run]\n\n` +
`Fence-backfill: appends every legacy fact row (row_num IS NULL) to its\n` +
`entity page's \`## Facts\` fence and stamps row_num + source_markdown_slug\n` +
`back onto the DB row. Idempotent — re-runs only pick up rows still\n` +
`missing a fence assignment. Clears the backlog that makes the cycle's\n` +
`extract_facts phase skip fence→DB reconciliation.\n\n` +
` --dry-run report what would be fenced; no FS or DB writes\n`,
);
}
export async function runFactsCommand(engine: BrainEngine, args: string[]): Promise<void> {
const sub = args[0];
if (!sub || sub === '--help' || sub === '-h') {
printHelp();
return;
}
if (sub !== 'fence-backfill') {
process.stderr.write(`Unknown facts subcommand: ${sub}\n`);
printHelp();
setCliExitVerdict(1);
return;
}
const dryRun = args.includes('--dry-run');
const result = await phaseBFenceFacts(engine, { dryRun });
process.stderr.write(
`fence-backfill: ${result.status}${result.detail ? `${result.detail}` : ''}\n`,
);
if (result.status === 'failed') setCliExitVerdict(1);
}
+32 -4
View File
@@ -39,6 +39,7 @@ import type { BrainEngine } from '../../core/engine.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
import { upsertFactRow, parseFactsFence } from '../../core/facts-fence.ts';
import { resolvePageFilePath } from '../../core/markdown.ts';
let testEngineOverride: BrainEngine | null = null;
export function __setTestEngineOverride(engine: BrainEngine | null): void {
@@ -148,9 +149,16 @@ function isLocalPathDirty(localPath: string): boolean {
}
}
async function phaseBFenceFacts(
/**
* Exported (not just via `__testing`) because `gbrain facts fence-backfill`
* (#1867) re-runs this phase on demand: remote `extract_facts` deposits that
* predate the fence-write backstop leave row_num-NULL rows the cycle guard
* refuses to reconcile past. The phase is idempotent (only touches
* `row_num IS NULL` rows), so re-running is always safe.
*/
export async function phaseBFenceFacts(
engine: BrainEngine | null,
opts: OrchestratorOpts,
opts: Pick<OrchestratorOpts, 'dryRun'>,
): Promise<OrchestratorPhaseResult> {
if (opts.dryRun) {
// Dry-run: report what WOULD happen without touching FS or DB.
@@ -238,7 +246,11 @@ async function phaseBFenceFacts(
for (const [key, group] of groups) {
const [sourceId, entitySlug] = key.split('\0');
const localPath = localPathById.get(sourceId)!;
const filePath = join(localPath, `${entitySlug}.md`);
// resolvePageFilePath, NOT a bare join — non-default sources fence
// into `<local_path>/.sources/<id>/<slug>.md`, the same path the
// fence-write backstop and put_page write-through compute. A bare
// join here diverges fence and DB for non-default sources (#2044).
const filePath = resolvePageFilePath(localPath, entitySlug, sourceId);
const tmpPath = `${filePath}.tmp`;
try {
@@ -269,6 +281,21 @@ async function phaseBFenceFacts(
const existingFence = parseFactsFence(body);
const existingKeySet = new Set(existingFence.facts.map(f => `${f.claim}\0${f.source ?? ''}`));
// Seed appended row_nums from MAX(fence max, DB max) — same #2044
// divergence guard as writeFactsToFence. When the fence at the
// resolved path is missing/behind but the DB already holds stamped
// rows for this slug (legacy wrong-path fence writes), fence-max+1
// collides with idx_facts_fence_key on the post-rename UPDATE,
// failing the page and leaving fence and DB disagreeing.
const dbMaxRows = await engine.executeRaw<{ max: number | string | null }>(
`SELECT MAX(row_num) AS max FROM facts
WHERE source_id = $1 AND source_markdown_slug = $2`,
[sourceId, entitySlug],
);
const dbMaxRowNum = Number(dbMaxRows[0]?.max ?? 0) || 0;
const fenceMaxRowNum = existingFence.facts.reduce((m, f) => Math.max(m, f.rowNum), 0);
let nextRowNum = Math.max(fenceMaxRowNum, dbMaxRowNum) + 1;
const assignments: Array<{ id: string; row_num: number }> = [];
for (const row of group) {
const key = `${row.fact}\0${row.source ?? ''}`;
@@ -291,6 +318,7 @@ async function phaseBFenceFacts(
.toISOString().slice(0, 10)
: undefined;
const { body: updated, rowNum } = upsertFactRow(body, {
rowNum: nextRowNum++,
claim: row.fact,
kind: row.kind,
confidence: row.confidence,
@@ -381,7 +409,7 @@ async function phaseCVerify(
for (const g of groups) {
const localPath = localPathById.get(g.source_id);
if (!localPath) continue;
const filePath = join(localPath, `${g.source_markdown_slug}.md`);
const filePath = resolvePageFilePath(localPath, g.source_markdown_slug, g.source_id);
if (!existsSync(filePath)) {
mismatches.push(`${g.source_markdown_slug} (file missing)`);
continue;
+5 -3
View File
@@ -176,9 +176,11 @@ export async function runExtractFacts(
if (legacyCount > 0) {
result.guardTriggered = true;
result.warnings.push(
`extract_facts: ${legacyCount} legacy v0.31 fact rows pending fence backfill. ` +
`Run \`gbrain apply-migrations --yes\` to complete v0_32_2 before this phase ` +
`can safely reconcile fence → DB.`,
`extract_facts: ${legacyCount} legacy fact rows pending fence backfill ` +
`(row_num IS NULL — v0.31 rows or remote extract_facts deposits that ` +
`predate the fence backstop). Run \`gbrain facts fence-backfill\` ` +
`(idempotent, re-runnable) before this phase can safely reconcile ` +
`fence → DB.`,
);
return result;
}
+7 -6
View File
@@ -1739,13 +1739,14 @@ export interface BrainEngine {
* single-row supersede flow because fence reconciliation is the canonical
* source-of-truth direction, not the consolidator path.
*
* Insertion is atomic per call: all rows commit in a single transaction
* or none commit (the transaction rolls back on any constraint
* violation, e.g. the v51 partial UNIQUE index on
* `(source_id, source_markdown_slug, row_num)`).
* Insertion runs in a single transaction. A collision on the v51
* partial UNIQUE index `(source_id, source_markdown_slug, row_num)`
* skips ONLY that row (ON CONFLICT DO NOTHING, #2044) — the rest of
* the batch still commits, so a redundant deposit against an
* already-indexed fence row is idempotent instead of a hard failure.
*
* Returns the inserted ids in input-order so callers can correlate
* fence-row → DB-id without a separate lookup.
* Returns the inserted ids in input-order (colliding rows omitted) so
* callers can correlate fence-row → DB-id without a separate lookup.
*/
insertFacts(
rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+17 -1
View File
@@ -218,11 +218,27 @@ export async function writeFactsToFence(
}
// 2. Upsert each fact onto the fence in input order. row_num
// monotonically increases (max-existing + 1 per call, append-only).
// monotonically increases, append-only, seeded from the MAX of
// the fence and the DB index (#2044): when fence and DB have
// diverged (e.g. legacy writes that stamped DB rows against a
// fence at a path this code no longer reads), fence-max+1 can
// collide with an existing DB row_num, tripping
// idx_facts_fence_key and rolling back the whole batch.
const dbMaxRows = await engine.executeRaw<{ max: number | string | null }>(
`SELECT MAX(row_num) AS max FROM facts
WHERE source_id = $1 AND source_markdown_slug = $2`,
[target.sourceId, target.slug],
);
const dbMaxRowNum = Number(dbMaxRows[0]?.max ?? 0) || 0;
const fenceMaxRowNum = parseFactsFence(body).facts
.reduce((m, f) => Math.max(m, f.rowNum), 0);
let nextRowNum = Math.max(fenceMaxRowNum, dbMaxRowNum) + 1;
const assignedRowNums: number[] = [];
for (const f of facts) {
const validFromStr = (f.validFrom ?? new Date()).toISOString().slice(0, 10);
const { body: updated, rowNum } = upsertFactRow(body, {
rowNum: nextRowNum++,
claim: f.fact,
kind: (f.kind ?? 'fact') as 'fact' | 'event' | 'preference' | 'commitment' | 'belief',
confidence: f.confidence ?? 1.0,
+2 -61
View File
@@ -424,23 +424,6 @@ export interface OperationContext {
* satisfied even on single-source brains.
*/
sourceId: string;
/**
* #2561 — federated read scope for UNQUALIFIED local CLI reads.
*
* Set ONLY by the local CLI's context builder (src/cli.ts makeContext), and
* only when the source resolved via a non-explicit tier (local_path /
* brain_default / sole_non_default / seed_default — NOT --source, NOT
* GBRAIN_SOURCE, NOT a .gbrain-source dotfile). Contains the resolved
* source first, then every other `config.federated = true` source, so an
* unqualified `gbrain search "X"` spans federated sources as
* docs/guides/multi-source-brains.md promises.
*
* Consumed exclusively by `federatedSearchScope` and ONLY when
* `ctx.remote === false` — a remote caller's scope stays governed by
* `ctx.auth.allowedSources` / scalar `ctx.sourceId` (source-isolation
* invariant, fail-closed).
*/
localFederatedSourceIds?: string[];
}
/**
@@ -556,45 +539,6 @@ export function resolveRequestedScope(
return sourceScopeOpts(ctx);
}
/**
* #2561 — source scope for the search-shaped read ops (`search`, `query`).
*
* Delegates to `resolveRequestedScope` (the single trust+grant resolver), then
* widens an UNQUALIFIED trusted-local scalar scope to the CLI-computed
* federated set (`ctx.localFederatedSourceIds`, resolved source first). This is
* what makes `sources add --federated` mean something for local search: a
* federated source participates in unqualified `gbrain search "X"` results.
*
* The expansion NEVER applies when:
* - the caller is not strictly trusted-local (`ctx.remote !== false`) —
* remote scope stays grant-governed (fail-closed source isolation);
* - a per-call `source_id` was passed (explicit wins, including `__all__`);
* - the resolver already produced a federated array (OAuth grant);
* - the CLI resolved the source from an explicit signal (--source / env /
* dotfile) — makeContext leaves `localFederatedSourceIds` unset then.
*
* Deliberately NOT inside `sourceScopeOpts`: code-intel ops collapse a
* multi-element scope to an error (`resolveCodeIntelScope`), and non-search
* reads (get_page, get_links, …) keep their long-standing scalar behavior.
*/
export function federatedSearchScope(
ctx: OperationContext,
sourceIdParam?: string,
): { sourceId?: string; sourceIds?: string[] } {
const scope = resolveRequestedScope(ctx, sourceIdParam);
if (
ctx.remote === false &&
sourceIdParam === undefined &&
scope.sourceId !== undefined &&
scope.sourceIds === undefined &&
ctx.localFederatedSourceIds !== undefined &&
ctx.localFederatedSourceIds.length > 1
) {
return { sourceIds: ctx.localFederatedSourceIds };
}
return scope;
}
/**
* Code-intel adapter for `resolveRequestedScope`. Graph traversal
* (code_callers/code_callees/code_blast/code_flow) is single-source by design —
@@ -1504,8 +1448,7 @@ const search: Operation = {
const queryText = p.query as string;
const limit = (p.limit as number) || 20;
const offset = (p.offset as number) || 0;
// #2561: unqualified trusted-local search spans federated sources.
const scope = federatedSearchScope(ctx);
const scope = sourceScopeOpts(ctx);
// T4/D5 — per-call mode honored ONLY for trusted/local callers so a remote
// OAuth client can't escalate to the costly tokenmax bundle. Local + unknown
@@ -1667,9 +1610,7 @@ const query: Operation = {
// is spread into BOTH the image-similarity searchVector path and the text
// hybridSearch path below, so both honor the same grant.
const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
// #2561: unqualified trusted-local query spans federated sources (per-call
// source_id / remote grants still resolve through resolveRequestedScope).
const querySourceScope = federatedSearchScope(ctx, sourceIdParam);
const querySourceScope = resolveRequestedScope(ctx, sourceIdParam);
// v0.27.1: image-similarity branch. Bypasses hybridSearch (which is
// text-only); embeds the image via embedMultimodal and runs a direct
+18 -8
View File
@@ -4102,11 +4102,13 @@ export class PGLiteEngine implements BrainEngine {
): Promise<{ inserted: number; ids: number[] }> {
if (rows.length === 0) return { inserted: 0, ids: [] };
// Single transaction so the v51 partial UNIQUE index can roll back the
// whole batch on constraint violation. Per-row INSERTs (not multi-row
// VALUES) keep the embedding-vs-no-embedding branching readable; batch
// sizes are small (5-30 rows per page in practice) so the loop overhead
// is negligible vs the embedding compute cost.
// Single transaction; per-row INSERTs (not multi-row VALUES) keep the
// embedding-vs-no-embedding branching readable; batch sizes are small
// (5-30 rows per page in practice) so the loop overhead is negligible
// vs the embedding compute cost. #2044: ON CONFLICT DO NOTHING on the
// v51 partial UNIQUE index makes a residual fence/DB row_num collision
// skip that row instead of rolling back the whole batch (parity with
// postgres-engine.ts).
const ids = await this.db.transaction(async (tx) => {
const out: number[] = [];
for (const input of rows) {
@@ -4149,7 +4151,11 @@ export class PGLiteEngine implements BrainEngine {
$14, $15,
$16, $17, $18, $19,
$20
) RETURNING id`
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
DO NOTHING
RETURNING id`
: `INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
@@ -4163,12 +4169,16 @@ export class PGLiteEngine implements BrainEngine {
$15, $16,
$17, $18, $19, $20,
$21
) RETURNING id`,
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
DO NOTHING
RETURNING id`,
embedStr === null
? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
: [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
);
out.push(ins.rows[0].id);
if (ins.rows[0]) out.push(ins.rows[0].id);
}
return out;
});
+12 -6
View File
@@ -4302,10 +4302,12 @@ export class PostgresEngine implements BrainEngine {
// ONCE per process so the cast matches the actual column type
// (halfvec vs vector). The probe is cached after first call.
const castSuffix = await this.resolveFactsEmbeddingCast();
// Single transaction so the v51 partial UNIQUE index can roll back
// the whole batch on constraint violation. Per-row INSERTs (not
// multi-row VALUES) keep the embedding-vs-no-embedding branching
// readable; batch sizes are small (5-30 rows per page in practice).
// Single transaction; per-row INSERTs (not multi-row VALUES) keep the
// embedding-vs-no-embedding branching readable; batch sizes are small
// (5-30 rows per page in practice). #2044: ON CONFLICT DO NOTHING on
// the v51 partial UNIQUE index makes a residual fence/DB row_num
// collision skip that row instead of rolling back the whole batch —
// the fence stays system-of-record and reconciliation catches up.
// No supersede flow in this path — fence reconciliation is the
// canonical source-of-truth direction, not the consolidator path.
const ids = await sql.begin(async (tx) => {
@@ -4346,9 +4348,13 @@ export class PostgresEngine implements BrainEngine {
${input.row_num}, ${input.source_markdown_slug},
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
${eventType}
) RETURNING id
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
DO NOTHING
RETURNING id
`;
out.push(Number(ins[0].id));
if (ins[0]) out.push(Number(ins[0].id));
}
return out;
});
-39
View File
@@ -353,45 +353,6 @@ export async function resolveSourceWithTier(
return { source_id: 'default', tier: 'seed_default' };
}
/**
* #2561 — compute the federated read scope for an UNQUALIFIED local CLI call.
*
* `sources add --federated` promises that a `config.federated = true` source
* "participates in unqualified `gbrain search` results"
* (docs/guides/multi-source-brains.md). This helper turns that promise into a
* scope: given the resolved source and WHICH tier resolved it, return
* `[resolvedSource, ...other federated source ids]` — or `undefined` when the
* expansion must not apply:
*
* - explicit tiers (`flag` / `env` / `dotfile`): the user named a source;
* scalar scope stands (that IS the qualified case);
* - no other federated source exists: keep the scalar fast path unchanged.
*
* Archived sources are excluded (same rationale as pickSoleNonDefaultSource);
* the archived column is v34+, so fall back to the un-archived query on older
* brains. Callers put the result on `OperationContext.localFederatedSourceIds`
* — consumed only by `federatedSearchScope` and only when `remote === false`.
*/
export async function localFederatedSourceIds(
engine: BrainEngine,
sourceId: string,
tier: SourceTier,
): Promise<string[] | undefined> {
if (tier === 'flag' || tier === 'env' || tier === 'dotfile') return undefined;
let rows: Array<{ id: string }>;
try {
rows = await engine.executeRaw<{ id: string }>(
`SELECT id FROM sources WHERE config->>'federated' = 'true' AND archived = false ORDER BY id`,
);
} catch {
rows = await engine.executeRaw<{ id: string }>(
`SELECT id FROM sources WHERE config->>'federated' = 'true' ORDER BY id`,
);
}
const ids = [sourceId, ...rows.map((r) => r.id).filter((id) => id !== sourceId)];
return ids.length > 1 ? ids : undefined;
}
/** Exposed for tests. */
export const __testing = {
readDotfileWalk,
+3 -1
View File
@@ -304,7 +304,9 @@ describe('runExtractFacts — empty-fence guard (Codex R2-#7)', () => {
expect(r.legacyRowsPending).toBe(1);
expect(r.factsInserted).toBe(0);
expect(r.factsDeleted).toBe(0);
expect(r.warnings.some(w => w.includes('apply-migrations'))).toBe(true);
// #1867: the remedy hint points at the re-runnable backfill command,
// not the one-shot v0_32_2 migration (which the ledger never re-runs).
expect(r.warnings.some(w => w.includes('gbrain facts fence-backfill'))).toBe(true);
// Legacy row was NOT touched.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
+133
View File
@@ -0,0 +1,133 @@
/**
* #1867 — `gbrain facts fence-backfill` command tests.
*
* The command re-runs the (idempotent) v0_32_2 phase B on demand so
* row_num-NULL backlogs — remote extract_facts deposits that predate
* the fence-write backstop — can be cleared without re-running the
* one-shot migration. Real PGLite + real tempdir filesystem.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runFactsCommand } from '../src/commands/facts.ts';
import { phaseBFenceFacts } from '../src/commands/migrations/v0_32_2.ts';
let engine: PGLiteEngine;
let brainDir: string;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
});
afterAll(async () => {
await engine.disconnect();
try {
if (brainDir) rmSync(brainDir, { recursive: true, force: true });
} catch { /* best-effort */ }
});
beforeEach(async () => {
brainDir = mkdtempSync(join(tmpdir(), 'facts-backfill-cmd-test-'));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query('DELETE FROM facts');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query(
`UPDATE sources SET local_path = $1 WHERE id = 'default'`,
[brainDir],
);
});
async function seedLegacyFact(fact: string): Promise<void> {
// The row_num-NULL shape a remote extract_facts deposit leaves behind
// when it lands via the legacy DB-only path.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query(
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability,
valid_from, source, confidence)
VALUES ('default', 'people/alice', $1, 'fact', 'private', 'medium',
now(), 'mcp:extract_facts', 1.0)`,
[fact],
);
}
describe('gbrain facts fence-backfill', () => {
test('fences row_num-NULL rows and stamps the DB', async () => {
await seedLegacyFact('Deposited remotely');
await runFactsCommand(engine, ['fence-backfill']);
// The fence exists on disk with the claim.
const filePath = join(brainDir, 'people/alice.md');
expect(existsSync(filePath)).toBe(true);
expect(readFileSync(filePath, 'utf-8')).toContain('Deposited remotely');
// The backlog is cleared: no row_num-NULL rows remain.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query(
'SELECT row_num, source_markdown_slug FROM facts',
);
expect(rows.rows).toHaveLength(1);
expect(rows.rows[0].row_num).toBe(1);
expect(rows.rows[0].source_markdown_slug).toBe('people/alice');
});
test('re-run is a no-op (idempotent)', async () => {
await seedLegacyFact('Deposited remotely');
await runFactsCommand(engine, ['fence-backfill']);
await runFactsCommand(engine, ['fence-backfill']);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query('SELECT id FROM facts');
expect(rows.rows).toHaveLength(1);
const body = readFileSync(join(brainDir, 'people/alice.md'), 'utf-8');
expect(body.match(/Deposited remotely/g)).toHaveLength(1);
});
test('--dry-run reports without writing', async () => {
await seedLegacyFact('Deposited remotely');
await runFactsCommand(engine, ['fence-backfill', '--dry-run']);
expect(existsSync(join(brainDir, 'people/alice.md'))).toBe(false);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query(
'SELECT row_num FROM facts',
);
expect(rows.rows[0].row_num).toBeNull();
});
test('diverged page: appends past the DB row_num max instead of colliding (#2044 class)', async () => {
// The #2044 divergence shape the backfill must survive: the DB already
// holds stamped rows 1..3 for the slug (legacy wrong-path fence write),
// but the fence at the resolved path is missing. Fence-max+1 (= 1) would
// collide with the stamped rows on the post-rename UPDATE, failing the
// page and leaving the renamed fence disagreeing with the DB.
for (let n = 1; n <= 3; n++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query(
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability,
valid_from, source, confidence, row_num, source_markdown_slug)
VALUES ('default', 'people/alice', $1, 'fact', 'private', 'medium',
now(), 'mcp:extract_facts', 1.0, $2, 'people/alice')`,
[`stamped ${n}`, n],
);
}
await seedLegacyFact('Deposited remotely');
const result = await phaseBFenceFacts(engine, { dryRun: false });
expect(result.status).toBe('complete');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query(
`SELECT row_num FROM facts WHERE fact = 'Deposited remotely'`,
);
expect(rows.rows[0].row_num).toBe(4);
const body = readFileSync(join(brainDir, 'people/alice.md'), 'utf-8');
expect(body).toContain('| 4 | Deposited remotely |');
});
});
+43
View File
@@ -292,6 +292,49 @@ describe('lookupSourceLocalPath', () => {
});
});
describe('writeFactsToFence — fence/DB divergence (#2044)', () => {
test('seeds row_num past the DB max when the fence lags the DB', async () => {
// Simulate the divergence class from #2044: DB rows were stamped with
// row_nums against a fence written at a path this code no longer reads
// (e.g. the pre-"Local patch 2026-06-11" wrong-path writes). The page
// on disk has NO fence, but the DB already holds row_num 1..3 for the
// slug. Pre-fix, the next deposit re-assigned row_num=1 from fence
// text alone and the whole insertFacts batch failed on
// idx_facts_fence_key.
for (let n = 1; n <= 3; n++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query(
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability,
valid_from, source, confidence, row_num, source_markdown_slug)
VALUES ('default', 'people/dana', $1, 'fact', 'private', 'medium',
now(), 'mcp:extract_facts', 1.0, $2, 'people/dana')`,
[`old claim ${n}`, n],
);
}
const result = await writeFactsToFence(
engine,
{ sourceId: 'default', localPath: brainDir, slug: 'people/dana' },
[baseInput({ fact: 'second deposit' })],
);
expect(result.fenceWriteFailed).toBeUndefined();
expect(result.inserted).toBe(1);
// The new row landed PAST the DB max, not at fence-max+1 (= 1).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query(
'SELECT row_num FROM facts WHERE id = $1',
[result.ids[0]],
);
expect(rows.rows[0].row_num).toBe(4);
// And the on-disk fence carries the same row_num — fence and DB agree.
const body = readFileSync(join(brainDir, 'people/dana.md'), 'utf-8');
expect(body).toContain('| 4 | second deposit |');
});
});
// Cleanup any leftover tempdirs after the whole suite.
afterAll(() => {
// No-op: each test cleaned up via the beforeEach; this is a safety net.
+18 -19
View File
@@ -5,7 +5,7 @@
* - Batch insert N rows persists row_num + source_markdown_slug
* - Empty batch is a no-op
* - Returns ids in input-order
* - v51 partial UNIQUE index rolls back the whole batch on a collision
* - v51 partial UNIQUE collision skips only the colliding row (#2044)
* - deleteFactsForPage scopes by (source_id, source_markdown_slug);
* never touches other pages or pre-v51 NULL-source_markdown_slug rows
* - deleteFactsForPage on an empty page returns deleted:0 (idempotent)
@@ -135,30 +135,29 @@ describe('engine.insertFacts — batch insert', () => {
});
});
test('v51 partial UNIQUE index rolls back the whole batch on collision', async () => {
test('v51 partial UNIQUE collision skips ONLY the colliding row (#2044)', async () => {
// Seed row #1 first.
await engine.insertFacts([fixtureFact(1, { fact: 'seeded' })], { source_id: 'default' });
// Now try to batch-insert rows that include a colliding row_num=1.
let threw = false;
try {
await engine.insertFacts(
[
fixtureFact(2, { fact: 'second' }),
fixtureFact(1, { fact: 'collides' }), // row_num=1 on same (source_id, source_markdown_slug)
fixtureFact(3, { fact: 'third' }),
],
{ source_id: 'default' },
);
} catch {
threw = true;
}
expect(threw).toBe(true);
// Batch-insert rows that include a colliding row_num=1. Pre-#2044 this
// threw and rolled back the whole batch, making a second remote
// extract_facts deposit to an already-fenced page a hard failure. Now
// ON CONFLICT DO NOTHING skips the colliding row and keeps the rest.
const result = await engine.insertFacts(
[
fixtureFact(2, { fact: 'second' }),
fixtureFact(1, { fact: 'collides' }), // row_num=1 on same (source_id, source_markdown_slug)
fixtureFact(3, { fact: 'third' }),
],
{ source_id: 'default' },
);
expect(result.inserted).toBe(2);
expect(result.ids).toHaveLength(2);
// Verify the transaction rolled back — only the seeded row should remain.
// The seeded row survives untouched; the colliding claim is skipped.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query('SELECT fact FROM facts ORDER BY id');
expect(rows.rows.map((r: { fact: string }) => r.fact)).toEqual(['seeded']);
expect(rows.rows.map((r: { fact: string }) => r.fact)).toEqual(['seeded', 'second', 'third']);
});
test('different source_markdown_slug values DO NOT collide on the same row_num', async () => {
-154
View File
@@ -1,154 +0,0 @@
/**
* #2561 sources.config.federated participates in UNQUALIFIED local CLI
* search/query.
*
* Pre-fix: the local CLI always emitted a scalar `{sourceId}` scope (required
* field, auto-filled 'default'), so a source registered with
* `gbrain sources add --federated` was invisible to an unqualified
* `gbrain search "X"` contradicting docs/guides/multi-source-brains.md
* ("Source participates in unqualified `gbrain search` results").
*
* Fix: the CLI context builder computes `ctx.localFederatedSourceIds`
* (resolved source + every other federated source) whenever the source
* resolved via a NON-explicit tier; `federatedSearchScope` widens the scalar
* scope to that set for the `search` / `query` ops trusted-local only
* (`ctx.remote === false`), never for remote callers, never when a per-call
* `source_id` or an explicit --source/env/dotfile was given.
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { localFederatedSourceIds } from '../src/core/source-resolver.ts';
import {
federatedSearchScope,
operations,
type OperationContext,
} from '../src/core/operations.ts';
let engine: PGLiteEngine;
const search = operations.find((o) => o.name === 'search')!;
function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
return {
engine: engine as any,
config: {} as any,
logger: console as any,
dryRun: false,
remote: false,
sourceId: 'default',
...overrides,
};
}
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
// Seeded 'default' source is federated=true. Add:
// wiki — federated (must join unqualified search)
// private — NOT federated (must stay invisible unless explicitly named)
// oldnews — federated but archived (must stay excluded)
await engine.executeRaw(
`INSERT INTO sources (id, name, local_path, config) VALUES ('wiki', 'wiki', '/tmp/wiki', '{"federated": true}'::jsonb)`,
);
await engine.executeRaw(
`INSERT INTO sources (id, name, local_path, config) VALUES ('private', 'private', '/tmp/private', '{}'::jsonb)`,
);
await engine.executeRaw(
`INSERT INTO sources (id, name, local_path, config, archived) VALUES ('oldnews', 'oldnews', '/tmp/oldnews', '{"federated": true}'::jsonb, true)`,
);
const pages: Array<[slug: string, sourceId: string, where: string]> = [
['notes/home', 'default', 'default'],
['wiki/topic', 'wiki', 'wiki'],
['private/topic', 'private', 'private'],
['old/topic', 'oldnews', 'oldnews'],
];
for (const [slug, sourceId, where] of pages) {
await engine.putPage(slug, {
type: 'note', title: `Topic in ${where}`, compiled_truth: `the zebra telescope in ${where}`, frontmatter: {},
}, { sourceId });
await engine.upsertChunks(slug, [
{ chunk_index: 0, chunk_text: `the zebra telescope in ${where}`, chunk_source: 'compiled_truth' },
], { sourceId });
}
// Keyword-only search path: no embedding provider needed in tests.
await engine.setConfig('search.mcp_keyword_only', 'true');
}, 60_000);
afterAll(async () => {
if (engine) await engine.disconnect();
}, 60_000);
describe('localFederatedSourceIds — CLI-side scope computation', () => {
test('non-explicit tier: resolved source first, then other federated, archived excluded', async () => {
expect(await localFederatedSourceIds(engine, 'default', 'seed_default')).toEqual(['default', 'wiki']);
});
test('non-federated resolved source still joins its own scope', async () => {
expect(await localFederatedSourceIds(engine, 'private', 'brain_default')).toEqual(['private', 'default', 'wiki']);
});
test('explicit tiers (--source / env / dotfile) never expand', async () => {
expect(await localFederatedSourceIds(engine, 'default', 'flag')).toBeUndefined();
expect(await localFederatedSourceIds(engine, 'default', 'env')).toBeUndefined();
expect(await localFederatedSourceIds(engine, 'default', 'dotfile')).toBeUndefined();
});
test('single federated source (the resolved one) keeps the scalar fast path', async () => {
const solo = { executeRaw: async () => [{ id: 'default' }] } as any;
expect(await localFederatedSourceIds(solo, 'default', 'seed_default')).toBeUndefined();
});
});
describe('federatedSearchScope — trust + explicitness matrix', () => {
test('trusted local + unqualified widens to the federated set', () => {
const ctx = ctxOf({ localFederatedSourceIds: ['default', 'wiki'] });
expect(federatedSearchScope(ctx)).toEqual({ sourceIds: ['default', 'wiki'] });
});
test('remote caller NEVER widens (fail-closed), even if the field is set', () => {
const ctx = ctxOf({ remote: true, localFederatedSourceIds: ['default', 'wiki'] });
expect(federatedSearchScope(ctx)).toEqual({ sourceId: 'default' });
});
test('per-call source_id wins over the federated set', () => {
const ctx = ctxOf({ localFederatedSourceIds: ['default', 'wiki'] });
expect(federatedSearchScope(ctx, 'wiki')).toEqual({ sourceId: 'wiki' });
});
test('per-call __all__ keeps the whole-brain semantics for trusted local', () => {
const ctx = ctxOf({ localFederatedSourceIds: ['default', 'wiki'] });
expect(federatedSearchScope(ctx, '__all__')).toEqual({});
});
test('a federated OAuth grant wins over the local set', () => {
const ctx = ctxOf({
localFederatedSourceIds: ['default', 'wiki'],
auth: { allowedSources: ['a', 'b'] } as OperationContext['auth'],
});
expect(federatedSearchScope(ctx)).toEqual({ sourceIds: ['a', 'b'] });
});
test('no local federated set → unchanged scalar scope', () => {
expect(federatedSearchScope(ctxOf())).toEqual({ sourceId: 'default' });
});
});
describe('search op — unqualified local search spans federated sources', () => {
test('federated source results appear; non-federated + archived stay invisible', async () => {
const ctx = ctxOf({
localFederatedSourceIds: await localFederatedSourceIds(engine, 'default', 'seed_default'),
});
const results = (await search.handler(ctx, { query: 'zebra telescope' })) as Array<{ slug: string }>;
const slugs = results.map((r) => r.slug);
expect(slugs).toContain('notes/home');
expect(slugs).toContain('wiki/topic'); // pre-#2561 this was missing
expect(slugs).not.toContain('private/topic');
expect(slugs).not.toContain('old/topic');
});
test('explicit source resolution (no federated set on ctx) stays single-source', async () => {
const results = (await search.handler(ctxOf(), { query: 'zebra telescope' })) as Array<{ slug: string }>;
const slugs = results.map((r) => r.slug);
expect(slugs).toEqual(['notes/home']);
});
});