Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P2.2 (#6474): fence a DB link walk's origin once, at its live snapshot revision

garrytan08c3ee51ce95
diff --git a/docs/architecture/key-files/company-brain.md b/docs/architecture/key-files/company-brain.md
index 289930cf85..ec22ab2fce 100644
--- a/docs/architecture/key-files/company-brain.md
+++ b/docs/architecture/key-files/company-brain.md
@@ -9,7 +9,7 @@ For the operator workflow, see the [company-brain ingestion guide](../../guides/
- `src/commands/company-brain-{inspect,connect,demo}.ts` — dedicated source subcommand parsing and versioned JSON/error output. Inspection is engine-free; connect requires explicit brain/source selection and previews through the existing resident-owner route before a probe-only local connection. Human progress is stderr-scoped for JSON output. `core/company-brain/{demo,sample,evidence,status}.ts` supplies the real-pipeline offline sample, actual source-scoped evidence, and private receipt status without fabricated answers or host-path fields.
-- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints (foreign ones included) and resolves a target into another source only under the source policy it shares with `put_page`'s link preparation (`makeLinkSourceResolver`: `link_resolution.cross_source`, or a `[[source:slug]]` reference from a federated origin; #4680). Standard DB extraction passes the same captured endpoint revision fences. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`engine.readPageSnapshotsBatch`, built on `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, page-subject purges and the '*' purge marker included, line fingerprints only for pages with withdrawals, purges or a '*' marker, a body-byte budget per call; Postgres binds the refs' sources for RLS; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.
+- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints (foreign ones included) and resolves a target into another source only under the source policy it shares with `put_page`'s link preparation (`makeLinkSourceResolver`: `link_resolution.cross_source`, or a `[[source:slug]]` reference from a federated origin; #4680). Standard DB extraction passes the same captured endpoint revision fences. `capturedLinkEndpoints(links, metadata, origin?)` is the one place those fences are built: every endpoint at the resolver census's revision except the source-qualified origin, which `expectedRevision` already fences at the snapshot that supplied its body and type (#6474: fencing it again at the older census revision deferred a page rewritten between the census and its own read); the managed `links-preparation.ts` and both DB walks (`extract links|all`, `extract --stale`) pass the origin, and a self-reference's target type comes from the live snapshot rather than the census. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`engine.readPageSnapshotsBatch`, built on `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, page-subject purges and the '*' purge marker included, line fingerprints only for pages with withdrawals, purges or a '*' marker, a body-byte budget per call; Postgres binds the refs' sources for RLS; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.
- `src/core/attendance-repair.ts` and `src/commands/extract-attendance-repair.ts` — trusted-local historical attendance preview and exact-receipt apply. Indexed source-page slug windows precede eligibility filtering; explicit Markdown evidence uses capped endpoint and adjacency lookups, while all frontmatter remains report-only and unmaterialized. A narrow `derived-links.ts` delta preserves unrelated row IDs and evidence; brain/source incarnation, page revisions, ontology/parser and affected-edge hashes fence each origin transaction. Existing `op_checkpoints` banks commit proof before the private cursor advances across committed origins and revalidated skipped pages, making interruption replay idempotent. No broad derived replacement, normal-extraction watermark updates, MCP administration or provider calls. Covered by the dual-engine `test/attendance-repair.test.ts` and real CLI `test/attendance-repair-cli.serial.test.ts`; operator contract and limits are in `docs/guides/attendance-evidence.md`.
- `src/core/schema-pack/base/company-brain.yaml` — optional company vocabulary extending `gbrain-base-v2` without normalization rules or maintenance phases. Overrides company aliases and prefixes so product stays a distinct query and path type. Bundled through `schema-pack/bundled.ts` and `bundled-assets.ts`; attribution is in `third-party/company-brain/`. The generic fictional sample in `src/core/company-brain/sample/` preserves the upstream layout and relationship metadata. `test/company-brain-schema.test.ts` pins inherited lint, type closure, folder inference, read-only bundling, and sample references.
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 29d7a79a8d..88cb7383e6 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -1969,7 +1969,7 @@ async function extractLinksFromDB(
{ skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,
source_id, allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId });
- return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
+ return !resolved.ok ? undefined : targetSlug === slug && resolved.toSourceId === source_id ? page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;
} },
);
unresolved.push(...extracted.unresolved);
@@ -2021,7 +2021,7 @@ async function extractLinksFromDB(
pendingWrites.push({ slug, source_id, item: { origin: { slug, sourceId: source_id, expectedRevision: snapshot.revision,
sourceIncarnation: snapshot.sourceIncarnation }, links: batch, opts: { includeFrontmatter, lineGrammar: grammar,
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },
- expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata) } } });
+ expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata, { slug, sourceId: source_id }) } } });
} catch (error) {
if (jsonMode) process.stderr.write(JSON.stringify({ event: 'batch_error', size: batch.length, code: 'graph_write_failed' }) + '\n');
throw error;
@@ -2233,7 +2233,7 @@ export async function extractStaleFromDB(
{ skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {
const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, page.slug,
page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId });
- return resolved.ok ? targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;
+ return !resolved.ok ? undefined : targetSlug === page.slug && resolved.toSourceId === page.source_id ? snapshot.page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;
} },
);
if (!extracted.attendanceComplete) {
@@ -2259,7 +2259,7 @@ export async function extractStaleFromDB(
frontmatterUnresolved: includeFrontmatter ? extracted.unresolved : [], originSourceId: page.source_id,
crossSourceAllowed: federatedSourceIds.has(page.source_id) || crossSource, resolve: c => resolveCandidateSources(c, page.slug,
page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];
- const linkOpts = { includeFrontmatter, lineGrammar: grammar, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata),
+ const linkOpts = { includeFrontmatter, lineGrammar: grammar, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata, origin),
wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted } };
const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;
const written = await replaceDerivedLinksDeferringConflicts(engine, origin, linkRows, linkOpts);
diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.ts
index 40e2260a8d..8439a10b86 100644
--- a/src/core/link-reconciliation.ts
+++ b/src/core/link-reconciliation.ts
@@ -274,10 +274,22 @@ export function makeLinkSourceResolver(pageSlug: string, pageSourceId: string,
};
}
-export function capturedLinkEndpoints(links: LinkBatchInput[], metadata: ReadonlyMap<string, Pick<LinkPageMetadata, 'slug' | 'source_id' | 'knowledge_revision'>>) {
+/**
+ * Endpoint fences for one origin's link batch: every endpoint at the revision
+ * the resolver census captured. The source-qualified `origin`, when given, is
+ * left out (#6474): its body and type came from the snapshot whose revision
+ * `expectedRevision` already fences at publication, so fencing it again at
+ * the older census revision would defer a page rewritten between the census
+ * and its own read even though the run extracted its live body. A page with
+ * the same slug in another source is still fenced. This is the one place the
+ * rule lives; the managed preparation and both DB walks call it.
+ */
+export function capturedLinkEndpoints(links: LinkBatchInput[], metadata: ReadonlyMap<string, Pick<LinkPageMetadata, 'slug' | 'source_id' | 'knowledge_revision'>>,
+ origin?: { slug: string; sourceId: string }) {
const keys = new Set(links.flatMap(link => [
`${link.from_source_id ?? 'default'}\0${link.from_slug}`, `${link.to_source_id ?? 'default'}\0${link.to_slug}`,
]));
+ if (origin) keys.delete(`${origin.sourceId}\0${origin.slug}`);
return [...keys].map(key => {
const endpoint = metadata.get(key);
if (!endpoint) throw new Error('A derived link endpoint was not captured during type resolution');
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index bdf6b9329b..a1b0085db4 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -135,9 +135,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
try {
const result = await tx.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,
sourceIncarnation: snapshot.sourceIncarnation, snapshot }, rows, { preserveExisting: true, semanticsPrimed: primeSemantics, lineGrammar: settings, wanted: { ...wanted, producers: [...wanted.producers] },
- expectedEndpoints: capturedLinkEndpoints(rows, new Map([...metadata,
- [`${sourceId}\0${slug}`, { slug, source_id: sourceId, type: page.type, knowledge_revision: snapshot.revision }]]))
- .filter(endpoint => endpoint.slug !== slug || endpoint.sourceId !== sourceId) });
+ expectedEndpoints: capturedLinkEndpoints(rows, metadata, { slug, sourceId }) });
return { ...result, errors: 0, unresolved_count: unresolved.length, skipped_cross_source: skippedCrossSource, wanted_count: wanted.rows.length,
...(wanted.rows.length ? { wanted: wanted.rows.slice(0, 10).map(row => ({ slug: row.target_ref, source_id: row.target_source_id })),
wanted_message: 'These link targets have no page yet; each edge is created when its page is. Create the page if it is real, or fix the link if it is a typo.',
diff --git a/test/e2e/extract-endpoint-revision-postgres.test.ts b/test/e2e/extract-endpoint-revision-postgres.test.ts
new file mode 100644
index 0000000000..d687e5067c
--- /dev/null
+++ b/test/e2e/extract-endpoint-revision-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../extract-endpoint-revision.serial.test.ts'));
diff --git a/test/extract-endpoint-revision.serial.test.ts b/test/extract-endpoint-revision.serial.test.ts
index 3026b4f25a..1431cf323e 100644
--- a/test/extract-endpoint-revision.serial.test.ts
+++ b/test/extract-endpoint-revision.serial.test.ts
@@ -6,12 +6,33 @@ import { PageRevisionConflictError, RevisionBackfillPendingError } from '../src/
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runExtract, extractStaleFromDB } from '../src/commands/extract.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { capturedLinkEndpoints } from '../src/core/link-reconciliation.ts';
const sourceId = 'revision-origin';
const otherSourceId = 'revision-target';
const originSlug = 'meetings/weekly';
const targetSlug = 'people/alice-example';
+// #6474 (wave 15 P2.2, after PR #6498 by @javieraldape): the origin of a DB
+// link walk is fenced once, by its own snapshot revision (expectedRevision);
+// its census row, read before the walk, must not fence it a second time.
+test('capturedLinkEndpoints drops only the source-qualified origin and needs no census row for it (#6474)', () => {
+ const metadata = new Map([
+ [`${otherSourceId}\0${originSlug}`, { slug: originSlug, source_id: otherSourceId, knowledge_revision: 'foreign-rev' }],
+ [`${sourceId}\0${targetSlug}`, { slug: targetSlug, source_id: sourceId, knowledge_revision: 'target-rev' }],
+ ]);
+ const links: LinkBatchInput[] = [
+ { from_slug: originSlug, from_source_id: sourceId, to_slug: targetSlug, to_source_id: sourceId, link_type: 'mentions', context: '' },
+ { from_slug: originSlug, from_source_id: sourceId, to_slug: originSlug, to_source_id: otherSourceId, link_type: 'related', context: '' },
+ ];
+ expect(capturedLinkEndpoints(links, metadata, { slug: originSlug, sourceId })).toEqual([
+ { slug: targetSlug, sourceId, revision: 'target-rev' },
+ { slug: originSlug, sourceId: otherSourceId, revision: 'foreign-rev' },
+ ]);
+ // Without an origin every endpoint is fenced, and the origin's own census row is required.
+ expect(() => capturedLinkEndpoints(links, metadata)).toThrow('not captured');
+});
+
for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {
describe(`DB extraction endpoint fences (${kind})`, () => {
let engine: BrainEngine;
@@ -179,6 +200,52 @@ for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]
});
}
+ for (const mode of ['links', 'all', 'stale']) {
+ test(`${mode}: an origin rewritten between the census and its snapshot read is written from the live read, not deferred (#6474)`, async () => {
+ await engine.putPage(targetSlug, { type: 'person', title: 'Alice Example', compiled_truth: 'A person.' }, { sourceId });
+ await engine.putPage(originSlug, { type: 'note', title: 'Weekly', compiled_truth: 'Old prose, no links.' }, { sourceId });
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1', [sourceId]);
+ const staleRead = engine.listStalePagesForExtraction, batchRead = engine.readPageSnapshotsBatch;
+ const replace = engine.replaceDerivedLinks, replaceBatch = engine.replaceDerivedLinksBatch;
+ let rewritten = false;
+ const fences: NonNullable<DerivedLinkReplacementOptions['expectedEndpoints']> = [];
+ // The census (loadLinkPageMetadata) runs before either read; a writer retypes the origin to a meeting in between.
+ const rewriteOrigin = async () => {
+ if (rewritten) return;
+ rewritten = true;
+ await engine.putPage(originSlug, { type: 'meeting', title: 'Weekly', compiled_truth: `Attendees: [[${targetSlug}]].` }, { sourceId });
+ };
+ engine.listStalePagesForExtraction = async function (opts) { await rewriteOrigin(); return staleRead.call(this, opts); };
+ engine.readPageSnapshotsBatch = async function (refs) { await rewriteOrigin(); return batchRead.call(this, refs); };
+ engine.replaceDerivedLinks = async function (origin, links, opts) {
+ if (origin.slug === originSlug) fences.push(...(opts?.expectedEndpoints ?? []));
+ return replace.call(this, origin, links, opts);
+ };
+ engine.replaceDerivedLinksBatch = async function (items) {
+ for (const item of items) if (item.origin.slug === originSlug) fences.push(...(item.opts?.expectedEndpoints ?? []));
+ return replaceBatch.call(this, items);
+ };
+ try {
+ if (mode === 'stale') {
+ const result = await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, sourceIdFilter: sourceId, includeFrontmatter: false, catchUp: false });
+ expect(result.skippedConcurrentWrite ?? 0).toBe(0);
+ } else await runExtract(engine, [mode, '--source', 'db', '--source-id', sourceId, '--json']);
+ } finally {
+ engine.listStalePagesForExtraction = staleRead;
+ engine.readPageSnapshotsBatch = batchRead;
+ engine.replaceDerivedLinks = replace;
+ engine.replaceDerivedLinksBatch = replaceBatch;
+ }
+ expect(rewritten).toBe(true);
+ // The live body was typed from the live snapshot: a meeting's [[person]] is `attended`.
+ expect((await graph()).filter(row => row.link_source === 'markdown').map(row => row.link_type)).toEqual(['attended']);
+ // The origin is fenced by its snapshot revision alone; the target still carries its census fence.
+ expect(fences.some(endpoint => endpoint.slug === originSlug && endpoint.sourceId === sourceId)).toBe(false);
+ expect(fences.some(endpoint => endpoint.slug === targetSlug && endpoint.sourceId === sourceId)).toBe(true);
+ if (mode !== 'links') expect(await stamp()).not.toBeNull();
+ });
+ }
+
test('only a real concurrent write defers; a synthetic revision_conflict, a backfill-pending revision and storage errors stay fatal (#6272)', async () => {
const item = { origin: { slug: 'notes/x', sourceId, expectedRevision: '00000000-0000-0000-0000-000000000000', sourceIncarnation: '00000000-0000-0000-0000-000000000000' }, links: [] };
const failing = (error: unknown) => ({ replaceDerivedLinks: async () => { throw error; }, replaceDerivedLinksBatch: async () => { throw error; } }) as unknown as BrainEngine;