Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(takes): our own implementation of the #5059 fix (#5059)

time-attack8f77799bcb91
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index 01fcba5d93..01d83f428a 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -678,9 +678,10 @@ async function cmdExtract(engine: BrainEngine, rest: string[]): Promise<void> {
}
process.stdout.write(
`takes extract --from-pages: ${result.claims_extracted} claim(s) from ${result.pages_scanned} page(s)` +
- (dryRun ? ' (dry-run)' : '') + '\n' +
- (result.next_before ? `next: --before '${result.next_before}'\n` : ''),
+ (dryRun ? ' (dry-run)' : '') + '\n',
);
+ // Quoted: the cursor's timestamp contains a space.
+ if (result.next_before) process.stdout.write(`next: --before '${result.next_before}'\n`);
}
const BEFORE_CURSOR_RE = /^(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}(?::?\d{2})?)?),([1-9]\d{0,15})$/;
diff --git a/src/core/extract-takes-from-pages.ts b/src/core/extract-takes-from-pages.ts
index 6ec2ac8531..916860e8f7 100644
--- a/src/core/extract-takes-from-pages.ts
+++ b/src/core/extract-takes-from-pages.ts
@@ -62,7 +62,11 @@ export interface ExtractTakesFromPagesOpts {
sourceIdFilter?: string;
/** Max pages to classify per run (caps cost). Default 50. */
maxPages?: number;
- /** #5059: continue strictly below this `(updated_at, id)` keyset cursor (a prior run's `next_before`). */
+ /**
+ * Resume point from an earlier run's `next_before` (#5043): only pages
+ * ordered after it (older `updated_at`, or the same instant and a lower id)
+ * are selected.
+ */
before?: { updatedAt: string; id: number };
/**
* Also rescan pages that already hold takes (refresh semantics).
@@ -89,11 +93,12 @@ export interface ExtractTakesFromPagesResult {
pages_scanned: number;
claims_extracted: number;
/**
- * #5059: `<updated_at>,<id>` of the last page this run processed (exact
- * timestamptz text), or null when it processed none. Pass it to the next
- * run's `--before` to continue past pages that yielded no claims; a page
- * skipped on a failure stays uncovered, so a run without `--before`
- * selects it again.
+ * Where the next run should resume, as `<updated_at text>,<page id>`: the
+ * position of the last page this run finished with, or null if it finished
+ * none. Pages that yield no claims stay uncovered and would otherwise be
+ * selected first forever (#5043); passing this to `--before` moves past
+ * them. A page a budget stop never reached is not counted as finished, and
+ * one skipped on an error stays uncovered for a run without `--before`.
*/
next_before: string | null;
/** True if the run was a no-op because bootstrapEnabled is false. */
@@ -134,6 +139,8 @@ interface PageRow {
type: string;
compiled_truth: string;
updated_at: string | Date;
+ /** `<updated_at::text>,<id>`, the value `next_before` reports for this page. */
+ resume_at: string;
}
/**
@@ -195,13 +202,14 @@ export async function extractTakesFromPages(
const maxPages = opts.maxPages ?? 50;
const holder = opts.holder ?? 'system';
const params: unknown[] = [];
- const sourceFilter = opts.sourceIdFilter ? `AND source_id = $${params.push(opts.sourceIdFilter)}` : '';
- // #5059: keyset continuation. updated_at travels as its exact timestamptz
- // text (microseconds and offset) and binds as text: a ::timestamptz-typed
- // parameter makes postgres.js serialize it through a JS Date (milliseconds).
- const beforeFilter = opts.before
- ? `AND (updated_at, id) < ($${params.push(opts.before.updatedAt)}::text::timestamptz, $${params.push(opts.before.id)})`
- : '';
+ const bind = (value: unknown): string => `$${params.push(value)}`;
+ const scope: string[] = [];
+ if (opts.sourceIdFilter) scope.push(`source_id = ${bind(opts.sourceIdFilter)}`);
+ // Resume strictly after the caller's position in the (updated_at DESC,
+ // id DESC) order. The timestamp is bound as text and cast in SQL so its
+ // microseconds survive; a parameter typed as timestamptz goes through a JS
+ // Date in postgres.js and loses them.
+ if (opts.before) scope.push(`(updated_at, id) < (${bind(opts.before.updatedAt)}::text::timestamptz, ${bind(opts.before.id)})`);
// Fetch eligible pages. Order by updated_at DESC so recently-edited
// pages get bootstrapped first.
@@ -215,14 +223,13 @@ export async function extractTakesFromPages(
? ''
: `AND NOT EXISTS (SELECT 1 FROM takes t WHERE t.page_id = pages.id)`;
const pages = await engine.executeRaw<PageRow>(
- `SELECT id, slug, source_id, type, compiled_truth, updated_at::text AS updated_at
+ `SELECT id, slug, source_id, type, compiled_truth, updated_at, updated_at::text || ',' || id AS resume_at
FROM pages
WHERE type IN (${typesList})
AND deleted_at IS NULL
AND length(COALESCE(compiled_truth, '')) > 200
${coveredFilter}
- ${sourceFilter}
- ${beforeFilter}
+ ${scope.map((condition) => `AND ${condition}`).join(' ')}
ORDER BY updated_at DESC, id DESC
LIMIT ${maxPages}`,
params,
@@ -235,7 +242,6 @@ export async function extractTakesFromPages(
let budgetExhausted = false;
let duplicatesSkipped = 0;
const skipped: Array<{ slug: string; reason: string }> = [];
- let nextBefore: string | null = null;
const model = opts.model || getChatModel();
const meter = new BudgetMeter({
budgetUsd: await resolveBudgetUsd(engine, opts.budgetUsd),
@@ -253,8 +259,6 @@ export async function extractTakesFromPages(
};
for (const page of pages) {
- const previousCursor = nextBefore;
- nextBefore = `${String(page.updated_at)},${page.id}`;
pagesScanned++;
opts.onProgress?.(pagesScanned, pages.length, claimsExtracted);
@@ -296,8 +300,6 @@ export async function extractTakesFromPages(
label: 'takes_bootstrap',
});
if (!budget.allowed) {
- // The page was never classified: the next run resumes at it.
- nextBefore = previousCursor;
budgetExhausted = true;
break;
}
@@ -410,10 +412,12 @@ export async function extractTakesFromPages(
}
}
+ // Every page the loop entered is finished except the one a budget stop broke on.
+ const finished = budgetExhausted ? pagesScanned - 1 : pagesScanned;
return {
pages_scanned: pagesScanned,
claims_extracted: claimsExtracted,
- next_before: nextBefore,
+ next_before: finished > 0 ? pages[finished - 1]!.resume_at : null,
consent_gate_blocked: false,
llm_unavailable: false,
pages_skipped: pagesSkipped,
diff --git a/test/extract-takes-bootstrap-safety.test.ts b/test/extract-takes-bootstrap-safety.test.ts
index 218fa6b861..c7cedcfc23 100644
--- a/test/extract-takes-bootstrap-safety.test.ts
+++ b/test/extract-takes-bootstrap-safety.test.ts
@@ -107,29 +107,6 @@ describe('takes bootstrap safety (B-14)', () => {
expect(chatCalls).toBe(0);
expect(result.budget_exhausted).toBe(true);
expect(result.claims_extracted).toBe(0);
- expect(result.next_before).toBeNull();
- });
-
- test('#5059: a budget-limited cursor resumes at the first unclassified page, not past it', async () => {
- await seed('concepts/budget-tail');
- await seed('concepts/budget-head');
- await engine.executeRaw(`UPDATE pages SET updated_at = '2030-01-02T03:04:05.123456Z'::timestamptz`);
- const [head] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', ['concepts/budget-head']);
- reply = () => '[]';
- const first = await extractTakesFromPages(engine, { bootstrapEnabled: true, budgetUsd: 0.015 });
- expect(chatCalls).toBe(1);
- expect(first.budget_exhausted).toBe(true);
- expect(first.next_before).toEndWith(`,${head!.id}`);
- const separator = first.next_before!.lastIndexOf(',');
-
- reply = () => '[{"claim":"The older page still gets classified","kind":"take","weight":0.5}]';
- const second = await extractTakesFromPages(engine, {
- bootstrapEnabled: true,
- before: { updatedAt: first.next_before!.slice(0, separator), id: Number(first.next_before!.slice(separator + 1)) },
- });
- expect(second.pages_scanned).toBe(1);
- expect(second.claims_extracted).toBe(1);
- expect(chatCalls).toBe(2);
});
test('the budget reads takes.bootstrap_budget_usd', async () => {
diff --git a/test/extract-takes-from-pages-progression.test.ts b/test/extract-takes-from-pages-progression.test.ts
index 8f09235500..8454b26366 100644
--- a/test/extract-takes-from-pages-progression.test.ts
+++ b/test/extract-takes-from-pages-progression.test.ts
@@ -101,91 +101,4 @@ describe('extractTakesFromPages — bootstrap progression', () => {
});
expect(r4.pages_scanned).toBe(3);
});
-
- // #5059: a page that yields zero claims stays uncovered, so the plain
- // updated_at-DESC selection re-picked it first forever. next_before is the
- // exact (updated_at, id) keyset position of the last processed page.
- function transport(textFor: (content: string) => string | Error): void {
- __setChatTransportForTests(async (opts) => {
- const content = String(opts.messages[0]?.content ?? '');
- const text = textFor(content);
- if (text instanceof Error) throw text;
- return {
- text,
- blocks: [{ type: 'text' as const, text }],
- stopReason: 'end' as const,
- usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
- model: 'anthropic:claude-haiku-4-5-20251001',
- providerId: 'anthropic',
- };
- });
- }
-
- function cursorOf(nextBefore: string | null): { updatedAt: string; id: number } {
- const separator = nextBefore!.lastIndexOf(',');
- return { updatedAt: nextBefore!.slice(0, separator), id: Number(nextBefore!.slice(separator + 1)) };
- }
-
- async function seedAt(slug: string, at: string): Promise<number> {
- const body = `A narrative body for ${slug} long enough to clear the 200-char eligibility floor. `.repeat(4);
- await engine.putPage(slug, { type: 'concept', title: slug, compiled_truth: body, frontmatter: {} });
- seedMd(slug, body);
- await engine.executeRaw(`UPDATE pages SET updated_at = $2::text::timestamptz WHERE slug = $1`, [slug, at]);
- const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);
- return row!.id;
- }
-
- test('a cursor advances past a newest page that yields no claims (equal timestamps break on id)', async () => {
- const olderSlug = 'concepts/claim-bearing-older';
- const newestSlug = 'concepts/zero-claim-newest';
- await seedAt(olderSlug, '2030-01-02T03:04:05.123456Z');
- const newestId = await seedAt(newestSlug, '2030-01-02T03:04:05.123456Z');
- transport((content) => content.includes(newestSlug) ? '[]' : '[{"claim":"an older claim","kind":"take","weight":0.7}]');
-
- const first = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1, sourceIdFilter: 'default' });
- expect(first.pages_scanned).toBe(1);
- expect(first.claims_extracted).toBe(0);
- expect(first.next_before).toEndWith(`,${newestId}`);
-
- const again = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1, sourceIdFilter: 'default' });
- expect(again.next_before).toBe(first.next_before);
-
- const second = await extractTakesFromPages(engine, {
- bootstrapEnabled: true, maxPages: 1, sourceIdFilter: 'default', before: cursorOf(first.next_before),
- });
- expect(second.pages_scanned).toBe(1);
- expect(second.claims_extracted).toBe(1);
- });
-
- test('the cursor keeps microsecond precision: a page 1 microsecond older is not skipped', async () => {
- await seedAt('concepts/micro-newer', '2031-05-06T07:08:09.123457Z');
- await seedAt('concepts/micro-older', '2031-05-06T07:08:09.123456Z');
- transport(() => '[]');
- const first = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1, dryRun: true });
- expect(first.next_before).toContain('.123457');
- let seen = '';
- transport((content) => { seen = content; return '[]'; });
- const second = await extractTakesFromPages(engine, {
- bootstrapEnabled: true, maxPages: 1, dryRun: true, before: cursorOf(first.next_before),
- });
- expect(second.pages_scanned).toBe(1);
- expect(seen).toContain('concepts/micro-older');
- });
-
- test('a page whose model call failed is reported and selected again by a run without --before', async () => {
- const failing = 'concepts/flaky-newest';
- const failingId = await seedAt(failing, '2032-01-01T00:00:00.000001Z');
- transport((content) => content.includes(failing) ? new Error('provider overloaded') : '[]');
- const first = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1 });
- expect(first.skipped).toEqual([{ slug: failing, reason: expect.stringMatching(/^llm_error:/) }]);
- expect(first.next_before).toEndWith(`,${failingId}`);
-
- transport(() => '[{"claim":"recovered claim","kind":"take","weight":0.6}]');
- const retry = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1 });
- expect(retry.pages_scanned).toBe(1);
- expect(retry.claims_extracted).toBe(1);
- const [covered] = await engine.executeRaw<{ n: number }>(
- 'SELECT count(*)::int AS n FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1', [failing]);
- expect(covered!.n).toBe(1);
- });
});
diff --git a/test/extract-takes-resume-cursor.test.ts b/test/extract-takes-resume-cursor.test.ts
new file mode 100644
index 0000000000..8f3a78c08b
--- /dev/null
+++ b/test/extract-takes-resume-cursor.test.ts
@@ -0,0 +1,171 @@
+/**
+ * Resuming `takes extract --from-pages` with `next_before` / `--before` (#5043).
+ *
+ * Protects: a page that yields no claims holds no takes, so it stays eligible
+ * and, newest first under a LIMIT, is selected again ahead of everything
+ * older. Chaining each run's `next_before` into the next run's `--before`
+ * must visit every eligible page exactly once, in (updated_at DESC, id DESC)
+ * order, keeping equal timestamps apart by id and microsecond differences
+ * intact. A budget stop must resume at the page it never classified, and a
+ * page whose model call failed is passed by the cursor but retried by a plain
+ * run. The cursor round-trips through the CLI's own parser
+ * (`parseTakesBeforeCursor`), so what a run prints is what `--before`
+ * accepts.
+ *
+ * Regression it catches: no cursor (each run re-selects the same zero-claim
+ * slice), a millisecond-truncated cursor, a missing id tie-break, or a budget
+ * stop that reports the unclassified page as finished.
+ *
+ * Negative control: runs without `--before` keep re-selecting the newest
+ * zero-claim page, which is the defect the cursor exists to get past.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { extractTakesFromPages } from '../src/core/extract-takes-from-pages.ts';
+import { parseTakesBeforeCursor } from '../src/commands/takes.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const NO_CLAIMS = '[]';
+const ONE_CLAIM = '[{"claim":"Small teams ship faster","kind":"take","weight":0.6}]';
+
+let engine: PGLiteEngine;
+let repo: string;
+/** Slugs the classifier saw, in call order. */
+let seen: string[] = [];
+let answerFor: (slug: string) => string | Error = () => NO_CLAIMS;
+
+async function eligiblePage(slug: string, updatedAt: string): Promise<number> {
+ const body = `Notes on ${slug}: a long enough opinion-bearing body to pass the 200-character eligibility floor. `.repeat(3);
+ await engine.putPage(slug, { type: 'concept', title: slug, compiled_truth: body, frontmatter: {} });
+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\n${body}\n`, 'utf-8');
+ const [row] = await engine.executeRaw<{ id: number }>(
+ `UPDATE pages SET updated_at = $2::text::timestamptz WHERE slug = $1 RETURNING id`, [slug, updatedAt],
+ );
+ return Number(row!.id);
+}
+
+function resumeAfter(nextBefore: string | null) {
+ expect(nextBefore).not.toBeNull();
+ return parseTakesBeforeCursor(['--from-pages', '--before', nextBefore!])!;
+}
+
+async function slugsInSweepOrder(): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages ORDER BY updated_at DESC, id DESC`);
+ return rows.map((r) => r.slug);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gb-takes-resume-'));
+ mkdirSync(join(repo, 'concepts'), { recursive: true });
+ configureGateway({ chat_model: 'anthropic:claude-haiku-4-5-20251001', env: { ANTHROPIC_API_KEY: 'sk-ant-test-takes-resume' } });
+ __setChatTransportForTests(async (req) => {
+ const slug = /<page slug="([^"]+)"/.exec(String(req.messages[0]?.content ?? ''))?.[1] ?? '';
+ seen.push(slug);
+ const answer = answerFor(slug);
+ if (answer instanceof Error) throw answer;
+ return {
+ text: answer, blocks: [{ type: 'text' as const, text: answer }], stopReason: 'end' as const,
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5-20251001', providerId: 'anthropic',
+ };
+ });
+});
+
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ rmSync(repo, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('sync.repo_path', repo);
+ seen = [];
+ answerFor = () => NO_CLAIMS;
+});
+
+describe('takes extract resume cursor (#5043)', () => {
+ test('chaining next_before visits every zero-claim page once, ties by id, microseconds intact, then ends', async () => {
+ await eligiblePage('concepts/tie-first', '2030-03-01 10:00:00.000002+00');
+ await eligiblePage('concepts/tie-second', '2030-03-01 10:00:00.000002+00');
+ await eligiblePage('concepts/one-microsecond-older', '2030-03-01 10:00:00.000001+00');
+ await eligiblePage('concepts/last-year', '2029-03-01 10:00:00+00');
+
+ let before: { updatedAt: string; id: number } | undefined;
+ const cursors: string[] = [];
+ for (let run = 0; run < 8; run++) {
+ const result = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1, ...(before ? { before } : {}) });
+ if (result.pages_scanned === 0) {
+ expect(result.next_before).toBeNull();
+ break;
+ }
+ expect(result.claims_extracted).toBe(0);
+ cursors.push(result.next_before!);
+ before = resumeAfter(result.next_before);
+ }
+
+ expect(seen).toEqual(await slugsInSweepOrder());
+ expect(cursors[2]).toStartWith('2030-03-01 10:00:00.000001');
+ });
+
+ test('negative control: without --before the newest zero-claim page is selected again every run', async () => {
+ await eligiblePage('concepts/older-with-claims', '2030-01-01 00:00:00+00');
+ await eligiblePage('concepts/newest-no-claims', '2030-02-01 00:00:00+00');
+
+ const first = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1 });
+ const second = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1 });
+
+ expect(seen).toEqual(['concepts/newest-no-claims', 'concepts/newest-no-claims']);
+ expect(second.next_before).toBe(first.next_before);
+ });
+
+ test('a budget stop reports the last classified page, so the next run classifies the page it stopped on', async () => {
+ const newestId = await eligiblePage('concepts/budget-newest', '2030-05-05 05:05:05.5+00');
+ await eligiblePage('concepts/budget-stopped-on', '2030-05-05 05:05:05.4+00');
+
+ const stopped = await extractTakesFromPages(engine, { bootstrapEnabled: true, budgetUsd: 0.015 });
+ expect(stopped.budget_exhausted).toBe(true);
+ expect(seen).toEqual(['concepts/budget-newest']);
+ expect(resumeAfter(stopped.next_before).id).toBe(newestId);
+
+ answerFor = () => ONE_CLAIM;
+ const resumed = await extractTakesFromPages(engine, { bootstrapEnabled: true, before: resumeAfter(stopped.next_before) });
+ expect(seen).toEqual(['concepts/budget-newest', 'concepts/budget-stopped-on']);
+ expect(resumed.claims_extracted).toBe(1);
+ });
+
+ test('a budget that stops before the first page reports no resume point', async () => {
+ await eligiblePage('concepts/never-classified', '2030-06-06 06:06:06+00');
+ const stopped = await extractTakesFromPages(engine, { bootstrapEnabled: true, budgetUsd: 0.0000001 });
+ expect(stopped.budget_exhausted).toBe(true);
+ expect(stopped.pages_scanned).toBe(1);
+ expect(stopped.next_before).toBeNull();
+ expect(seen).toEqual([]);
+ });
+
+ test('a failed model call is passed by the cursor and retried by a plain run', async () => {
+ await eligiblePage('concepts/after-the-outage', '2030-07-01 00:00:00+00');
+ const flakyId = await eligiblePage('concepts/hit-the-outage', '2030-07-02 00:00:00+00');
+ answerFor = (slug) => slug === 'concepts/hit-the-outage' ? new Error('upstream overloaded') : ONE_CLAIM;
+
+ const failed = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1 });
+ expect(failed.skipped.map((s) => s.slug)).toEqual(['concepts/hit-the-outage']);
+ expect(resumeAfter(failed.next_before).id).toBe(flakyId);
+
+ await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1, before: resumeAfter(failed.next_before) });
+ expect(seen.at(-1)).toBe('concepts/after-the-outage');
+
+ answerFor = () => ONE_CLAIM;
+ const retried = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 1 });
+ expect(seen.at(-1)).toBe('concepts/hit-the-outage');
+ expect(retried.claims_extracted).toBe(1);
+ });
+});
diff --git a/test/takes-extract-json.test.ts b/test/takes-extract-json.test.ts
index 5fe0001a85..1d823b612f 100644
--- a/test/takes-extract-json.test.ts
+++ b/test/takes-extract-json.test.ts
@@ -67,18 +67,27 @@ describe('gbrain takes extract --from-pages --json (#3962)', () => {
});
});
- test('#5059: --before binds the exact cursor after the source parameter', async () => {
+ test('--before reaches the page query as bound parameters, never as SQL text', async () => {
queries.length = 0;
+ const cursorTs = '2031-07-08 09:10:11.654321-05';
await captureStdout(() =>
- runTakes(engine, [
- 'extract', '--from-pages', '--dry-run', '--json',
- '--source-id', 'default',
- '--before', '2030-01-02 03:04:05.123456+00,42',
- ]));
- const lastQuery = queries.at(-1);
- expect(lastQuery?.sql).toContain('(updated_at, id) < ($2::text::timestamptz, $3)');
- expect(lastQuery?.sql).toContain('ORDER BY updated_at DESC, id DESC');
- expect(lastQuery?.params).toEqual(['default', '2030-01-02 03:04:05.123456+00', 42]);
+ runTakes(engine, ['extract', '--from-pages', '--json', '--dry-run', '--before', `${cursorTs},977`, '--source-id', 'default']));
+ const pageQuery = queries.find((q) => q.sql.includes('FROM pages'));
+ expect(pageQuery).toBeDefined();
+ expect(pageQuery!.sql).not.toContain(cursorTs);
+ expect(pageQuery!.sql).not.toContain('977');
+ expect(pageQuery!.params).toEqual(['default', cursorTs, 977]);
+ // Bound as text, cast in SQL: postgres.js would round a timestamptz-typed bind to milliseconds.
+ expect(pageQuery!.sql).toMatch(/\(updated_at, id\) < \(\$2::text::timestamptz, \$3\)/);
+ expect(pageQuery!.sql).toMatch(/ORDER BY updated_at DESC, id DESC/);
+ });
+
+ test('negative control: without --before the page query carries no cursor condition', async () => {
+ queries.length = 0;
+ await captureStdout(() => runTakes(engine, ['extract', '--from-pages', '--json', '--dry-run']));
+ const pageQuery = queries.find((q) => q.sql.includes('FROM pages'));
+ expect(pageQuery!.sql).not.toContain('(updated_at, id) <');
+ expect(pageQuery!.params).toEqual([]);
});
});
@@ -117,7 +126,7 @@ describe('takes extract --before cursor validation (#5059)', () => {
const pageEngine = {
getConfig: async (key: string) => key === 'takes.bootstrap_enabled' ? 'true' : null,
executeRaw: async (sql: string) => sql.includes('FROM pages')
- ? [{ id: 9, slug: 'concepts/short', source_id: 'default', type: 'concept', compiled_truth: 'too short', updated_at: '2030-01-02 03:04:05.123456+00' }]
+ ? [{ id: 9, slug: 'concepts/short', source_id: 'default', type: 'concept', compiled_truth: 'too short', updated_at: new Date('2030-01-02T03:04:05.123Z'), resume_at: '2030-01-02 03:04:05.123456+00,9' }]
: [],
} as unknown as BrainEngine;
const stdout = await captureStdout(() => runTakes(pageEngine, ['extract', '--from-pages', '--dry-run']));