Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract): extract all --source db stamps only pages both phases completed (S4)

time-attacke9c1a9f02de3
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 53ba6f2590..7cf4d30546 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilo
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
src/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)
-src/commands/extract.ts 2626 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts)
+src/commands/extract.ts 2629 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)
src/core/ai/gateway.ts 4457 ratchet +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here)
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index cc94984771..7ff80bd10b 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -162,6 +162,7 @@ test/eval-longmemeval-synopsis-tier.serial.test.ts R1 R1: mutates process.env (G
test/eval-retrieval-quality-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)
test/eval-run-all-outcome.serial.test.ts R2 R2: mock.module(../src/commands/eval-brainbench.ts) replaces modules for every file in the process; spyOn process.stderr.write
test/eval-takes-quality-runner.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/extract-all-stamp-intersection.serial.test.ts global-state global-state: spyOn process.exit; patches console
test/extract-conversation-facts-diagnostics.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests, __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; spyOn console.log, process.exit, concurrency.resolveWorkersWithClamp, console.error (+2 more)
test/extract-cross-source-links-db.serial.test.ts R1 R1: mutates process.env (bracket or computed key)
test/extract-endpoint-revision.serial.test.ts global-state global-state: spyOn console.error, process.exit
diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.ts
index b93cc4c9b4..d113f2cfcc 100644
--- a/src/commands/extract-timeline-db.ts
+++ b/src/commands/extract-timeline-db.ts
@@ -34,7 +34,7 @@ import { readFix } from '../core/ops/op-fix.ts';
import { createProgress } from '../core/progress.ts';
import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../core/planner-stats.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
-import { filterRefsSince } from './extract.ts';
+import { extractCompletionKey, filterRefsSince } from './extract.ts';
import { isQuarantined } from '../core/quarantine.ts';
import { pageSnapshotKey } from '../core/page-snapshot-batch.ts';
import type { PageSnapshot } from '../core/page-state/types.ts';
@@ -65,6 +65,8 @@ export interface TimelineDbOptions {
inferDates?: boolean;
/** Restrict the walk to these slugs (requires sourceIdFilter). */
slugs?: readonly string[];
+ /** S4 (P2.18): receives `extractCompletionKey` for each page whose timeline write landed (or had nothing to write). */
+ completed?: Set<string>;
}
/**
@@ -125,13 +127,18 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
const analyzeEvery = opts.dryRun ? 0 : await importAnalyzeEveryPages(engine);
let walked = 0;
+ // Unmanaged pages whose rows sit in the unflushed batch, and pages a refused batch held: completion follows the flush.
+ const unflushed = new Set<string>(), refusedPages = new Set<string>();
async function flush() {
if (batch.length === 0) return;
- const snapshot = batch.slice();
+ const snapshot = batch.slice(), held = [...unflushed];
batch.length = 0;
+ unflushed.clear();
try {
result.created += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_db' }));
+ for (const key of held) if (!refusedPages.has(key)) opts.completed?.add(key);
} catch (e) {
+ for (const key of held) { refusedPages.add(key); opts.completed?.delete(key); }
const code = refusalCode(e);
codes.add(code);
result.refused += snapshot.length;
@@ -157,7 +164,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
{ snapshot, stored: snapshot ? readBatch.stored.get(Number(snapshot.page.id)) ?? [] : [] });
if (outcome === 'skipped') result.skipped++;
else if (outcome === 'pending') result.pending++;
- else if (outcome !== null) { result.created += outcome; result.pages++; }
+ else if (outcome !== null) { result.created += outcome; result.pages++; opts.completed?.add(extractCompletionKey(source_id, slug, snapshot!.revision)); }
} catch (e) {
const code = refusalCode(e);
codes.add(code);
@@ -180,7 +187,9 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
const anchor = anchorFor(page, slug);
if (anchor) entries = [anchor];
}
- for (const entry of entries) {
+ const completion = extractCompletionKey(source_id, slug, snapshot!.revision);
+ if (!opts.dryRun) { if (entries.length) unflushed.add(completion); else opts.completed?.add(completion); }
+ for (const [n, entry] of entries.entries()) {
if (dryRunSeen) {
const key = `${source_id}::${slug}::${entry.date}::${entry.summary}`;
if (dryRunSeen.has(key)) continue;
@@ -196,7 +205,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
result.created++;
} else {
batch.push({ slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id });
- if (batch.length >= BATCH_SIZE) await flush();
+ if (batch.length >= BATCH_SIZE) { await flush(); if (n < entries.length - 1) unflushed.add(completion); }
}
}
result.pages++;
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 59379038cf..fa3607327d 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -132,6 +132,21 @@ export const STALE_TIME_BUDGET_MS = Math.max(1000, Number(process.env.GBRAIN_EXT
* itself: there the stamp is the resume mechanism and a failure must surface
* (CDX-4 — see extractStaleFromDB).
*/
+/** S4 (P2.18): one page's completion of a DB extract phase, at the revision that phase read. */
+export const extractCompletionKey = (sourceId: string, slug: string, revision: string) => `${sourceId}\0${slug}\0${revision}`;
+
+/** S4 (P2.18): stamp the pages both DB phases completed at the same revision, if the page is still at it. */
+async function stampCompletedIntersection(engine: BrainEngine, links: Set<string>, timeline: Set<string>): Promise<void> {
+ const both = [...links].filter(key => timeline.has(key)).map(key => key.split('\0'));
+ for (let i = 0; i < both.length; i += BATCH_SIZE) {
+ const chunk = both.slice(i, i + BATCH_SIZE);
+ const live = await engine.executeRaw<{ slug: string; source_id: string }>(`SELECT p.slug,p.source_id FROM pages p
+ JOIN unnest($1::text[],$2::text[],$3::text[]) AS t(source_id,slug,revision) ON p.source_id=t.source_id AND p.slug=t.slug
+ WHERE p.knowledge_revision::text=t.revision AND p.deleted_at IS NULL`, [chunk.map(k => k[0]), chunk.map(k => k[1]), chunk.map(k => k[2])]);
+ await stampExtracted(engine, live);
+ }
+}
+
export async function stampExtracted(
engine: BrainEngine,
refs: Array<{ slug: string; source_id: string; extractedAt?: string }>,
@@ -1231,22 +1246,27 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?
if (!byMention) result.pages_processed += r.pages;
}
} else {
- if (subcommand === 'links' || subcommand === 'all') {
- // C3 (D6): only stamp the combined links+timeline watermark when BOTH
- // ran ('all'); a links-only run must not mark timeline fresh.
- const r = await extractLinksFromDB(engine, dryRun, jsonMode, typeFilter, since, { includeFrontmatter, sourceIdFilter, stampWatermark: subcommand === 'all' });
- result.links_created = r.created;
- result.pages_processed = r.pages;
- // #2589: "counted, never silent" reaches the --json summary too —
- // additive fields, only present on the DB links path.
- result.skipped_missing_target = r.skippedMissingTarget;
- result.skipped_cross_source = r.skippedCrossSource;
- if (r.skippedAttendanceIncomplete) result.skipped_attendance_incomplete = r.skippedAttendanceIncomplete;
- if (r.skippedConcurrentWrite) result.skipped_concurrent_write = r.skippedConcurrentWrite;
- }
- if (subcommand === 'timeline' || subcommand === 'all') {
- const r = await (await import('./extract-timeline-db.ts')).extractTimelineFromDB(engine, { dryRun, jsonMode, typeFilter, since, sourceIdFilter, inferDates });
- Object.assign(result, { timeline_entries_created: r.created, pages_processed: Math.max(result.pages_processed, r.pages) }, r.refused + r.pending ? { timeline_refused: r.refused + r.pending } : {});
+ // v0.42.7 (#1696) + S4 (P2.18): 'all' stamps the watermark for the pages both phases completed at one revision
+ // (zero-link pages included), in a finally, so a throwing phase still keeps what both finished.
+ const completed = subcommand === 'all' && !dryRun ? { links: new Set<string>(), timeline: new Set<string>() } : null;
+ try {
+ if (subcommand === 'links' || subcommand === 'all') {
+ const r = await extractLinksFromDB(engine, dryRun, jsonMode, typeFilter, since, { includeFrontmatter, sourceIdFilter, completed: completed?.links });
+ result.links_created = r.created;
+ result.pages_processed = r.pages;
+ // #2589: "counted, never silent" reaches the --json summary too —
+ // additive fields, only present on the DB links path.
+ result.skipped_missing_target = r.skippedMissingTarget;
+ result.skipped_cross_source = r.skippedCrossSource;
+ if (r.skippedAttendanceIncomplete) result.skipped_attendance_incomplete = r.skippedAttendanceIncomplete;
+ if (r.skippedConcurrentWrite) result.skipped_concurrent_write = r.skippedConcurrentWrite;
+ }
+ if (subcommand === 'timeline' || subcommand === 'all') {
+ const r = await (await import('./extract-timeline-db.ts')).extractTimelineFromDB(engine, { dryRun, jsonMode, typeFilter, since, sourceIdFilter, inferDates, completed: completed?.timeline });
+ Object.assign(result, { timeline_entries_created: r.created, pages_processed: Math.max(result.pages_processed, r.pages) }, r.refused + r.pending ? { timeline_refused: r.refused + r.pending } : {});
+ }
+ } finally {
+ if (completed) await stampCompletedIntersection(engine, completed.links, completed.timeline);
}
}
} else {
@@ -1806,15 +1826,13 @@ async function extractLinksFromDB(
jsonMode: boolean,
typeFilter: PageType | undefined,
since: string | undefined,
- opts?: { includeFrontmatter?: boolean; sourceIdFilter?: string; stampWatermark?: boolean },
+ opts?: { includeFrontmatter?: boolean; sourceIdFilter?: string; completed?: Set<string> },
): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number; skippedAttendanceIncomplete: number; skippedConcurrentWrite?: number }> {
const includeFrontmatter = opts?.includeFrontmatter ?? false;
const sourceIdFilter = opts?.sourceIdFilter;
- // C3 (D6): the links_extracted_at watermark covers links AND timeline, so a
- // links-ONLY run must NOT stamp it (that would hide timeline staleness for
- // `gbrain extract links --source db`). Only stamp when the caller ran BOTH
- // (subcommand 'all'). Caller passes stampWatermark accordingly.
- const stampWatermark = opts?.stampWatermark ?? false;
+ // C3 (D6) + S4 (P2.18): the links_extracted_at watermark covers links AND timeline, so this phase never stamps it;
+ // it reports each page it published (keyed by revision) to the caller's `completed`, and 'all' stamps the pages
+ // both phases completed.
const resolvers = new Map<string, ReturnType<typeof makeResolver>>();
const unresolved: UnresolvedFrontmatterRef[] = [];
// Issue #972: opt-in global-basename wikilink resolution. Read once
@@ -1883,10 +1901,6 @@ async function extractLinksFromDB(
// design (source isolation) unless the #3908 flag is on, but distinct
// from a genuinely missing target.
let skippedCrossSource = 0;
- // v0.42.7 (#1696): pages whose links we extracted this run — stamped after
- // the loop so a manual `gbrain extract links|all --source db` clears the
- // links_extraction_lag doctor signal. Non-dry-run only.
- const processedRefs: Array<{ slug: string; source_id: string }> = [];
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
const grammar = await readLineGrammarSettings(engine), lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
@@ -1906,11 +1920,11 @@ async function extractLinksFromDB(
const results = await replaceDerivedLinksBatchOrReplay(engine, writes.map(write => write.item), item => {
if (jsonMode) process.stderr.write(JSON.stringify({ event: 'batch_error', size: item.links.length, code: 'graph_write_failed' }) + '\n');
});
- writes.forEach(({ slug, source_id }, i) => {
+ writes.forEach(({ slug, source_id, item }, i) => {
const written = results[i];
if (written === 'settings_changed') skippedSettingsChanged++;
else if (written === 'concurrent_write') skippedConcurrentWrite++;
- else { created += written.created; processed++; processedRefs.push({ slug, source_id }); }
+ else { created += written.created; processed++; if (!dryRun) opts?.completed?.add(extractCompletionKey(source_id, slug, item.origin.expectedRevision)); }
progress.tick(1);
});
}
@@ -2010,17 +2024,6 @@ async function extractLinksFromDB(
progress.tick(1);
}
await flushLinkWrites();
- // v0.42.7 (#1696): stamp the extraction watermark for every page we
- // processed (incl. zero-link pages — they WERE extracted). Chunked so the
- // unnest UPDATE stays bounded on big brains. Best-effort (stampExtracted
- // swallows): a stamp miss just leaves the page for extract --stale.
- // C3 (D6): ONLY when both links + timeline ran (stampWatermark) — a
- // links-only run leaves the combined watermark untouched.
- if (!dryRun && stampWatermark) {
- for (let i = 0; i < processedRefs.length; i += BATCH_SIZE) {
- await stampExtracted(engine, processedRefs.slice(i, i + BATCH_SIZE));
- }
- }
progress.finish();
if (!jsonMode) {
diff --git a/test/extract-all-stamp-intersection.serial.test.ts b/test/extract-all-stamp-intersection.serial.test.ts
new file mode 100644
index 0000000000..6f80d67d5f
--- /dev/null
+++ b/test/extract-all-stamp-intersection.serial.test.ts
@@ -0,0 +1,72 @@
+/**
+ * S4 (P2.18, R11): `extract all --source db` stamped every page's combined links+timeline watermark from the links
+ * phase, before the timeline phase ran. A timeline phase that threw (or a page edited between the phases) left pages
+ * marked fresh whose timeline was never extracted. Each phase now reports the pages it completed, keyed by revision,
+ * to the caller, which stamps their intersection in a finally. Synthetic content.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const sourceId = 'stamp-intersection';
+const PAGES = 105;
+const slug = (i: number) => `notes/p-${String(i).padStart(3, '0')}`;
+
+for (const kind of ['pglite', ...(process.env.DATABASE_URL ? ['postgres'] : [])]) {
+ describe(`extract all --source db stamps only what both phases completed (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; close = pg.close; }
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);
+ for (let i = 0; i < PAGES; i++) {
+ await engine.putPage(slug(i), { type: 'note', title: slug(i), compiled_truth: `Links [[${slug((i + 1) % PAGES)}]].`, timeline: `- **2024-01-${String(1 + (i % 28)).padStart(2, '0')}** | Event ${i}` }, { sourceId });
+ }
+ }, 180_000);
+ afterAll(async () => { await close?.(); });
+
+ test('a timeline phase that throws after its first batch committed: those pages are stamped, the rest and an edited page are not', async () => {
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1', [sourceId]);
+ const original = engine.readPageSnapshotsBatch;
+ let calls = 0;
+ // The timeline phase's reads (readTimelineBatch): before its first, another writer edits the first page; its second throws.
+ engine.readPageSnapshotsBatch = async function (this: BrainEngine, ...args) {
+ if (new Error().stack?.includes('readTimelineBatch')) {
+ calls++;
+ if (calls === 1) await engine.putPage(slug(0), { type: 'note', title: slug(0), compiled_truth: 'Edited between phases.', timeline: '- **2024-02-01** | Edited' }, { sourceId });
+ if (calls === 2) throw new Error('timeline read failed');
+ }
+ // A transaction's engine inherits this method: keep its own receiver.
+ return original.apply(this, args);
+ };
+ const errorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});
+ const exitSpy = spyOn(process, 'exit').mockImplementation(code => { throw new Error(`extract exited ${code}`); });
+ try {
+ await expect(runExtract(engine, ['all', '--source', 'db', '--source-id', sourceId, '--json'])).rejects.toThrow('extract exited 1');
+ } finally {
+ engine.readPageSnapshotsBatch = original;
+ errorSpy.mockRestore(); logSpy.mockRestore(); exitSpy.mockRestore();
+ }
+ expect(calls).toBe(2);
+ const rows = await engine.executeRaw<{ slug: string; stamped: boolean }>(
+ 'SELECT slug,links_extracted_at IS NOT NULL AS stamped FROM pages WHERE source_id=$1 ORDER BY slug', [sourceId]);
+ const stamped = new Set(rows.filter(r => r.stamped).map(r => r.slug));
+ // Timeline's first batch (pages 0..99) committed; page 0 moved between the phases, so its two completions differ.
+ for (let i = 1; i < 100; i++) expect(stamped.has(slug(i))).toBe(true);
+ expect(stamped.has(slug(0))).toBe(false);
+ for (let i = 100; i < PAGES; i++) expect(stamped.has(slug(i))).toBe(false);
+ }, 180_000);
+
+ test('a clean run stamps every page', async () => {
+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1', [sourceId]);
+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});
+ try { await runExtract(engine, ['all', '--source', 'db', '--source-id', sourceId, '--json']); } finally { logSpy.mockRestore(); }
+ const [row] = await engine.executeRaw<{ n: number | string }>('SELECT count(*) AS n FROM pages WHERE source_id=$1 AND links_extracted_at IS NULL', [sourceId]);
+ expect(Number(row!.n)).toBe(0);
+ }, 180_000);
+ });
+}