Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): defer and name pages whose source has no sources row in DB link drains (#6808)
time-attackea782e21b9ed
diff --git a/docs/architecture/key-files/company-brain.md b/docs/architecture/key-files/company-brain.mdindex ec22ab2fce..a04c9a4524 100644--- a/docs/architecture/key-files/company-brain.md+++ b/docs/architecture/key-files/company-brain.md@@ -9,7 +9,7 @@ For the operator workflow, see the [company-brain ingestion guide](../../guides/- `src/commands/company-brain-{inspect,connect,demo}.ts` — dedicated source subcommand parsing and versioned JSON/error output. Inspection is engine-free; connect requires explicit brain/source selection and previews through the existing resident-owner route before a probe-only local connection. Human progress is stderr-scoped for JSON output. `core/company-brain/{demo,sample,evidence,status}.ts` supplies the real-pipeline offline sample, actual source-scoped evidence, and private receipt status without fabricated answers or host-path fields.-- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints (foreign ones included) and resolves a target into another source only under the source policy it shares with `put_page`'s link preparation (`makeLinkSourceResolver`: `link_resolution.cross_source`, or a `[[source:slug]]` reference from a federated origin; #4680). Standard DB extraction passes the same captured endpoint revision fences. `capturedLinkEndpoints(links, metadata, origin?)` is the one place those fences are built: every endpoint at the resolver census's revision except the source-qualified origin, which `expectedRevision` already fences at the snapshot that supplied its body and type (#6474: fencing it again at the older census revision deferred a page rewritten between the census and its own read); the managed `links-preparation.ts` and both DB walks (`extract links|all`, `extract --stale`) pass the origin, and a self-reference's target type comes from the live snapshot rather than the census. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`engine.readPageSnapshotsBatch`, built on `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, page-subject purges and the '*' purge marker included, line fingerprints only for pages with withdrawals, purges or a '*' marker, a body-byte budget per call; Postgres binds the refs' sources for RLS; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.+- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints (foreign ones included) and resolves a target into another source only under the source policy it shares with `put_page`'s link preparation (`makeLinkSourceResolver`: `link_resolution.cross_source`, or a `[[source:slug]]` reference from a federated origin; #4680). Standard DB extraction passes the same captured endpoint revision fences. #6808: `replaceDerivedLinksDeferringConflicts` (and the batch replay) turns the guard's `PageSourceMissingError` for the origin's or an endpoint's source into `{ unknownSource }`; both DB link drains (`extract links|all --source db`, `extract --stale`) keep that page's links and watermark, count it as `skipped_unknown_source`, name the first 20 in `unknown_source_pages` and print `unknownSourceSkipLine`, which, unlike the settings-changed and concurrent-write lines, does not suggest a re-run (`test/extract-missing-source-6808.test.ts` + Postgres twin). `capturedLinkEndpoints(links, metadata, origin?)` is the one place those fences are built: every endpoint at the resolver census's revision except the source-qualified origin, which `expectedRevision` already fences at the snapshot that supplied its body and type (#6474: fencing it again at the older census revision deferred a page rewritten between the census and its own read); the managed `links-preparation.ts` and both DB walks (`extract links|all`, `extract --stale`) pass the origin, and a self-reference's target type comes from the live snapshot rather than the census. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`engine.readPageSnapshotsBatch`, built on `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, page-subject purges and the '*' purge marker included, line fingerprints only for pages with withdrawals, purges or a '*' marker, a body-byte budget per call; Postgres binds the refs' sources for RLS; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.- `src/core/attendance-repair.ts` and `src/commands/extract-attendance-repair.ts` — trusted-local historical attendance preview and exact-receipt apply. Indexed source-page slug windows precede eligibility filtering; explicit Markdown evidence uses capped endpoint and adjacency lookups, while all frontmatter remains report-only and unmaterialized. A narrow `derived-links.ts` delta preserves unrelated row IDs and evidence; brain/source incarnation, page revisions, ontology/parser and affected-edge hashes fence each origin transaction. Existing `op_checkpoints` banks commit proof before the private cursor advances across committed origins and revalidated skipped pages, making interruption replay idempotent. No broad derived replacement, normal-extraction watermark updates, MCP administration or provider calls. Covered by the dual-engine `test/attendance-repair.test.ts` and real CLI `test/attendance-repair-cli.serial.test.ts`; operator contract and limits are in `docs/guides/attendance-evidence.md`.- `src/core/schema-pack/base/company-brain.yaml` — optional company vocabulary extending `gbrain-base-v2` without normalization rules or maintenance phases. Overrides company aliases and prefixes so product stays a distinct query and path type. Bundled through `schema-pack/bundled.ts` and `bundled-assets.ts`; attribution is in `third-party/company-brain/`. The generic fictional sample in `src/core/company-brain/sample/` preserves the upstream layout and relationship metadata. `test/company-brain-schema.test.ts` pins inherited lint, type closure, folder inference, read-only bundling, and sample references.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e5f2d8c2bf..06353e0994 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1650 ratchet refactor wave 1 split target (W4 autopilosrc/commands/doctor.ts 688 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.tssrc/commands/embed.ts 2304 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)src/commands/extract-conversation-facts.ts 2044 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-src/commands/extract.ts 2643 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+src/commands/extract.ts 2654 ratchet +11 #6808: both DB link drains defer and name pages whose source (or a link target source) has no sources row instead of aborting (outcome and skip line in core/derived-links.ts); +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 measuredsrc/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 codessrc/commands/serve-http.ts 937 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)src/core/ai/gateway.ts 4525 ratchet +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 textdiff --git a/src/commands/extract.ts b/src/commands/extract.tsindex bac8268f44..22b6ba5e1e 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -50,7 +50,7 @@ import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadaimport { collectWantedLinks, isWantedPagesEnabled } 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, type DerivedLinkBatchItem } from '../core/derived-links.ts';+import { concurrentWriteSkipLine, replaceDerivedLinksBatchOrReplay, replaceDerivedLinksDeferringConflicts, settingsChangedSkipLine, unknownSourceSkipLine, type DerivedLinkBatchItem, type UnknownSourceSkip } from '../core/derived-links.ts';import { pageSnapshotKey } from '../core/page-snapshot-batch.ts';import type { PageSnapshot } from '../core/page-state/types.ts';export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';@@ -277,6 +277,9 @@ interface ExtractResult {skipped_cross_source?: number;/** #6272: pages a concurrent writer changed mid-run, left unstamped (DB links path, present when non-zero). */skipped_concurrent_write?: number;+ /** #6808: pages whose source (or a link target's) has no sources row, left unstamped; the first 20 named (DB paths, present when non-zero). */+ skipped_unknown_source?: number;+ unknown_source_pages?: UnknownSourceSkip[];/** #5904: timeline writes the writer refused or left pending (DB path); the command exits non-zero. */timeline_refused?: number;}@@ -918,6 +921,7 @@ async function extractFromDB(engine: BrainEngine, result: ExtractResult, subcommresult.skipped_cross_source = r.skippedCrossSource;if (r.skippedAttendanceIncomplete) result.skipped_attendance_incomplete = r.skippedAttendanceIncomplete;if (r.skippedConcurrentWrite) result.skipped_concurrent_write = r.skippedConcurrentWrite;+ if (r.unknownSource.length) { result.skipped_unknown_source = r.unknownSource.length; result.unknown_source_pages = r.unknownSource.slice(0, 20); }}if (subcommand === 'timeline' || subcommand === 'all') {const r = await (await import('./extract-timeline-db.ts')).extractTimelineFromDB(engine, { ...o, completed: completed?.timeline });@@ -1834,7 +1838,7 @@ async function extractLinksFromDB(typeFilter: PageType | undefined,since: string | undefined,opts?: { includeFrontmatter?: boolean; sourceIdFilter?: string; completed?: Set<string> },-): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number; skippedAttendanceIncomplete: number; skippedConcurrentWrite?: number }> {+): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number; skippedAttendanceIncomplete: number; skippedConcurrentWrite?: number; unknownSource: UnknownSourceSkip[] }> {const includeFrontmatter = opts?.includeFrontmatter ?? false;const sourceIdFilter = opts?.sourceIdFilter;// C3 (D6) + S4 (P2.18): the links_extracted_at watermark covers links AND timeline, so this phase never stamps it;@@ -1912,6 +1916,7 @@ async function extractLinksFromDB(const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));const grammar = await readLineGrammarSettings(engine), lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };let skippedSettingsChanged = 0, skippedConcurrentWrite = 0;+ const unknownSource: UnknownSourceSkip[] = [];progress.start('extract.links_db', walkRefs.length);const plannerTick = dryRun ? async () => {} : await plannerStatsForLinkDrain(engine, async () => walkRefs.length);@@ -1931,6 +1936,7 @@ async function extractLinksFromDB(const written = results[i];if (written === 'settings_changed') skippedSettingsChanged++;else if (written === 'concurrent_write') skippedConcurrentWrite++;+ else if ('unknownSource' in written) unknownSource.push({ slug, source_id, missing_source: written.unknownSource });else { created += written.created; processed++; if (!dryRun) opts?.completed?.add(extractCompletionKey(source_id, slug, item.origin.expectedRevision)); }progress.tick(1);});@@ -2041,6 +2047,7 @@ async function extractLinksFromDB(if (skippedAttendanceIncomplete) console.log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);if (skippedSettingsChanged) console.log(settingsChangedSkipLine(skippedSettingsChanged));if (skippedConcurrentWrite) console.log(concurrentWriteSkipLine(skippedConcurrentWrite));+ if (unknownSource.length) console.log(unknownSourceSkipLine(unknownSource));if (skippedMissingTarget > 0) {console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);}@@ -2065,7 +2072,7 @@ async function extractLinksFromDB(// #2589: the counters ride the return value so machine consumers (and the// --json path, which has no summary event on this path) can see the drops —// "counted, never silent" must hold beyond human-mode console lines.- return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete, ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}) };+ return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete, ...(skippedSettingsChanged ? { skippedSettingsChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}), unknownSource };}/**@@ -2104,7 +2111,7 @@ export async function extractStaleFromDB(timeBudgetMs?: number;/** GBRA-130 A-1 (managed brains): clear held link-extraction failures first. */ retryHeld?: boolean;},-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; mentions?: MentionPassResult;+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; skippedUnknownSource?: number; mentions?: MentionPassResult;linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[] }> {const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);@@ -2194,6 +2201,7 @@ export async function extractStaleFromDB(// design (source isolation) unless the #3908 flag is on, but distinct// from a genuinely missing target.let skippedCrossSource = 0, skippedChanged = 0, skippedConcurrentWrite = 0;+ const unknownSource: UnknownSourceSkip[] = [];const wantedEnabled = await isWantedPagesEnabled(engine);const plannerTick = await plannerStatsForLinkDrain(engine, async () => totalStale);@@ -2272,6 +2280,7 @@ export async function extractStaleFromDB(// Settings moved, or a concurrent writer moved the page or an endpoint (#6272): not stamped, re-extracts next run.if (written === 'settings_changed') { skippedChanged++; continue; }if (written === 'concurrent_write') { skippedConcurrentWrite++; continue; }+ if ('unknownSource' in written) { unknownSource.push({ slug: page.slug, source_id: page.source_id, missing_source: written.unknownSource }); continue; }linksCreated += written.created;const timelineText = fullContent ?? await segmentedTimelineText(engine, snapshot.page);await retractRemovedTimelineEntries(engine, page.slug, page.source_id, timelineText);@@ -2332,6 +2341,7 @@ export async function extractStaleFromDB(if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);if (skippedChanged) log(settingsChangedSkipLine(skippedChanged));if (skippedConcurrentWrite) log(concurrentWriteSkipLine(skippedConcurrentWrite));+ if (unknownSource.length) log(unknownSourceSkipLine(unknownSource));if (skippedMissingTarget > 0) {log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);}@@ -2348,11 +2358,12 @@ export async function extractStaleFromDB(pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skipped_changed: skippedChanged } : {}),- ...(skippedConcurrentWrite ? { skipped_concurrent_write: skippedConcurrentWrite } : {}), ...mentionJsonFields(mentions), ...counts,+ ...(skippedConcurrentWrite ? { skipped_concurrent_write: skippedConcurrentWrite } : {}),+ ...(unknownSource.length ? { skipped_unknown_source: unknownSource.length, unknown_source_pages: unknownSource.slice(0, 20) } : {}), ...mentionJsonFields(mentions), ...counts,}) + '\n');}return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}), mentions };+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}), ...(skippedConcurrentWrite ? { skippedConcurrentWrite } : {}), ...(unknownSource.length ? { skippedUnknownSource: unknownSource.length } : {}), mentions };}/**diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 386af037c4..b2447b2c08 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -904,13 +904,14 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },- // Wave 20 lane 1 (#6944 #6945 #6940 #6953 #6958 #6997).+ // Wave 20 lane 1 (#6944 #6945 #6940 #6953 #6958 #6997 #6808).{ since: '0.60.307.0', text: '`gbrain recall --since <value>` now refuses a value it cannot read (and a `--since` with no value) with `invalid_params` (exit 2), echoing the value and listing the accepted forms, instead of silently recalling every time window. `--session` / `--session-id` with no ID refuses the same way instead of recalling every session. The CLI and the recall operation now share one `--since` parser.' },{ since: '0.60.307.0', text: '`gbrain recall --since-last-run` (and `--watch`) on a local brain no longer skips facts when more than `--limit` of them arrived since the last run. A run that fills the window now shows the OLDEST `--limit` new facts (newest first within the page) and the next run continues right after the last one shown, until it catches up; before, it showed the newest `--limit` and the rest were never shown. The cursor file keeps `schema_version: 1` and gains two optional fields, so cursor files from earlier versions keep working. A thin client cannot page yet: when its window is full it prints a warning to raise `--limit`.' },{ since: '0.60.307.0', text: '`get_health` / `gbrain health` `most_connected` no longer counts links to or from soft-deleted pages, so a hub whose neighbours were deleted drops in the ranking instead of keeping their edges (#6940). The islanded scan already applied this liveness rule.' },{ since: '0.60.307.0', text: 'The dream cycle\'s `edge_contradictions` phase now judges a `works_at` group only when its subject is a person (the pack\'s `person` type or a type that declares `aliases: [person]`) and its targets can employ someone: links from companies, and links to people, meetings, conversations, emails, sources, notes or inbox pages, no longer become "Ended works_at" proposals, and such malformed groups no longer use up the phase\'s subject limit (#6953). Link extraction no longer types a link to a conversation, email, source, note or inbox page as `works_at` (it stays `mentions`). Open proposals made earlier are not re-checked: reject unwanted ones with `gbrain edge-proposals reject <id>`. The judge prompt is unchanged.' },{ since: '0.60.307.0', text: 'Automatic mention linking now skips a page of any type whose whole title is one generic word (such as "Info", "Team" or "Update"); before, only person pages were skipped, so a company or concept page with such a title collected a mention link from every page that used the word (#6958). The page itself is unchanged, multi-word titles still link, and `gbrain extract mentions --explain <slug>` reports the reason as `generic_token`.' },{ since: '0.60.307.0', text: 'When `chat_fallback_chain` answers a `gbrain think` (or `think` tool) call, the result now names the model that answered instead of the configured one that failed: `modelUsed`, `cost_usd`, the synthesize verb\'s `cost.model` and a `--save` page\'s `model:` frontmatter use it. New fields `requested_model` (the configured model) and `fallback_reason` (why it did not answer; omitted for HTTP MCP callers) appear only after a fallback, and the human output says `(fallback from ...)`. Calls the first model answers are unchanged.' },+ { since: '0.60.307.0', text: '`gbrain extract links --source db` (and `extract all --source db`, `extract --stale`) no longer aborts the whole run at the first page whose source, or whose link target\'s source, has no sources row. That page keeps its links and watermark and the run continues; the summary counts it as `skipped_unknown_source`, names the first 20 in `unknown_source_pages` (JSON) and names the missing sources. Re-running extract does not clear these pages: re-register the source or remove its pages (#6808).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/derived-links.ts b/src/core/derived-links.tsindex ec6bb8b849..9c9a0f3712 100644--- a/src/core/derived-links.ts+++ b/src/core/derived-links.ts@@ -1,6 +1,7 @@import type { BrainEngine, LinkBatchInput } from './engine.ts';import { assertPageRevision, PageRevisionConflictError, RevisionBackfillPendingError, type PageSnapshot } from './page-state/types.ts';import { pipelined } from './page-state/transactions.ts';+import { PageSourceMissingError } from './page-state/guards.ts';import { beliefCoveredSources, unmanagedBeliefPoint } from './belief/projection-point.ts';import { executeRawJsonb } from './sql-query.ts';import { pageSnapshotKey } from './page-snapshot-batch.ts';@@ -76,14 +77,33 @@ export function isConcurrentLinkWriteConflict(error: unknown): boolean {|| (error instanceof PageRevisionConflictError && !(error instanceof RevisionBackfillPendingError));}-/** A deferring caller's outcome for one origin: written, left stale by a settings change, or by a concurrent write. */-export type DeferredDerivedLinkOutcome = { created: number; removed: number } | 'settings_changed' | 'concurrent_write';+/**+ * A deferring caller's outcome for one origin: written, left stale by a settings change or a concurrent write, or+ * (#6808) refused because the origin's source or a link target's source has no sources row (the missing source id).+ */+export type DeferredDerivedLinkOutcome = { created: number; removed: number } | 'settings_changed' | 'concurrent_write' | { unknownSource: string };-/** replaceDerivedLinksUnlessSettingsChanged for a run that defers (and counts) pages a concurrent writer moved. */+/** replaceDerivedLinksUnlessSettingsChanged for a run that defers (and counts) pages a concurrent writer moved or whose source is gone. */export async function replaceDerivedLinksDeferringConflicts(engine: Pick<BrainEngine, 'replaceDerivedLinks'>,...args: Parameters<BrainEngine['replaceDerivedLinks']>): Promise<DeferredDerivedLinkOutcome> {try { return await replaceDerivedLinksUnlessSettingsChanged(engine, ...args) ?? 'settings_changed'; }- catch (error) { if (isConcurrentLinkWriteConflict(error)) return 'concurrent_write'; throw error; }+ catch (error) {+ if (error instanceof PageSourceMissingError) return { unknownSource: error.sourceId };+ if (isConcurrentLinkWriteConflict(error)) return 'concurrent_write';+ throw error;+ }+}++/** #6808: a page a DB link drain deferred because a source it writes through has no sources row. */+export interface UnknownSourceSkip { slug: string; source_id: string; missing_source: string }++/** The operator line for unknown-source deferrals: unlike the lines above, re-running extraction does not clear them. */+export function unknownSourceSkipLine(skips: readonly UnknownSourceSkip[]): string {+ const missing = [...new Set(skips.map(s => s.missing_source))].sort();+ const sample = skips.slice(0, 5).map(s => `${s.source_id}:${s.slug}`).join(', ');+ return `Skipped ${skips.length} page(s) because source(s) ${missing.join(', ')} have no sources row (unknown_source; e.g. ${sample}); ` ++ 'their links and watermark were kept and the run is incomplete for them. Re-running extract does not fix this: re-register the source ' ++ '(`gbrain sources list` shows the registered ones) or remove its pages.';}/** The operator line for pages a settings change left stale mid-run. */@@ -214,7 +234,7 @@ export async function replaceDerivedLinksBatch(* Publish through replaceDerivedLinksBatch; when that transaction fails,* replay the origins one by one so every outcome is the unbatched one:* `settings_changed` for a settings-changed skip, `concurrent_write` for an- * origin a concurrent writer moved (#6272), and any other failing origin's+ * origin a concurrent writer moved (#6272), `{ unknownSource }` for a missing source (#6808), and any other failing origin's* error thrown (after `onError`) with the origins before it committed.*/export async function replaceDerivedLinksBatchOrReplay(engine: Pick<BrainEngine, 'replaceDerivedLinks' | 'replaceDerivedLinksBatch'>,diff --git a/test/e2e/extract-missing-source-6808.test.ts b/test/e2e/extract-missing-source-6808.test.tsnew file mode 100644index 0000000000..afa9ede024--- /dev/null+++ b/test/e2e/extract-missing-source-6808.test.ts@@ -0,0 +1,3 @@+/** Real PostgreSQL execution of the shared missing-source drain contracts. */+import { registerPostgresTests } from '../helpers/test-backends.ts';+await registerPostgresTests(() => import('../extract-missing-source-6808.test.ts'));diff --git a/test/extract-missing-source-6808.test.ts b/test/extract-missing-source-6808.test.tsnew file mode 100644index 0000000000..5ebbd3bee0--- /dev/null+++ b/test/extract-missing-source-6808.test.ts@@ -0,0 +1,102 @@+/** Legacy orphan pages must not poison a brain-wide link drain (#6808).+ * The FK is removed only in this isolated fixture to model the reported legacy state.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { extractStaleFromDB, runExtract } from '../src/commands/extract.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++for (const backend of testBackends()) {+ describe(`missing source link extraction (${backend})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (backend === 'postgres') {+ const fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = fixture.engine;+ close = fixture.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.executeRaw('ALTER TABLE pages DROP CONSTRAINT pages_source_id_fkey');+ await engine.setConfig('mentions.auto_link', 'false');+ }, 120_000);+ afterAll(async () => { await close?.(); });+ beforeEach(async () => {+ await engine.setConfig('link_resolution.cross_source', 'false');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('missing','Missing'),('healthy','Healthy')");+ for (const sourceId of ['missing', 'healthy']) {+ for (const [slug, body] of [['notes/a', 'See [[notes/b]].'], ['notes/b', 'Target.']]) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body }, { sourceId });+ }+ }+ await engine.executeRaw("DELETE FROM sources WHERE id='missing'");+ });++ async function edges() {+ return engine.executeRaw<{ source_id: string; from_slug: string; to_slug: string }>(`SELECT f.source_id,f.slug from_slug,t.slug to_slug+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id ORDER BY f.source_id,f.slug,t.slug`);+ }++ test('brain-wide DB links replays a failed batch and counts orphan pages while healthy pages publish', async () => {+ // Cross the 100-page publication boundary: later batches must run too.+ for (let i = 0; i < 105; i++) await engine.putPage(`notes/tail-${i}`, { type: 'note', title: 'Tail', compiled_truth: 'No links.' }, { sourceId: 'healthy' });+ const log = spyOn(console, 'log').mockImplementation(() => {});+ const exit = spyOn(process, 'exit').mockImplementation(() => { throw new Error('Unexpected CLI exit'); });+ try {+ await runExtract(engine, ['links', '--source', 'db', '--json']);+ const summary = JSON.parse(String(log.mock.calls.at(-1)![0]));+ expect(summary.skipped_unknown_source).toBe(2);+ expect(summary.unknown_source_pages).toEqual([+ { slug: 'notes/a', source_id: 'missing', missing_source: 'missing' },+ { slug: 'notes/b', source_id: 'missing', missing_source: 'missing' },+ ]);+ expect(summary.pages_processed).toBe(107);+ expect(summary.links_created).toBe(1);+ expect(await edges()).toEqual([{ source_id: 'healthy', from_slug: 'notes/a', to_slug: 'notes/b' }]);+ // Retry does not create duplicates or declare the orphan pages processed.+ await runExtract(engine, ['links', '--source', 'db', '--json']);+ expect(JSON.parse(String(log.mock.calls.at(-1)![0])).skipped_unknown_source).toBe(2);+ expect(await edges()).toHaveLength(1);+ } finally { exit.mockRestore(); log.mockRestore(); }+ });++ test('stale extraction continues without stamping the orphan pages fresh', async () => {+ const result = await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });+ expect(result).toMatchObject({ skippedUnknownSource: 2, pagesProcessed: 2, staleRemaining: 2 });+ expect(await edges()).toEqual([{ source_id: 'healthy', from_slug: 'notes/a', to_slug: 'notes/b' }]);+ const orphan = await engine.executeRaw<{ links_extracted_at: unknown }>("SELECT links_extracted_at FROM pages WHERE source_id='missing'");+ expect(orphan).toHaveLength(2);+ expect(orphan.every(row => row.links_extracted_at === null)).toBe(true);+ });++ test('an unrelated error with similar text is still fatal', async () => {+ const original = engine.replaceDerivedLinks;+ engine.replaceDerivedLinks = async function () { throw new Error('Page source does not exist: injected storage failure'); };+ try {+ await expect(extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true }))+ .rejects.toThrow('injected storage failure');+ } finally { engine.replaceDerivedLinks = original; }+ });++ test('a missing target source preserves the healthy origin\'s prior projection and watermark', async () => {+ await engine.setConfig('link_resolution.cross_source', 'true');+ await engine.putPage('notes/a', { type: 'note', title: 'Origin', compiled_truth: 'See [[missing:notes/b]].' }, { sourceId: 'healthy' });+ await engine.addLinksBatch([{ from_slug: 'notes/a', to_slug: 'notes/b', from_source_id: 'healthy', to_source_id: 'healthy',+ link_type: 'mentions', link_source: 'markdown' }]);+ const before = await engine.executeRaw('SELECT * FROM links ORDER BY id');+ const result = await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });+ expect(result).toMatchObject({ skippedUnknownSource: 3, pagesProcessed: 1, staleRemaining: 3 });+ expect(await engine.executeRaw('SELECT * FROM links ORDER BY id')).toEqual(before);+ const [page] = await engine.executeRaw<{ links_extracted_at: unknown }>("SELECT links_extracted_at FROM pages WHERE source_id='healthy' AND slug='notes/a'");+ expect(page!.links_extracted_at).toBeNull();+ });+ });+}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 73171e78e0..0091650c1c 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4437,7 +4437,7 @@"kind": "function","name": "extractStaleFromDB","signature": [- "(engine: BrainEngine, opts: { dryRun: boolean; jsonMode: boolean; quiet?: boolean; includeFrontmatter?: boolean; sourceIdFilter?: string; catchUp: boolean; timeBudgetMs?: number; retryHeld?: boolean; }) => Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; mentions?: MentionPassResult; linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[]; }>"+ "(engine: BrainEngine, opts: { dryRun: boolean; jsonMode: boolean; quiet?: boolean; includeFrontmatter?: boolean; sourceIdFilter?: string; catchUp: boolean; timeBudgetMs?: number; retryHeld?: boolean; }) => Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; skippedUnknownSource?: number; mentions?: MentionPassResult; linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[]; }>"]},{