Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wake a bare-name link's page when its target is first written during an extraction
garrytanf664526b383d
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bdb793e6ee..97e1a87c5c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilosrc/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +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; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)src/commands/embed.ts 2306 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); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +2 agent operator wave D2: --json failure envelope via writeCliErrorsrc/commands/extract-conversation-facts.ts 1949 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); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts); +3 #7438: ExtractConversationFactsResult.facts_skipped_purged (interface field) and one notePurgedSkips call (the count and log live in core/facts/conversation-publication.ts); grown v0.46.x per-provider gateway-unavailable copy; re-summed at the Wave B PR 4 merge with v0.60.452.0 (1949 measured)-src/commands/extract.ts 2700 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); 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; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured; +16 #7394: --type/--since/--infer-dates on the file walk refuse with the --source db command beside the other --source db refusals, and the help says so; +5 GBRA-161 PR 5 (T-2, L-6): timeline retraction and the mention rebuild sweep are bound to the revision they read (PageRevisionConflictError import, the scanned-revision read and its FOR SHARE check); +2 GBRA-133: ExtractOpts.timeBudgetMs, forwarded to the managed stale-page pass so the cycle bounds a pass with no slug list+src/commands/extract.ts 2701 ratchet +1 GST-2460: the wanted-link read time taken before extractLinksFromDB's slug snapshot; +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); 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; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured; +16 #7394: --type/--since/--infer-dates on the file walk refuse with the --source db command beside the other --source db refusals, and the help says so; +5 GBRA-161 PR 5 (T-2, L-6): timeline retraction and the mention rebuild sweep are bound to the revision they read (PageRevisionConflictError import, the scanned-revision read and its FOR SHARE check); +2 GBRA-133: ExtractOpts.timeBudgetMs, forwarded to the managed stale-page pass so the cycle bounds a pass with no slug listsrc/commands/jobs.ts 693 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; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts); +20 #7242 jobs wait: subcommand row, import, usage lines and its --help text with the exit codes (logic in jobs/wait.ts); +6 GBRA-283 B3a: runJobs enters the local scope (withLocalScope; scope store in core/engine-scope-store.ts), the entry wrapper and its import cannot movesrc/commands/serve-http.ts 947 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); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts); +4 GBRA-199: serve --http --advertise parse, help line and pass-through (logic in mcp/surface.ts parseAdvertiseFlag); +6 GBRA-283 B3a: runServeHttp enters the local scope (withLocalScope; scope store in core/engine-scope-store.ts), the entry wrapper and its import cannot movesrc/core/ai/gateway.ts 4571 ratchet +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +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); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given; +1 GBRA-283 B2 (#8499 item 1): requireConfig refuses an unscoped call in a process holding embedded engines (engine_scope_missing; predicate in engine-scope.ts); +7 GBRA-283 B3a: every embed/chat/expand/rerank/toolLoop entry and requireConfig/configFor call refuseUnscoped (predicate and refusal in ai/engine-gateway.ts), the unscoped state, and the shrink/no_key/structured-output memory read through gw() (state in ai/engine-gateway.ts GatewayState)diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex f238a05b0e..407184c263 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -48,7 +48,7 @@ import { isMissingSchemaObject } from '../core/utils.ts';import type { PageType } from '../core/types.ts';import { parseMarkdown } from '../core/markdown.ts';import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, replacePageFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';-import { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';+import { collectWantedLinks, isWantedPagesEnabled, wantedReadAt } from '../core/wanted-links.ts';import { readLineGrammarSettings, statedRelationTypes } from '../core/line-grammar.ts';import { effectiveLinkExtractorWatermark, linkExtractorWatermarkFor } from '../core/link-extraction-watermark.ts';import { concurrentWriteSkipLine, replaceDerivedLinksBatchOrReplay, replaceDerivedLinksDeferringConflicts, settingsChangedSkipLine, unknownSourceSkipLine, type DerivedLinkBatchItem, type UnknownSourceSkip } from '../core/derived-links.ts';@@ -1896,6 +1896,7 @@ async function extractLinksFromDB(// cross-source wikilinks (qualified like `[[other-src:slug]]`) can// resolve — the filter is on WHICH pages we extract FROM, not what// we can resolve TO.+ const readAt = await wantedReadAt(engine);const allRefs = sourceIdFilter? (await engine.listAllPageRefs()).filter(r => r.source_id === sourceIdFilter): await engine.listAllPageRefs();@@ -2058,7 +2059,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,...(extracted.temporalBody ? { temporalBody: extracted.temporalBody } : {}),- wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },+ wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted, readAt },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');@@ -2197,7 +2198,7 @@ export async function extractStaleFromDB(// #4611: mirrors extractLinksFromDB — configured default, resolved once.const linkDefaultSourceId = await resolveLinkFallbackDefault(engine);// Nothing link-stale: skip the whole-brain resolver reads; the mention pass still runs.- const allRefs = totalStale ? await engine.listAllPageRefs() : [];+ const [readAt, allRefs] = totalStale ? [await wantedReadAt(engine), await engine.listAllPageRefs()] : [undefined, []];const allSlugs = new Set<string>();const slugToSources = new Map<string, string[]>();for (const ref of allRefs) {@@ -2312,7 +2313,7 @@ export async function extractStaleFromDB(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, origin),- wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted },+ wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted, readAt },...(extracted.temporalBody ? { temporalBody: extracted.temporalBody } : {}) };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.tsindex 968ad105f5..b11315319a 100644--- a/src/core/link-reconciliation.ts+++ b/src/core/link-reconciliation.ts@@ -5,7 +5,7 @@ import { fetchSource, isSourceFederated } from './sources-load.ts';import { parseMarkdown } from './markdown.ts';import { isValidSourceId } from './source-id.ts';import { buildSourceLocalReferenceIndex } from './source-local-reference-index.ts';-import { collectWantedLinks, isWantedPagesEnabled } from './wanted-links.ts';+import { collectWantedLinks, isWantedPagesEnabled, wantedReadAt } from './wanted-links.ts';import { readLineGrammarSettings } from './line-grammar.ts';import { DerivedLinkSettingsChangedError } from './derived-links.ts';import { isSegmentedPage } from './page-body/page-shape.ts';@@ -77,6 +77,7 @@ export async function reconcileSourceLinks(const sourceIncarnation = sources[0].incarnation;// #4680: every source's live pages, so the source policy can resolve a target into another// source (names still resolve within the origin's source: makeIndexedLinkResolver filters).+ const readAt = await wantedReadAt(engine);const pages = await loadLinkPageMetadata(engine);const metadata = new Map(pages.map(page => [`${page.source_id}\0${page.slug}`, page]));const endpoints = indexLinkSources(pages);@@ -131,7 +132,7 @@ export async function reconcileSourceLinks(try {written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,expectedRevision: snapshot.revision, sourceIncarnation }, rows, { lineGrammar: grammar,- wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints: capturedLinkEndpoints(rows, metadata),+ wanted: { producers: ['body', 'frontmatter'], rows: wanted, readAt }, expectedEndpoints: capturedLinkEndpoints(rows, metadata),...(extracted.temporalBody ? { temporalBody: extracted.temporalBody } : {}) });} catch (error) {if (!(error instanceof DerivedLinkSettingsChangedError)) throw error;diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex 48a393919d..bf3006b962 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -6,7 +6,7 @@ import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResoimport { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';import { DerivedLinkEndpointChangedError } from '../derived-links.ts';import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, makeLinkSourceResolver } from '../link-reconciliation.ts';-import { collectWantedLinks, isWantedPagesEnabled, possibleWantedRows } from '../wanted-links.ts';+import { collectWantedLinks, isWantedPagesEnabled, possibleWantedRows, wantedReadAt } from '../wanted-links.ts';import { readFix } from '../ops/op-fix.ts';import { readLineGrammarSettings, type LineGrammarSettings } from '../line-grammar.ts';import { primeRelationSemantics } from '../link-semantics-pack.ts';@@ -119,6 +119,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,roleText ??= await segmentedRoleText(engine, segmented);return extractSegmentedPageLinks(engine, segmented, resolver, { ...o, roleText });};+ const readAt = await wantedReadAt(engine);const referenced = new Set([slug]);const initial = await extract({ ...opts, onResolvedFrontmatterTarget: target => referenced.add(target) });// A link written against a renamed page's old slug follows its slug alias, like get_page does.@@ -143,7 +144,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,: 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)+ const wanted = { producers: ['body', 'frontmatter'] as const, readAt, rows: await isWantedPagesEnabled(engine)? await possibleWantedRows(engine, sourceId, collectWantedLinks({ candidates: candidates.map(retarget), frontmatterUnresolved: unresolved,originSourceId: sourceId, crossSourceAllowed: sources.crossSourceAllowed, resolve: sources.resolve })): [] };diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 09d2cb629a..ae6df2e246 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -378,8 +378,8 @@ async function runLinksTimelinePass(// edit between SELECT and stamp stays stale and re-sweeps. Deferred pages are left out in SQL, before the LIMIT.const deferred = await liveDeferredPages(engine, sourceId, cutoffIso);skip('segmented_page_deferred', deferred.length);- const recent = await engine.executeRaw<{ slug: string; updated_at_iso: string; body_storage: string | null; body_bytes: number | null }>(- `SELECT slug,+ const recent = await engine.executeRaw<{ slug: string; updated_at_iso: string; body_storage: string | null; body_bytes: number | null; read_at: string }>(+ `SELECT slug, to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS read_at,to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso,body_storage, body_bytesFROM pages@@ -392,7 +392,7 @@ async function runLinksTimelinePass(LIMIT $3`,[sourceId, cutoffIso, batchLimit, deferred],);- if (recent.length === 0) return;+ const readAt = recent[0]?.read_at; if (!readAt) return;// resolveCandidateSources + stampExtracted are the shared helpers the// extract command exports precisely so sibling walkers can't drift from@@ -617,7 +617,7 @@ async function runLinksTimelinePass(const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,{ includeFrontmatter: false, preserveExisting: true, lineGrammar: grammar,- wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, temporalBody: temporalBodies.get(ref.slug), expectedEndpoints: [...new Set(desired.flatMap(row =>+ wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [], readAt }, temporalBody: temporalBodies.get(ref.slug), expectedEndpoints: [...new Set(desired.flatMap(row =>[`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {const endpoint = endpointMetadata.get(key)!;return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };diff --git a/src/core/wanted-links-store.ts b/src/core/wanted-links-store.tsindex cb95e14660..8e631e393d 100644--- a/src/core/wanted-links-store.ts+++ b/src/core/wanted-links-store.ts@@ -23,6 +23,19 @@ export interface WantedLinksReplacement {rows: WantedLinkInput[];/** Producers whose rows this replacement owns; others stay untouched. */producers: readonly WantedProducer[];+ /**+ * wantedReadAt() taken before the extraction's first resolution read. Every+ * `name` row is stamped with it, so a page written after that read wakes the+ * origin and one the read already saw does not. Required when rows has a name.+ */+ readAt?: string;+}++/** The database clock as a UTC ISO string with microseconds, independent of the session's DateStyle. */+export async function wantedReadAt(engine: Pick<BrainEngine, 'executeRaw'>): Promise<string> {+ const [row] = await engine.executeRaw<{ at: string }>(+ `SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at`);+ return row!.at;}/**@@ -54,11 +67,11 @@ function pageSlugShaped(target: string): boolean {* 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 a slug reference to an- * exact page counts here: a bare-name reference matching some page's slug or- * basename may legitimately stay unresolved (basename resolution is opt-in,- * and a directory hint can skip a top-level slug), and stamping it- * `-infinity` would re-list its origin forever.+ * after it with an `updated_at` past `checked_at`. A bare-name reference may+ * legitimately stay unresolved while a page has its exact slug or basename+ * (basename resolution is opt-in, and a directory hint can skip a top-level+ * slug), so it is stamped with the caller's read time instead: a page written+ * after that read wakes the origin once, and the next extraction settles it.*/export async function replaceWantedLinks(tx: Pick<BrainEngine, 'executeRaw' | 'lockPageKeys'>,@@ -66,6 +79,9 @@ export async function replaceWantedLinks(replacement: WantedLinksReplacement,): Promise<number> {if (!replacement.producers.length) return 0;+ if (!replacement.readAt && replacement.rows.some(row => row.ref_kind === 'name')) {+ throw new Error('replaceWantedLinks: name rows need the readAt taken before the extraction read');+ }const rows = (await possibleWantedRows(tx, origin.sourceId,replacement.rows.filter(row => replacement.producers.includes(row.producer)))).map(row => ({ ...row, context: sanitizeForJsonb(row.context) }));@@ -86,12 +102,12 @@ export async function replaceWantedLinks(SELECT $1, $2, v.producer, v.ref_kind, v.target_source_id, v.target_ref, v.link_type, v.context,CASE WHEN v.ref_kind = 'slug' AND EXISTS (SELECT 1 FROM pages t WHERE t.source_id = v.target_source_idAND t.deleted_at IS NULL AND t.slug = v.target_ref)- THEN '-infinity'::timestamptz ELSE now() END- FROM jsonb_to_recordset(($3::jsonb)->'rows')+ THEN '-infinity'::timestamptz WHEN v.ref_kind = 'name' THEN $3::timestamptz ELSE now() END+ FROM jsonb_to_recordset(($4::jsonb)->'rows')AS v(producer text, ref_kind text, target_source_id text, target_ref text, link_type text, context text)ON CONFLICT ON CONSTRAINT wanted_links_reference_unique DO UPDATESET link_type = EXCLUDED.link_type, context = EXCLUDED.context, checked_at = EXCLUDED.checked_at- RETURNING id`, [origin.pageId, origin.sourceId], [{ rows }]);+ RETURNING id`, [origin.pageId, origin.sourceId, replacement.readAt ?? null], [{ rows }]);return written.length;}diff --git a/src/core/wanted-links.ts b/src/core/wanted-links.tsindex 87d77234db..e6e385b4f0 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 { possibleWantedRows, replaceWantedLinks } from './wanted-links-store.ts';+export { possibleWantedRows, replaceWantedLinks, wantedReadAt } 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.tsindex a0c7702f11..d026886c28 100644--- a/test/e2e/wanted-links-postgres.test.ts+++ b/test/e2e/wanted-links-postgres.test.ts@@ -7,7 +7,8 @@ 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, topLevelSlugNamePageEditWakesOnce, topLevelSlugNameReferenceSettles } from '../helpers/wanted-links-scenarios.ts';+ restoredTargetHeals, basenameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin, nameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin,+ topLevelSlugNamePageEditWakesOnce, topLevelSlugNameReferenceSettles } from '../helpers/wanted-links-scenarios.ts';const url = process.env.DATABASE_URL;describe.skipIf(!url)('Postgres wanted pages', () => {@@ -16,6 +17,8 @@ describe.skipIf(!url)('Postgres wanted pages', () => {test('a bare-name reference settles', () => bareNameReferenceSettles(url), 180_000);test('#9140: a bare-name reference equal to a top-level slug settles', () => topLevelSlugNameReferenceSettles(url), 180_000);test('#9140: editing the top-level page wakes that origin once', () => topLevelSlugNamePageEditWakesOnce(url), 180_000);+ test('GST-2460: an exact-slug page first written during an extraction wakes its origin', () => nameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin(url), 180_000);+ test('GST-2460: a basename match first written during an extraction wakes its origin', () => basenameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin(url), 180_000);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);@@ -37,7 +40,8 @@ describe.skipIf(!url)('Postgres wanted pages: source registration race (#6225)',let deleteError = null as { code?: string } | 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: '' }] });+ { producer: 'body', ref_kind: 'name', target_source_id: 'archive', target_ref: 'erin-example', link_type: 'mentions', context: '' }],+ readAt: new Date().toISOString() });try {await other.begin(async sql => {await sql.unsafe("SET LOCAL lock_timeout = '300ms'");diff --git a/test/helpers/wanted-links-scenarios.ts b/test/helpers/wanted-links-scenarios.tsindex b5e4ec2c27..994ec05343 100644--- a/test/helpers/wanted-links-scenarios.ts+++ b/test/helpers/wanted-links-scenarios.ts@@ -11,6 +11,7 @@ import { submitPageMutation } from '../../src/core/persistence/page-mutations.tsimport { extractStaleFromDB } from '../../src/commands/extract.ts';import { LINK_EXTRACTOR_VERSION_TS } from '../../src/core/link-extraction.ts';import { operationsByName } from '../../src/core/operations.ts';+import { replaceWantedLinks, wantedReadAt } from '../../src/core/wanted-links.ts';import { managedBrain } from './managed-brain.ts';const put = (ctx: OperationContext, slug: string, body: string, type = 'note', frontmatter = '', expectedRevision?: string) =>@@ -125,6 +126,50 @@ export async function topLevelSlugNamePageEditWakesOnce(databaseUrl?: string) {}, { databaseUrl });}+/** Publish one bare-name body row for an origin as an extraction that read the brain at readAt would. */+const publishNameRow = async (engine: BrainEngine, originSlug: string, targetRef: string, readAt: string) => {+ const [origin] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [originSlug]);+ await engine.transaction(tx => replaceWantedLinks(tx, { pageId: Number(origin!.id), sourceId: 'default' }, { producers: ['body'], readAt,+ rows: [{ producer: 'body', ref_kind: 'name', target_source_id: 'default', target_ref: targetRef, link_type: 'mentions', context: originSlug }] }));+};++/**+ * GST-2460: extractions that read the brain before a bare name's exact-slug page was first written, and publish+ * their wanted row after that write, leave the origin stale however many overlap; the next sweep links it.+ */+export async function nameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/call', 'Call about [[Acme Toolkit]].');+ await extractStale(engine);+ expect(await wantedRows(engine)).toEqual([{ target_ref: 'acme-toolkit', ref_kind: 'name', producer: 'body' }]);+ const first = await wantedReadAt(engine);+ const second = await wantedReadAt(engine);+ await put(ctx, 'acme-toolkit', 'Acme toolkit.');+ await publishNameRow(engine, 'notes/call', 'acme-toolkit', second);+ await publishNameRow(engine, 'notes/call', 'acme-toolkit', first);+ expect(await staleSlugs(engine)).toContain('notes/call');+ await extractStale(engine);+ expect(await backlinks(engine, 'acme-toolkit')).toEqual([{ slug: 'notes/call' }]);+ expect(await stale(engine)).toBe(0);+ }, { databaseUrl });+}++/** GST-2460: the same race for a bare name matched only by a page's basename wakes the origin too. */+export async function basenameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/call', 'Call with [[Dave Example]].');+ await extractStale(engine);+ const readAt = await wantedReadAt(engine);+ await put(ctx, 'people/dave-example', 'Dave.', 'person');+ await publishNameRow(engine, 'notes/call', 'dave-example', readAt);+ expect(await staleSlugs(engine)).toContain('notes/call');+ await extractStale(engine);+ expect(await stale(engine)).toBe(0);+ await extractStale(engine);+ expect(await stale(engine)).toBe(0);+ }, { databaseUrl });+}+/** A remote caller never sees targets referenced only from private pages, nor counts that include them. */export async function privateOriginsStayPrivate(databaseUrl?: string) {await managedBrain(async ({ engine, ctx }) => {diff --git a/test/wanted-links.test.ts b/test/wanted-links.test.tsindex 72f319352a..030e6e4665 100644--- a/test/wanted-links.test.ts+++ b/test/wanted-links.test.ts@@ -10,13 +10,16 @@ import { collectWantedLinks, possibleWantedRows } from '../src/core/wanted-linksimport { 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, topLevelSlugNamePageEditWakesOnce, topLevelSlugNameReferenceSettles, wantedKeys } from './helpers/wanted-links-scenarios.ts';+ privateOriginsStayPrivate, restoredTargetHeals, basenameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin, nameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin,+ topLevelSlugNamePageEditWakesOnce, topLevelSlugNameReferenceSettles, 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);test('a bare-name reference matched only by basename settles after one re-extraction', () => bareNameReferenceSettles(), 120_000);test('#9140: a bare-name reference equal to a top-level slug settles after one re-extraction', () => topLevelSlugNameReferenceSettles(), 120_000);test('#9140: editing the top-level page wakes that origin once, and one extraction settles it again', () => topLevelSlugNamePageEditWakesOnce(), 120_000);+test('GST-2460: a bare name\'s exact-slug page first written during an extraction wakes its origin', () => nameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin(), 120_000);+test('GST-2460: a basename match first written during an extraction wakes its origin', () => basenameRowPublishedAfterItsTargetWasWrittenWakesItsOrigin(), 120_000);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);