Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): a wanted link no page can have never aborts extraction (#6228, #6225)

time-attack9f0c5ab3c6a8
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 7aaa55bc29..2a0f49edec 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -112,7 +112,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/line-grammar.ts` + `src/core/machine-sections.ts` — the line grammar: `parseLineGrammar` reads list items in a page body as typed relation lines (`- works_at [[companies/x]] (context)`: one type token or quoted phrase, exactly one link, optional `(context)`, optional `@effective[start,end)`, an optional trailing `[Source: ...]` citation) and fact lines (`- [category] claim #tag (context)`). Guards: a category is one letter-led token (timecodes, dates, citations, footnotes, task boxes and bracket phrases never match), `x`/`todo`/`done`/`wip` are refused, and code, blockquotes, HTML comments, frontmatter and the machine-written sections from `rolePriorSuppressedRanges` (now in `machine-sections.ts`, shared with type inference) are skipped. Prose after the link, two links, stoplisted generic words and verbs the active pack does not declare fall back to inference with a diagnostic. `statedRelationTypes` feeds `extractPageLinks` (and the filesystem scan in `commands/extract.ts`): the stated type wins for the link on its line, except an `attended` line on a meeting page, which stays with canonical attendance. `parseEffectiveQualifier` normalizes ISO ranges to half-open `[from, until)` dates and refuses everything else unpeeled (a range with more than one comma is refused with an exactly-one-comma message). Parsing stays linear on adversarial lines: the qualifier's date groups exclude commas, the trailing-citation pattern has no overlapping whitespace quantifiers, and links come from `findLinks`, a scan with precomputed stop positions that returns exactly the old link regex's matches. `lineGrammarOptions` resolves `line_grammar.enabled` (default off: held-out verdict H3 failed its precision bar) and `line_grammar.allow_undeclared_types`. Fact lines are reported (put_page `line_grammar`, `gbrain lint` rule `line-grammar`, `schema detect --fields`), not projected into `facts`. Pinned by `test/line-grammar.test.ts` (incl. a timeout-bounded adversarial input, a 200k-character linear-time ratio check and a `findLinks` equivalence property test), `test/link-extraction-line-grammar.test.ts`, `test/put-page-line-grammar.test.ts`.
-- `src/core/wanted-links.ts` + `src/core/wanted-links-store.ts` — wanted pages. `collectWantedLinks` turns an origin's link candidates (each body markdown link / wikilink carries an `authoredRef` from `extractPageLinks`) and unresolved frontmatter names into `wanted_links` rows: a reference is wanted only when every alternative resolution failed with `missing_target`/`cross_source` (an unqualified target existing only in another source is wanted in the origin source; a qualified target in a source the origin may not link to is not). Bare prose paths never become rows. `replaceWantedLinks` runs inside `replaceDerivedLinks` (`opts.wanted`, per producer `body`/`frontmatter`), so every extraction path (managed put_page and stale sweep via `links-preparation.ts`, unmanaged `extract`, the serve sweep, source reconciliation) replaces rows atomically with links; it locks slug targets and stamps a row `-infinity` when its exact target already exists. `WANTED_ORIGIN_IS_STALE` in `engine-sql/pages.ts` joins the stale-for-extraction predicate: a live target (exact slug, or basename for `ref_kind='name'`) updated after `checked_at` makes the origin stale, so the next sweep creates the edge; restore and rename bump `updated_at`. `listWantedPages` backs the `wanted_pages` op (`gbrain wanted`): source-scoped, private origins excluded before aggregation for remote callers, soft-deleted origins never count, bare-name targets list `existing_matches`. `wanted_pages.enabled` (default on). Migration v214. Pinned by `test/wanted-links.test.ts` + `test/e2e/wanted-links-postgres.test.ts`.
+- `src/core/wanted-links.ts` + `src/core/wanted-links-store.ts` — wanted pages. `collectWantedLinks` turns an origin's link candidates (each body markdown link / wikilink carries an `authoredRef` from `extractPageLinks`) and unresolved frontmatter names into `wanted_links` rows: a reference is wanted only when every alternative resolution failed with `missing_target`/`cross_source` (an unqualified target existing only in another source is wanted in the origin source; a qualified target in a source the origin may not link to is not). Bare prose paths never become rows. `replaceWantedLinks` runs inside `replaceDerivedLinks` (`opts.wanted`, per producer `body`/`frontmatter`), so every extraction path (managed put_page and stale sweep via `links-preparation.ts`, unmanaged `extract`, the serve sweep, source reconciliation) replaces rows atomically with links; it keeps only `possibleWantedRows` (a slug target `validateSlug` accepts, in the origin's or a registered source read `FOR SHARE`, so a regex literal on a code page or a `[[memory:123]]` citation never reaches the page guard and aborts extraction, #6228/#6225; `links-preparation.ts` filters the receipt preview the same way), locks slug targets and stamps a row `-infinity` when its exact target already exists. `WANTED_ORIGIN_IS_STALE` in `engine-sql/pages.ts` joins the stale-for-extraction predicate: a live target (exact slug, or basename for `ref_kind='name'`) updated after `checked_at` makes the origin stale, so the next sweep creates the edge; restore and rename bump `updated_at`. `listWantedPages` backs the `wanted_pages` op (`gbrain wanted`): source-scoped, private origins excluded before aggregation for remote callers, soft-deleted origins never count, bare-name targets list `existing_matches`. `wanted_pages.enabled` (default on). Migration v214. Pinned by `test/wanted-links.test.ts` + `test/e2e/wanted-links-postgres.test.ts`.
- `src/core/similar-pages.ts` — put_page's similar-pages advisory on creates (`page-advisories.ts`): exact title (`ILIKE`, served by `idx_pages_trgm`), `page_aliases`, same slug basename in another directory (`idx_pages_slug_basename`), and title trigram similarity >= 0.55 in the same top-level directory; up to 3 slugs with their evidence, private pages excluded for callers that may not read them, `semantic: 'not_checked'` (the page's embedding is queued after publication). A question, never a merge. `put_page.similar_pages` (default off: held-out verdict H5b failed its wrong-merge bar). Pinned by `test/put-page-similar-pages.test.ts` + `test/e2e/p5-graph-postgres.test.ts`.
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index a0ed1b4d53..1da4cce316 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -5,7 +5,7 @@ import { extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCa
import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
import { DerivedLinkEndpointChangedError } from '../derived-links.ts';
import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';
-import { collectWantedLinks, isWantedPagesEnabled } from '../wanted-links.ts';
+import { collectWantedLinks, isWantedPagesEnabled, possibleWantedRows } from '../wanted-links.ts';
import { readFix } from '../ops/op-fix.ts';
import { lineGrammarOptions } from '../line-grammar.ts';
@@ -54,9 +54,10 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
return resolved.ok ? (targetSlug === slug && resolved.toSourceId === sourceId ? page.type
: metadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type) : undefined;
} });
+ // The rows the store keeps (#6228/#6225), so the receipt's wanted preview never names a target no page can have.
const wanted = { producers: ['body', 'frontmatter'] as const, rows: await isWantedPagesEnabled(engine)
- ? collectWantedLinks({ candidates: candidates.map(retarget), frontmatterUnresolved: unresolved, originSourceId: sourceId,
- crossSourceAllowed: policy.allowCrossSource || policy.crossSource, resolve })
+ ? await possibleWantedRows(engine, sourceId, collectWantedLinks({ candidates: candidates.map(retarget), frontmatterUnresolved: unresolved,
+ originSourceId: sourceId, crossSourceAllowed: policy.allowCrossSource || policy.crossSource, resolve }))
: [] };
const rows = candidates.map(retarget).flatMap(candidate => {
const resolved = resolve(candidate);
diff --git a/src/core/wanted-links-store.ts b/src/core/wanted-links-store.ts
index 0fc9cf9167..78855c1f9d 100644
--- a/src/core/wanted-links-store.ts
+++ b/src/core/wanted-links-store.ts
@@ -6,6 +6,7 @@
import type { BrainEngine } from './engine.ts';
import { executeRawJsonb } from './sql-query.ts';
import { sanitizeForJsonb } from './batch-rows.ts';
+import { validateSlug } from './utils.ts';
export type WantedProducer = 'body' | 'frontmatter';
@@ -24,9 +25,33 @@ export interface WantedLinksReplacement {
producers: readonly WantedProducer[];
}
+/**
+ * #6228/#6225: the rows whose target can become a page. A slug target must
+ * pass validateSlug (a regex literal on a code page read as a wikilink does
+ * not) and every target must be in a registered source (a `[[memory:123]]`
+ * citation names none). Any other row names no possible page; locking it
+ * would throw and abort the caller's whole extraction transaction. Foreign
+ * sources are read `FOR SHARE`, so one cannot disappear between this check
+ * and the page-guard lock; the origin's own source needs no read.
+ */
+export async function possibleWantedRows<T extends Pick<WantedLinkInput, 'ref_kind' | 'target_source_id' | 'target_ref'>>(
+ tx: Pick<BrainEngine, 'executeRaw'>, originSourceId: string, rows: readonly T[],
+): Promise<T[]> {
+ const shaped = rows.filter(row => row.ref_kind !== 'slug' || pageSlugShaped(row.target_ref));
+ const foreign = [...new Set(shaped.map(row => row.target_source_id).filter(id => id !== originSourceId))];
+ if (!foreign.length) return shaped;
+ const registered = new Set((await tx.executeRaw<{ id: string }>(
+ 'SELECT id FROM sources WHERE id = ANY($1::text[]) ORDER BY id FOR SHARE', [foreign])).map(row => row.id));
+ return shaped.filter(row => row.target_source_id === originSourceId || registered.has(row.target_source_id));
+}
+
+function pageSlugShaped(target: string): boolean {
+ try { validateSlug(target); return true; } catch { return false; } // a refused slug is the answer, not an error
+}
+
/**
* Replace one origin's wanted rows inside the caller's transaction (the same
- * one that replaces its derived links). Slug targets are locked first, so a
+ * one that replaces its derived links), keeping only possibleWantedRows. Slug targets are locked first, so a
* concurrent writer creating the target either committed before this check
* (and the row is stamped `-infinity`, leaving the origin stale) or commits
* after it with an `updated_at` past `checked_at`. Only an exact slug counts
@@ -40,7 +65,8 @@ export async function replaceWantedLinks(
replacement: WantedLinksReplacement,
): Promise<number> {
if (!replacement.producers.length) return 0;
- const rows = replacement.rows.filter(row => replacement.producers.includes(row.producer))
+ const rows = (await possibleWantedRows(tx, origin.sourceId,
+ replacement.rows.filter(row => replacement.producers.includes(row.producer))))
.map(row => ({ ...row, context: sanitizeForJsonb(row.context) }));
const slugTargets = rows.filter(row => row.ref_kind === 'slug')
.map(row => ({ sourceId: row.target_source_id, slug: row.target_ref }));
diff --git a/src/core/wanted-links.ts b/src/core/wanted-links.ts
index 3f7cfd1c6b..87d77234db 100644
--- a/src/core/wanted-links.ts
+++ b/src/core/wanted-links.ts
@@ -19,7 +19,7 @@ import { isValidSourceId } from './source-id.ts';
import type { WantedLinkInput } from './wanted-links-store.ts';
export type { WantedLinkInput, WantedLinksReplacement, WantedProducer } from './wanted-links-store.ts';
-export { replaceWantedLinks } from './wanted-links-store.ts';
+export { possibleWantedRows, replaceWantedLinks } from './wanted-links-store.ts';
type Resolution = { ok: true } | { ok: false; reason: string };
diff --git a/test/e2e/wanted-links-postgres.test.ts b/test/e2e/wanted-links-postgres.test.ts
index 4e90aa9396..0b99d497b8 100644
--- a/test/e2e/wanted-links-postgres.test.ts
+++ b/test/e2e/wanted-links-postgres.test.ts
@@ -2,9 +2,12 @@
* Postgres arms of the wanted-pages scenarios (test/wanted-links.test.ts runs
* the same bodies on PGLite).
*/
-import { describe, test } from 'bun:test';
-import { bareNameReferenceSettles, disabledClearsRows, forwardReferenceHeals, onlyUnresolvedAuthoredReferences,
- privateOriginsStayPrivate, restoredTargetHeals } from '../helpers/wanted-links-scenarios.ts';
+import { describe, expect, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { replaceWantedLinks } from '../../src/core/wanted-links.ts';
+import { bareNameReferenceSettles, disabledClearsRows, forwardReferenceHeals, impossibleTargetsNeverAbortTheSweep,
+ impossibleTargetsStayOutOfWrites, onlyUnresolvedAuthoredReferences, privateOriginsStayPrivate,
+ restoredTargetHeals } from '../helpers/wanted-links-scenarios.ts';
const url = process.env.DATABASE_URL;
describe.skipIf(!url)('Postgres wanted pages', () => {
@@ -14,4 +17,34 @@ describe.skipIf(!url)('Postgres wanted pages', () => {
test('private origins stay private', () => privateOriginsStayPrivate(url), 180_000);
test('restoring a deleted target heals', () => restoredTargetHeals(url), 180_000);
test('disabling clears rows', () => disabledClearsRows(url), 180_000);
+ test('#6228/#6225: the stale sweep skips targets no page can have', () => impossibleTargetsNeverAbortTheSweep(url), 180_000);
+ test('#6228/#6225: a write records only targets a page can have', () => impossibleTargetsStayOutOfWrites(url), 180_000);
+});
+
+describe.skipIf(!url)('Postgres wanted pages: source registration race (#6225)', () => {
+ test('a foreign source checked for a wanted row cannot be deleted before the transaction ends', async () => {
+ const { isolatedPersistencePostgres } = await import('../helpers/persistence-postgres.ts');
+ const postgres = (await import('#postgres')).default;
+ const brain = await isolatedPersistencePostgres(url!);
+ const other = postgres(brain.databaseUrl, { max: 1, prepare: false });
+ try {
+ const engine = brain.engine;
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('archive', 'archive')");
+ await engine.putPage('notes/origin', { type: 'note', title: 'Origin', compiled_truth: 'Origin.', timeline: '' });
+ const [origin] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/origin'");
+ let deleteError: { code?: string } | null = null;
+ await engine.transaction(async tx => {
+ await replaceWantedLinks(tx, { pageId: Number(origin.id), sourceId: 'default' }, { producers: ['body'], rows: [
+ { producer: 'body', ref_kind: 'name', target_source_id: 'archive', target_ref: 'erin-example', link_type: 'mentions', context: '' }] });
+ try {
+ await other.begin(async sql => {
+ await sql.unsafe("SET LOCAL lock_timeout = '300ms'");
+ await sql.unsafe("DELETE FROM sources WHERE id = 'archive'");
+ });
+ } catch (error) { deleteError = error as { code?: string }; }
+ });
+ expect(deleteError?.code).toBe('55P03');
+ expect(await engine.executeRaw("SELECT target_source_id FROM wanted_links")).toEqual([{ target_source_id: 'archive' }]);
+ } finally { await other.end(); await brain.close(); }
+ }, 180_000);
});
diff --git a/test/helpers/wanted-links-scenarios.ts b/test/helpers/wanted-links-scenarios.ts
index 5f61f44ee0..70521e58b1 100644
--- a/test/helpers/wanted-links-scenarios.ts
+++ b/test/helpers/wanted-links-scenarios.ts
@@ -130,3 +130,47 @@ export async function restoredTargetHeals(databaseUrl?: string) {
expect(await backlinks(engine, 'people/carol-example')).toEqual([{ slug: 'notes/lunch' }]);
}, { databaseUrl });
}
+
+// #6228: bracketed code on a code page parses as a wikilink whose target no slug can be.
+// #6225: a citation prefix that names no registered source parses as a qualified wikilink.
+export const BRACKETED_CODE = 'const routes = mockFetch([[/api\\.example/, () => reply(200)]]);\n// see [[people/alice-example]] and [[people/bob-example]]';
+export const FOREIGN_PREFIXES = 'Noted in [[memory:4242]]. Ask [[people/alice-example]], [[people/bob-example]] and [[archive:people/erin-example]].';
+const registerArchive = async ({ engine }: { engine: BrainEngine }) => {
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('archive', 'archive')");
+};
+export const wantedKeys = (engine: BrainEngine) => engine.executeRaw<{ key: string }>(
+ "SELECT DISTINCT target_source_id || ':' || target_ref AS key FROM wanted_links ORDER BY 1");
+export const POSSIBLE_WANTED = [{ key: 'archive:people/erin-example' }, { key: 'default:people/bob-example' }];
+
+/** A sweep meeting targets no page can have records only possible ones, lands every valid link and stamps every page. */
+export async function impossibleTargetsNeverAbortTheSweep(databaseUrl?: string) {
+ await managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'people/alice-example', 'Alice.', 'person');
+ await engine.setConfig('wanted_pages.enabled', 'false');
+ await put(ctx, 'src/routes.test.ts', BRACKETED_CODE, 'code');
+ await put(ctx, 'notes/citations', FOREIGN_PREFIXES);
+ await engine.setConfig('wanted_pages.enabled', 'true');
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ await engine.executeRaw("UPDATE pages SET links_extracted_at = NULL WHERE slug IN ('src/routes.test.ts', 'notes/citations')");
+ await extractStale(engine);
+ expect(await stale(engine)).toBe(0);
+ expect(await backlinks(engine, 'people/alice-example')).toEqual([{ slug: 'notes/citations' }, { slug: 'src/routes.test.ts' }]);
+ expect(await wantedKeys(engine)).toEqual(POSSIBLE_WANTED);
+ }, { databaseUrl, setup: registerArchive });
+}
+
+/** A put_page holding such targets succeeds, and its receipt lists exactly the wanted rows the store kept. */
+export async function impossibleTargetsStayOutOfWrites(databaseUrl?: string) {
+ await managedBrain(async ({ engine, ctx }) => {
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ await put(ctx, 'people/alice-example', 'Alice.', 'person');
+ const code = (await put(ctx, 'src/routes.test.ts', BRACKETED_CODE, 'code')).outcome;
+ expect(code.auto_links.wanted).toEqual([{ slug: 'people/bob-example', source_id: 'default' }]);
+ const cited = (await put(ctx, 'notes/citations', FOREIGN_PREFIXES)).outcome;
+ expect(cited.auto_links.wanted_count).toBe(2);
+ expect(cited.auto_links.wanted).toEqual(expect.arrayContaining([{ slug: 'people/bob-example', source_id: 'default' },
+ { slug: 'people/erin-example', source_id: 'archive' }]));
+ expect(await backlinks(engine, 'people/alice-example')).toEqual([{ slug: 'notes/citations' }, { slug: 'src/routes.test.ts' }]);
+ expect(await wantedKeys(engine)).toEqual(POSSIBLE_WANTED);
+ }, { databaseUrl, setup: registerArchive });
+}
diff --git a/test/wanted-links.test.ts b/test/wanted-links.test.ts
index 67a9facb9b..b72dbc5729 100644
--- a/test/wanted-links.test.ts
+++ b/test/wanted-links.test.ts
@@ -3,13 +3,14 @@
* edges when their target appears, stay private, and never loop the stale
* sweep. Postgres arm: test/e2e/wanted-links-postgres.test.ts.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { extractStaleFromDB } from '../src/commands/extract.ts';
-import { collectWantedLinks } from '../src/core/wanted-links.ts';
-import type { LinkCandidate } from '../src/core/link-extraction.ts';
-import { bareNameReferenceSettles, disabledClearsRows, forwardReferenceHeals, onlyUnresolvedAuthoredReferences,
- privateOriginsStayPrivate, restoredTargetHeals } from './helpers/wanted-links-scenarios.ts';
+import { extractStaleFromDB, runExtract } from '../src/commands/extract.ts';
+import { collectWantedLinks, possibleWantedRows } from '../src/core/wanted-links.ts';
+import { LINK_EXTRACTOR_VERSION_TS, type LinkCandidate } from '../src/core/link-extraction.ts';
+import { bareNameReferenceSettles, BRACKETED_CODE, disabledClearsRows, FOREIGN_PREFIXES, forwardReferenceHeals,
+ impossibleTargetsNeverAbortTheSweep, impossibleTargetsStayOutOfWrites, onlyUnresolvedAuthoredReferences, POSSIBLE_WANTED,
+ privateOriginsStayPrivate, restoredTargetHeals, wantedKeys } from './helpers/wanted-links-scenarios.ts';
test('a link written before its target exists becomes an edge after the target is created', () => forwardReferenceHeals(), 120_000);
test('resolved references, prose paths and code spans are never wanted', () => onlyUnresolvedAuthoredReferences(), 120_000);
@@ -17,6 +18,8 @@ test('a bare-name reference matched only by basename settles after one re-extrac
test('remote callers never see targets or counts from private origins', () => privateOriginsStayPrivate(), 120_000);
test('restoring a deleted target heals links written while it was deleted', () => restoredTargetHeals(), 120_000);
test('wanted_pages.enabled=false clears an origin\'s rows on its next extraction', () => disabledClearsRows(), 120_000);
+test('#6228/#6225: the stale sweep skips targets no page can have and finishes', () => impossibleTargetsNeverAbortTheSweep(), 120_000);
+test('#6228/#6225: a put_page records and reports only targets a page can have', () => impossibleTargetsStayOutOfWrites(), 120_000);
describe('collectWantedLinks', () => {
const candidate = (targetSlug: string, key: string, extra: Partial<LinkCandidate> = {}): LinkCandidate => ({
@@ -82,3 +85,38 @@ describe('unmanaged brain', () => {
expect(await engine.executeRaw('SELECT target_ref FROM wanted_links')).toEqual([]);
}, 120_000);
});
+
+describe('#6228/#6225 targets no page can have, unmanaged brain', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('archive', 'archive')");
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ }, 60_000);
+ afterAll(async () => { await engine.disconnect(); }, 60_000);
+
+ test('possibleWantedRows keeps valid slugs, names and registered sources only', async () => {
+ const row = (ref_kind: 'slug' | 'name', target_source_id: string, target_ref: string) => ({ ref_kind, target_source_id, target_ref });
+ const kept = await possibleWantedRows(engine, 'default', [row('slug', 'default', '/api\\.example/, x'), row('slug', 'default', 'a/../b'),
+ row('slug', 'default', 'people/bob-example'), row('name', 'default', 'bob-example'), row('slug', 'memory', '4242'),
+ row('name', 'nowhere', 'erin'), row('slug', 'archive', 'people/erin-example')]);
+ expect(kept).toEqual([row('slug', 'default', 'people/bob-example'), row('name', 'default', 'bob-example'),
+ row('slug', 'archive', 'people/erin-example')]);
+ });
+
+ test('extract links --source db and the stale sweep both finish and land every valid link', async () => {
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: 'Alice.', timeline: '' });
+ await engine.putPage('src/routes.test.ts', { type: 'code', title: 'Routes', compiled_truth: BRACKETED_CODE, timeline: '' });
+ await engine.putPage('notes/citations', { type: 'note', title: 'Citations', compiled_truth: FOREIGN_PREFIXES, timeline: '' });
+ const quiet = spyOn(console, 'log').mockImplementation(() => {});
+ const exit = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`extract exited ${code}`); });
+ try { await runExtract(engine, ['links', '--source', 'db']); } finally { exit.mockRestore(); quiet.mockRestore(); }
+ expect(await wantedKeys(engine)).toEqual(POSSIBLE_WANTED);
+ await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });
+ expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
+ expect(await engine.executeRaw(`SELECT f.slug FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE t.slug = 'people/alice-example' ORDER BY f.slug`)).toEqual([{ slug: 'notes/citations' }, { slug: 'src/routes.test.ts' }]);
+ }, 120_000);
+});