Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): fact_bulk_dates doctor check and fact-claim-dates repair (#7247)
garrytan6d601887180c
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex f93699fd3a..cfa61dda99 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -226,6 +226,7 @@ src/core/repair/redacted-facts.ts 1 coordinator `gbrain repair redacted-facts` (src/core/repair/ontology-facts.ts 1 coordinator `gbrain repair ontology-facts` (#6264) gives preview-approved ontology observations their own provenance back, clears their fence row number and expiry. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the ontology_propose path: write authority checked, source incarnation revalidated, entity and page keys locked); an unmanaged brain runs it in one maintenance transaction. It writes database-only ontology rows and never a page or file.src/core/repair/facts-rehome.ts 1 coordinator `gbrain repair facts-rehome` (B-7, #6925) moves preview-approved database-only facts off a page-less entity_slug onto the page the strict resolver reaches. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, both slugs locked); an unmanaged brain runs one maintenance transaction per slug. It rechecks the slug, target and fact ids against the preview and never writes a page or file.src/core/repair/consolidate-ties.ts 1 coordinator `gbrain repair consolidate-ties` (#6023) sets preview-approved typed facts that consolidation closed at their own effective instant back to open validity. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity key locked); an unmanaged brain runs one maintenance transaction per fact. It rechecks the fact, take and instant against the preview and never writes a page or file.+src/core/repair/fact-claim-dates.ts 1 coordinator `gbrain repair fact-claim-dates` (#7247) moves preview-approved facts' valid_from to the date their claim states. Fence rows change only in the page through revision-bound put_page (the coordinator re-projects the facts row from the canonical text); the one direct UPDATE sets valid_from of database-only facts in one maintenanceTransaction on an unmanaged brain, rechecking each row's previewed valid_from, and is never reached on a managed brain.src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversation-labels` expires preview-approved label-misattributed conversation facts, expires the page completion marker and writes the not-extractable outcome, under the page key: one database-only managed_maintenance_conversation_label_retire request per batch of up to 25 pages on a managed brain (the preparer reclassifies each page under its lock), one maintenanceTransaction per batch on an unmanaged brain.src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex c85b5a5c63..7dc62da5c1 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -3,6 +3,7 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-2.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/commands/doctor/checks/fact-bulk-dates.ts` — `fact_bulk_dates` (wave check, #7247): `findBulkFactDays` over the scoped sources (remote callers: their permitted sources); warns per day with fact and entity counts, top source tags and `dated_claims`, says the dates record loading, not occurrence, and names the `gbrain repair fact-claim-dates --source <id>` preview. Read-only.- `src/commands/doctor/checks/integrations-memorable.ts` — `memorable_relay_health` (OPS category), the doctor surface for the optional third-party relay. Engine-free (file-plane reads only), pushed unconditionally so it survives `--fast`/`--scope`. Rung ladder: gate off → quiet ok; enabled WITHOUT the gbrain disclosure stamp → FAIL naming the exact fix (the `memorable enable` out-of-band state); CLI-side consent absent → warn; no runnable binary → FAIL; last relay run failed → warn with the CLAMPED cause (the shared `clampRelayCause`; child text never lands in a doctor message verbatim) — EXCEPT the documented openclaw `no_decisive_steps` rejection, which becomes an ok-with-note (`expected_openclaw_rejection`, name-only capture refused until argument capture lands) held as a DEFERRED note that surfaces only after the codex rung below passes: on a mixed openclaw+codex host the rejection is the persistent last-relay state, and an early return would paint the check green while a trust-stale codex hook sits silently dead; receipts written but the child never reported → warn; codex hooks wired but no codex-harness receipt in the recent receipt window (tail-200 read) → warn (`codex_hooks_never_fired` — codex hooks fail silently on a stale trust entry); healthy → ok with structured details (`out_of_band_settable: true` always rides — the enable flag can be flipped by the external CLI, which is exactly why the gate also demands the stamp). Pinned by `test/doctor-memorable.test.ts`.- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.mdindex 8219065785..048b333f3c 100644--- a/docs/architecture/key-files/core-persistence-facts.md+++ b/docs/architecture/key-files/core-persistence-facts.md@@ -4,6 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.Managed facts extraction: the entity-intent preparer and publisher, conversation facts batches and the unmanaged derived index. The extraction pipeline itself is in [Google and Loops (continued)](google-and-loops-continued.md) (`src/core/facts/backstop.ts`) and [Core Services (2/3)](core-services-2.md) (`src/core/facts/extract.ts`).+- `src/core/facts/bulk-days.ts` — #7247 the one rule doctor `fact_bulk_dates` and `gbrain repair fact-claim-dates` share. `findBulkFactDays` (one read-only aggregate over active facts of active sources, optionally scoped) returns each UTC `valid_from` day holding at least `BULK_DAY_RULE` (200 facts, 25% of the source, 20 entities) with counts, top source tags and `dated_claims`. `claimDate` returns a claim's only `YYYY-MM-DD` token when it is a real date from 1900 to the day before; the aggregate's SQL applies the same token and bounds.- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). GBRA-130 A-36: `collectManagedFacts` awaits every row before it throws. An entity request that ended on a code of its own page (`ENTITY_REFUSAL_CODES`: `revision_conflict`, `invalid_fence`, `page_body_segmented`, …; not a file-check or withdrawal refusal, which the follow-up walks own) is reported as `refused` (slug, code, request id) on `ManagedFactsResult` and the `extract_facts` result when the session sets `reportRefusals` and another entity of the batch committed (the backstop sets it; `managed-fact-write.ts` and `remember` do not and keep the refusal), and the completion receipt refused only as incomplete is not a failure of its own; any other terminal row, then a pending one, then a refusal with nothing committed beside it, throws as its receipt. Test: `test/pathological/a-36-facts-batch-partial-refusal.test.ts` (PGLite and Postgres). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).- `src/core/facts/same-page-shadow.ts` — #6333 the shadow counter both fact writers share. `samePageRewording(engine, sourceId, fact, embedding)` re-reads the entity's nearest live same-visibility candidate (`listSupersessionCandidates`, the pool and filters of `decideSingleFact`'s cosine pass) and answers whether `wouldDedupSamePage` (capture-dedup.ts: same lane, same `source_session`, same visibility, cosine ≥ 0.85, no diverging guard token) would have called the fact a rewording; `warnSamePageShadow` is the one stderr spelling (`[facts-backstop] #6333 shadow: …; both kept`). `facts-prepare.ts` calls it for every candidate `decideSingleFact` did not match and counts `would_dedup_same_page` on the entity outcome, the completion outcome, `ManagedFactsResult` and the `extract_facts` result; the count is frozen in the receipt, so a replay reports it and does not recount. Nothing is dropped; this is the managed mirror of the unmanaged backstop's counter (`backstop.ts`), which never fired on a managed brain. Tests: `test/backstop-same-page-shadow-managed-6333.test.ts` (PGLite and Postgres), `test/backstop-same-page-shadow-6333.test.ts` (unmanaged).- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex ffa83e1144..f68114e0f6 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -10,6 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as `segmented_pages` / `segmented_facts` and named in a warning. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).- `src/core/repair/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`pageTexts`: an inline page's body + timeline, a segmented page's body through `readBodyRange` up to 16 MiB, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. A proved fenced row on a segmented page is `segmented` (`segmented_page`): listed with its restoration, never rewritten (`restoreFencedRows` reads and publishes inline bodies only). The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).+- `src/core/repair/fact-claim-dates.ts` — `gbrain repair fact-claim-dates --source <id> [--day YYYY-MM-DD]` (#7247), explicit-only, preview-bound, destructive (`--yes`). Candidates: active facts on a bulk day (`findBulkFactDays`, or `--day`) whose claim has exactly one earlier ISO date (`claimDate`). A fence row's `valid_from` cell is rewritten in the page's one fence section and published by revision-bound `put_page` (the facts row is re-projected); a database-only fact is updated in one `maintenanceTransaction` on an unmanaged brain and counted `database_only_managed` on a managed one. Pages with an unparsed, split or segmented fence, or a rewrite that does not read back as the planned rows, are listed and kept. The hash binds revisions, row numbers and new dates; a fresh apply recomputes the plan and refuses `preview_changed` on any difference. Test: `test/repair-fact-claim-dates-7247.test.ts`.- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 8f567bdc33..17b5727a2a 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -294,6 +294,7 @@ or a physical projection that leaves attribution untouched):- `src/core/repair/consolidate-ties.ts` (1): `gbrain repair consolidate-ties` reopens facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per fact on unmanaged brains.- `src/core/repair/conversation-labels.ts` (4): a request on managed brains; the unmanaged label retirement runs in `maintenanceTransaction`.- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.+- `src/core/repair/fact-claim-dates.ts` (1): `gbrain repair fact-claim-dates` updates database-only facts' `valid_from` in one `maintenanceTransaction` on unmanaged brains only; fence rows move through revision-bound `put_page`, and a managed brain never takes the direct update.- `src/core/repair/facts-rehome.ts` (1): `gbrain repair facts-rehome` moves facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per slug on unmanaged brains.- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.- `src/core/repair/ghost-pages.ts` (2): `gbrain repair ghost-pages` retirement: a receipted `managed_maintenance_retire_ghost_page` request (a prepared `delete_page` with no file bytes) on managed brains; the unmanaged version and soft delete run in `maintenanceTransaction` after the same recheck.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex e5ce5e24b2..ffea007f4e 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1834,6 +1834,59 @@ take is not changed: if it holds the wrong statement, decide which one iscurrent and `gbrain forget` the other. It writes the database only; no page isrewritten.+<a id="fact-claim-dates"></a>+### Facts dated with the day a bulk load ran++A bulk import that writes the day it ran into every facts-fence row's+`valid_from` cell makes those facts look as if they all happened that day, so+timelines and as-of reads put them on one date. Those dates record when the+facts were loaded, not when they happened (#7247). Doctor `fact_bulk_dates`+warns when one UTC calendar day holds 200 or more of a source's active facts,+at least a quarter of them, across 20 or more entities. It reports each such+day with its fact and entity counts, the most frequent source tags, and how+many of those claims state exactly one earlier ISO date of their own ("Acme+Example closed a seed round on 2025-03-14"). A remote caller sees only its+permitted sources. `gbrain repair fact-claim-dates` moves those facts to the+date their claim states. It is explicit-only, preview-bound and destructive,+and it never runs on upgrade.++**Say to your agent:** *"Preview which bulk-dated facts can take the date their+claim states, then move them after I agree."* The agent runs the preview and,+after you agree, the printed apply command.++```bash+gbrain doctor --only fact_bulk_dates # the loaded days per source+gbrain repair fact-claim-dates --source <id> # preview: one line per page, residual counts+gbrain repair fact-claim-dates --source <id> --day 2026-01-15 # preview a loaded day the rule does not detect+gbrain repair fact-claim-dates --source <id> --apply --expect <hash> --yes+```++A candidate is an active fact whose `valid_from` falls on a loaded day and+whose claim holds exactly one `YYYY-MM-DD` date, a real calendar date from+1900 up to the day before. Facts with no date (`no_date`), several dates+(`several_dates`), or one out of range (`date_not_earlier`) keep the load+day and are counted, and so is a fact whose `valid_until` falls before its+claim's date (`ends_before_claim_date`).++A fact held by a page's facts fence is moved in the page: only that row's+`valid_from` cell changes, and the page is published through a revision-bound+`put_page`, so on a managed brain the canonical file changes and the facts row+is re-projected from it. A page is listed and kept when its fence does not+parse (`unparsed`, preview `gbrain repair fences`), it has a fence on both+sides of the timeline sentinel (`split_fences`, run `gbrain repair+split-facts` first), it is stored in segments (`segmented_page`), or the+rewritten fence would not read back as exactly the planned rows+(`not_conserved`). A row whose cell no longer reads the loaded day is+`fence_mismatch`. A fact with no fence row is updated in place on an unmanaged+brain; on a managed brain it is counted `database_only_managed` and kept.++The hash covers each page's revision, row numbers and new dates. The apply+recomputes the plan first and refuses `preview_changed` when anything moved,+then changes exactly the previewed rows; a page edited during the run reports+`changed_since_preview` and is kept. A second preview lists nothing. On a+managed brain `git revert` of the repair commit undoes it, and page history+keeps the earlier revision.+<a id="failed-writes"></a>### Failed writes@@ -3008,6 +3061,7 @@ walk me through it before changing anything."*| Doctor `google_file_modes` warns, or the upgrade printed `[google] Google source <id> keeps its files in <dir>, outside ~/.gbrain` | `gbrain repair google-file-modes --source <id>` | `gbrain repair google-file-modes --source <id> --apply` | `gbrain doctor --only google_file_modes --json` (`google_file_modes` ok) | brain host, after the user agrees | none || Recall or hot memory returns facts from gbrain's own claude-cli sessions or from pasted text; doctor `captured_facts_active` warns; the upgrade banner prints `captured_facts_active: N (explicit_kind_required; …)` | `gbrain repair captured-facts` (add `--include-ambiguous` to include paste candidates) | `gbrain repair captured-facts --apply --expect <hash>` with the hash that preview printed | `gbrain doctor --only captured_facts_active --json` (`captured_facts_active` ok) | brain host, after the user agrees | `destructive` (quarantines facts) || A stored fact reads `[redacted](…)` where a word such as "System" belongs; doctor `facts_redaction_marker` warns; `trust scan` flags the marker | `gbrain repair redacted-facts` | `gbrain repair redacted-facts --apply --expect <hash>` with the hash that preview printed | `gbrain doctor --only facts_redaction_marker --json` (ok, or only facts the preview listed as `ambiguous` or `unproven`) | brain host, after the user agrees | none |+| Timelines put hundreds of facts on one day; doctor `fact_bulk_dates` warns that a day holds a bulk-loaded share of a source's facts | `gbrain repair fact-claim-dates --source <id>` | `gbrain repair fact-claim-dates --source <id> --apply --expect <hash> --yes` with the hash that preview printed | `gbrain repair fact-claim-dates --source <id>` lists nothing to move (doctor keeps warning while facts without a date in the claim keep the load day) | brain host, after the user agrees | none || A finished promise still shows on entity cards and in recall after its loop was closed; doctor `loop_facts_drift` warns; the upgrade banner prints `loop_facts_drift: N (explicit_kind_required; …)` | `gbrain repair loop-facts` | `gbrain repair loop-facts --apply --expect <hash>` | `gbrain doctor --only loop_facts_drift --json` (`loop_facts_drift` ok) | brain host, after the user agrees | `destructive` (retires facts) || `gbrain upgrade` refuses with `requires Bun >=<floor>` (exit 78), or doctor `self_upgrade_health` says `Auto-upgrade to <target> held` | `bun --version` | `bun upgrade`, then `gbrain upgrade` ([Bun floor](upgrades-auto-update.md#bun-floor)) | `gbrain --version` shows the target; `gbrain doctor --only self_upgrade_health --json` (`self_upgrade_health` ok) | user | `persistent_install` |diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex c315df6c79..cf2b6a43f9 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -472,6 +472,7 @@ src/core/repair/conversation-labels.ts classifyLabelFacts sql STREAMsrc/core/repair/conversation-labels.ts countLabelFacts sql STREAMsrc/core/repair/extractor-facts.ts restorePageFacts field STREAMsrc/core/repair/extractor-facts.ts restorePageFacts sql STREAM+src/core/repair/fact-claim-dates.ts movePage call:serializePageToMarkdown SEGW refuses a segmented page: the plan lists it segmented_page and movePage keeps one as changed_since_previewsrc/core/repair/fences.ts afterBytes field STREAMsrc/core/repair/fences.ts fencesRepair field STREAMsrc/core/repair/frontmatter.ts analyzeFile field LEADdiff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.jsonindex c2b45c4570..3637a8a315 100644--- a/scripts/postgres-arm-weights.json+++ b/scripts/postgres-arm-weights.json@@ -357,6 +357,7 @@"test/remediation-manual-only.test.ts": 14638,"test/repair-apply-pending-6543.test.ts": 51967,"test/repair-embedding-effects.test.ts": 9932,+ "test/repair-fact-claim-dates-7247.test.ts": 9000,"test/repair-failed-writes-conflict-6429.test.ts": 9306,"test/repair-failed-writes-drift-w411.test.ts": 5486,"test/repair-fences.test.ts": 35248,diff --git a/src/commands/doctor/checks/fact-bulk-dates.ts b/src/commands/doctor/checks/fact-bulk-dates.tsnew file mode 100644index 0000000000..008aad6b3e--- /dev/null+++ b/src/commands/doctor/checks/fact-bulk-dates.ts@@ -0,0 +1,36 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { BULK_DAY_RULE, findBulkFactDays } from '../../../core/facts/bulk-days.ts';+import { agentFix, checkError } from '../check-fix.ts';++/**+ * `fact_bulk_dates` (#7247): a calendar day holding a large share of a source's active facts as their valid_from,+ * which a bulk load writes when it stamps the day it ran onto every row. Those dates record when the facts were+ * loaded, not when they happened. One read-only aggregate (`findBulkFactDays`, the rule the repair uses) over the+ * scoped sources' active facts reports each day with its fact and entity counts, the most frequent source tags and+ * how many claims state exactly one earlier date, and names the explicit-only `gbrain repair fact-claim-dates`+ * preview. Remote callers see only their permitted sources.+ */+export async function factBulkDatesCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ const name = 'fact_bulk_dates';+ const docs = 'docs/guides/repair.md#fact-claim-dates';+ try {+ const days = await findBulkFactDays(engine, sourceIds);+ const source_ids = [...new Set(days.map(d => d.source_id))];+ const details = { days, source_ids, rule: BULK_DAY_RULE, repair: 'fact-claim-dates', docs };+ if (!days.length) return { name, status: 'ok', details, message: 'No calendar day holds a bulk-loaded share of any source\'s facts.' };+ const first = days[0]!;+ const lines = days.map(d => `${d.source_id} ${d.day}: ${d.facts} of ${d.source_facts} active facts across ${d.entities} entities`+ + `${d.top_sources.length ? ` (source tags: ${d.top_sources.map(top => `${top.source} ${top.facts}`).join(', ')})` : ''}, ${d.dated_claims} state one earlier date in the claim`);+ return { name, status: 'warn', details,+ message: `${days.length} calendar day(s) hold a bulk-loaded share of a source's facts as their valid_from: ${lines.join('; ')}. `+ + 'These dates record when the facts were loaded, not when they happened, so timelines and as-of reads put every such fact on that day. '+ + `Preview moving the facts whose claim states its own date on the brain host: gbrain repair fact-claim-dates --source ${first.source_id}`+ + `${source_ids.length > 1 ? ` (one source at a time: ${source_ids.map(id => `--source ${id}`).join(', ')})` : ''} — it changes nothing until the user agrees `+ + 'to the apply command it prints; facts without a date in the claim keep the load day.',+ fix: agentFix(['gbrain', 'repair', 'fact-claim-dates', '--source', first.source_id, '--json'],+ 'Read-only preview: lists the facts whose claim states an earlier date, saves the set under a hash and prints the apply command.', name, { docs }) };+ } catch (error) {+ return checkError(name, 'look for bulk-loaded fact dates', error, { details: { days: 'unknown', docs } });+ }+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex fd1e55d209..8998f9e1ae 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -358,6 +358,7 @@ export const timelineHistoryEntry: DoctorEntry = {'conversation_outcomes_stale','captured_facts_active','facts_redaction_marker',+ 'fact_bulk_dates','loop_facts_drift','ontology_facts_fenced','stale_frontmatter_keys',diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex c38dccc236..6edee549c6 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -358,6 +358,12 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some active facts lost words to the pre-fix prompt sanitizer and hold a [redacted] marker in their stored text',run: async (engine, scope) => (await import('./checks/facts-redaction-marker.ts')).factsRedactionMarkerCheck(engine, scope.sourceIds),},+ {+ id: 'fact_bulk_dates', resolution: 'repair', registration: 'wave',+ count: d => Array.isArray(d.days) ? d.days.reduce((sum: number, day: { facts?: number }) => sum + Number(day.facts ?? 0), 0) : 0,+ impact: 'Some sources hold a large share of facts dated with the day a bulk load ran, which records when they were loaded, not when they happened',+ run: async (engine, scope) => (await import('./checks/fact-bulk-dates.ts')).factBulkDatesCheck(engine, scope.sourceIds),+ },{id: 'loop_facts_drift', resolution: 'repair', registration: 'wave',hostOnly: 'Retiring closed-loop commitment facts is a host-side, explicit-only repair.',diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 30fb3de4fe..3454a28716 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -78,6 +78,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <igbrain repair legacy-twins --source <id> [--apply --expect <preview-hash> --yes] [--json]gbrain repair uncommitted-deletions --source <id> [--after <page-id>] [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]+ gbrain repair fact-claim-dates --source <id> [--day YYYY-MM-DD] [--apply --expect <preview-hash> --yes] [--json]gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close][--apply --expect <preview-hash> --yes]] [--json]${REPAIR_CONTENT_HELP}@@ -137,7 +138,10 @@ Options:--after <page-id>uncommitted-deletions: preview the next window, below the next_after page id the previous preview printed;the hash and the apply command carry it.- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions --apply: the user agreed+ --day <YYYY-MM-DD>+ fact-claim-dates: the UTC day a bulk load stamped on the facts, instead of the days the preview detects;+ the hash and the apply command carry it.+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions, fact-claim-dates --apply: the user agreedto the previewed changes (destructive consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).@@ -154,7 +158,7 @@ A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/gRenames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held']);-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after']);+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--day']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],@@ -162,11 +166,11 @@ const KIND_FLAGS: Record<string, readonly string[]> = {'--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],- '--after': ['uncommitted-deletions'],+ '--after': ['uncommitted-deletions'], '--day': ['fact-claim-dates'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md','--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',- '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200' };+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--day': '2026-01-15' };/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });@@ -175,7 +179,7 @@ interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: booleanoLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;held: boolean; side?: string; state?: string;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number }+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number; day?: string }/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {@@ -276,6 +280,13 @@ export function parseRepairArgs(args: string[]): RepairArgs {['gbrain', 'repair', 'uncommitted-deletions', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);parsed.afterPage = Number(value);}+ else if (flag === '--day') {+ const [year, month, date] = value.split('-').map(Number);+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || new Date(Date.UTC(year!, month! - 1, date)).toISOString().slice(0, 10) !== value) throw invalid(`--day takes a calendar day as YYYY-MM-DD (got "${value}").`,+ 'Pass the UTC day doctor fact_bulk_dates reports, e.g. --day 2026-01-15, or omit --day to repair every detected day.',+ ['gbrain', 'repair', 'fact-claim-dates', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);+ parsed.day = value;+ }else if (flag === '--keep') keepText = value;else if (flag === '--request-id') {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw invalid(`--request-id must be a request UUID (got "${value}").`,@@ -366,7 +377,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,- prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force, from, close, afterPage } = parseRepairArgs(args);+ prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force, from, close, afterPage, day } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');// #6712 PR 2: a repair apply is a soak intervention; a file-drift apply is a content decision (soak-counters.ts).@@ -391,7 +402,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : []),...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),- ...(afterPage !== undefined ? ['--after', String(afterPage)] : []),+ ...(afterPage !== undefined ? ['--after', String(afterPage)] : []), ...(day ? ['--day', day] : []),...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),...(kind === 'origin-twins' ? slugs.flatMap(slug => ['--slug', slug]) : [])];const custom = repairSpec(kind as RepairKind).consentText;@@ -411,7 +422,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),- ...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}) }));+ ...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}),+ ...(k === kind && day ? { day } : {}) }));if (apply) clearHealthMemo(engine);const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex bd324a475a..d1da3263eb 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1054,6 +1054,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },+ { since: 'TBD', text: 'New doctor check `fact_bulk_dates` warns when one calendar day holds a bulk-loaded share of a source\'s facts as their `valid_from` (200 or more active facts, at least a quarter of the source, across 20 or more entities): those dates record when the facts were loaded, not when they happened. It names `gbrain repair fact-claim-dates --source <id>`, an explicit preview-then-apply repair that moves each such fact whose claim states exactly one earlier ISO date to that date, rewriting the page\'s facts fence row so the database follows the file; facts without a date keep the load day, and nothing changes on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 95d4e6438c..a26bab8f59 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -109,7 +109,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--timings', '--wait', '--yes'],'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],- 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],+ 'repair': ['--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--close', '--day', '--diff', '--expect', '--ff-only', '--force', '--force-break-lock', '--from', '--full', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--url', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 5150b8d182..6655659e00 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -62,6 +62,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['captured_facts_active',// #7125: facts whose stored text holds a pre-fix sanitizer redaction marker (doctor/checks/facts-redaction-marker.ts).'facts_redaction_marker',+ // #7247: a calendar day holding a bulk-loaded share of a source's facts as their valid_from (doctor/checks/fact-bulk-dates.ts).+ 'fact_bulk_dates','conversation_label_facts','conversation_outcomes_stale','connector_checkpoints',diff --git a/src/core/facts/bulk-days.ts b/src/core/facts/bulk-days.tsnew file mode 100644index 0000000000..90fa029d97--- /dev/null+++ b/src/core/facts/bulk-days.ts@@ -0,0 +1,97 @@+/**+ * #7247: calendar days that a bulk load stamped onto a large share of a+ * source's facts as their valid_from. A one-time backfill that wrote the day+ * it ran into every row's valid_from cell makes those facts look as if they+ * all happened that day; the dates record when the facts were loaded, not when+ * they happened. Doctor fact_bulk_dates reports such days and+ * `gbrain repair fact-claim-dates` moves the facts whose claim states its own+ * date; both detect days with findBulkFactDays, so they apply one rule.+ *+ * A bulk day of a source: a UTC calendar day of active facts' valid_from+ * holding at least min_facts facts and at least min_share of the source's+ * active facts, spread over at least min_entities distinct entity slugs.+ *+ * A claim date: the claim's only YYYY-MM-DD token (not adjacent to another+ * digit), when it is a real calendar date from 1900-01-01 up to the day before+ * the bulk day. claimDate (TypeScript) and claimDateSql (the aggregate the+ * doctor counts with) read the same token and apply the same bounds.+ */+import type { BrainEngine } from '../engine.ts';++export const BULK_DAY_RULE = { min_facts: 200, min_share: 0.25, min_entities: 20 } as const;++/** How many source tags a bulk day reports, most frequent first. */+const TOP_SOURCES = 5;++const DATE_TOKEN = '(^|[^0-9])([0-9]{4}-[0-9]{2}-[0-9]{2})(?![0-9])';+const EARLIEST = '1900-01-01';++export interface BulkFactDay {+ source_id: string;+ /** The UTC calendar day, YYYY-MM-DD. */+ day: string;+ facts: number;+ entities: number;+ /** The source's active facts, the share's denominator. */+ source_facts: number;+ top_sources: Array<{ source: string; facts: number }>;+ /** Facts of the day whose claim states exactly one ISO date earlier than the day (the date claimDate returns). */+ dated_claims: number;+}++export type ClaimDate = { date: string } | { skip: 'no_date' | 'several_dates' | 'date_not_earlier' };++/** The date a claim states for itself, judged against the bulk day it was loaded on. */+export function claimDate(claim: string, day: string): ClaimDate {+ const tokens = [...claim.matchAll(new RegExp(DATE_TOKEN, 'g'))].map(match => match[2]!);+ if (!tokens.length) return { skip: 'no_date' };+ if (tokens.length > 1) return { skip: 'several_dates' };+ const token = tokens[0]!;+ const [year, month, date] = token.split('-').map(Number) as [number, number, number];+ const real = new Date(Date.UTC(year, month - 1, date)).toISOString().slice(0, 10) === token;+ return real && token >= EARLIEST && token < day ? { date: token } : { skip: 'date_not_earlier' };+}++/** SQL truth of claimDate(claim, day) returning a date, for a text expression claim and a date expression day. */+function claimDateSql(claim: string, day: string): string {+ const d = 'x.dates[1]';+ return `(SELECT CASE WHEN cardinality(x.dates) = 1 AND ${d} >= '${EARLIEST}' AND ${d} < to_char(${day}, 'YYYY-MM-DD')+ AND substr(${d}, 6, 2) BETWEEN '01' AND '12' AND substr(${d}, 9, 2) BETWEEN '01' AND '31'+ THEN to_char(make_date(substr(${d}, 1, 4)::int, substr(${d}, 6, 2)::int, 1) + (substr(${d}, 9, 2)::int - 1), 'YYYY-MM-DD') = ${d}+ ELSE false END+ FROM (SELECT array_agg(m[2]) AS dates FROM regexp_matches(${claim}, '${DATE_TOKEN}', 'g') AS m) x)`;+}++/**+ * Every bulk day of the active sources (sourceIds narrows them), in (source, day) order. One read-only aggregate+ * over the sources' active facts.+ */+export async function findBulkFactDays(engine: BrainEngine, sourceIds?: string[]): Promise<BulkFactDay[]> {+ const rows = await engine.executeRaw<{ source_id: string; day: string; facts: number | string; entities: number | string; source_facts: number | string;+ top_sources: Array<{ source: string; facts: number | string }> | string | null; dated_claims: number | string }>(`+ WITH active AS MATERIALIZED (+ SELECT f.source_id, f.entity_slug, f.source, f.fact, (f.valid_from AT TIME ZONE 'UTC')::date AS day+ FROM facts f+ WHERE f.expired_at IS NULL+ AND f.source_id IN (SELECT id FROM sources WHERE archived IS NOT TRUE AND ($1::text[] IS NULL OR id = ANY($1::text[])))+ ), totals AS (+ SELECT source_id, count(*) AS n FROM active GROUP BY source_id+ ), bulk AS (+ SELECT a.source_id, a.day, count(*) AS n, count(DISTINCT a.entity_slug) AS entities, t.n AS source_facts+ FROM active a JOIN totals t ON t.source_id = a.source_id+ GROUP BY a.source_id, a.day, t.n+ HAVING count(*) >= $2::int AND count(*) >= t.n * $3::float8 AND count(DISTINCT a.entity_slug) >= $4::int+ )+ SELECT b.source_id, to_char(b.day, 'YYYY-MM-DD') AS day, b.n::int AS facts, b.entities::int AS entities, b.source_facts::int AS source_facts,+ (SELECT json_agg(json_build_object('source', s.source, 'facts', s.n) ORDER BY s.n DESC, s.source)+ FROM (SELECT a.source, count(*)::int AS n FROM active a WHERE a.source_id = b.source_id AND a.day = b.day+ GROUP BY a.source ORDER BY count(*) DESC, a.source LIMIT ${TOP_SOURCES}) s) AS top_sources,+ (SELECT count(*)::int FROM active a WHERE a.source_id = b.source_id AND a.day = b.day AND ${claimDateSql('a.fact', 'b.day')}) AS dated_claims+ FROM bulk b+ ORDER BY b.source_id, b.day`, [sourceIds ?? null, BULK_DAY_RULE.min_facts, BULK_DAY_RULE.min_share, BULK_DAY_RULE.min_entities]);+ return rows.map(row => {+ const tops = typeof row.top_sources === 'string' ? JSON.parse(row.top_sources) as Array<{ source: string; facts: number | string }> : row.top_sources ?? [];+ return { source_id: row.source_id, day: row.day, facts: Number(row.facts), entities: Number(row.entities), source_facts: Number(row.source_facts),+ top_sources: tops.map(top => ({ source: top.source, facts: Number(top.facts) })), dated_claims: Number(row.dated_claims) };+ });+}diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex f39f2a71c7..c7d3cc8ef2 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions' | 'fact-claim-dates';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex a8c3beec79..6752e7e348 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'fact-claim-dates'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -114,7 +114,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb/** `rename-identity` (#6729): the old slug that disambiguates a pair (`--from`), and the close disposition (`--close`). */from?: string; close?: boolean;/** `uncommitted-deletions` (#7130): the preview window starts below this page id (`--after`). */- afterPage?: number }+ afterPage?: number;+ /** `fact-claim-dates` (#7247): the bulk-loaded UTC day to repair (`--day`) instead of the detected ones. */+ day?: string }export interface RepairHandler {kind: RepairKind;@@ -310,7 +312,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sopts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number;+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; day?: string;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {@@ -334,7 +336,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),- ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}) };+ ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}),+ ...(opts.day ? { day: opts.day } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/fact-claim-dates.ts b/src/core/repair/fact-claim-dates.tsnew file mode 100644index 0000000000..10efc12106--- /dev/null+++ b/src/core/repair/fact-claim-dates.ts@@ -0,0 +1,251 @@+/**+ * `gbrain repair fact-claim-dates --source <id> [--day YYYY-MM-DD]` (#7247): give facts that a bulk load dated with+ * the day it ran the date their own claim states.+ *+ * A one-time backfill wrote one date, the day it ran, into the valid_from cell of a large share of a source's facts.+ * Those dates record when the facts were loaded, not when they happened, so timelines put every such fact on one day.+ * The real dates are unknown, except where the claim states one: "Acme Example closed a seed round on 2025-03-14".+ *+ * Candidates are active facts of the source whose valid_from falls on a bulk day (`findBulkFactDays`, the rule doctor+ * `fact_bulk_dates` reports with, or the explicit --day) and whose claim states exactly one ISO date, a real calendar+ * date from 1900 up to the day before (`claimDate`). Facts without a date, with several, or with one out of range are+ * counted and left as they are, and so is a fact whose valid_until falls before its claim's date.+ *+ * A fact held by a page's facts fence (`row_num` on `source_markdown_slug`) is moved in the page: its row's valid_from+ * cell becomes the claim's date and the page is published through a revision-bound put_page, so the canonical file+ * stays the source of truth and the facts row is re-projected from it. Every other row and cell of the fence is kept;+ * a page is listed and kept when its fence does not parse, it has fences on both sides of the timeline sentinel+ * (`gbrain repair split-facts`), it is stored in segments, or the rewritten fence would not read back as exactly the+ * planned rows. A row whose fence cell no longer reads the bulk day is counted `fence_mismatch`. A database-only fact+ * (no fence row) takes a direct valid_from update on an unmanaged brain; on a managed brain it is counted+ * `database_only_managed` and kept, because a managed write never changes a fact the canonical files do not hold.+ *+ * Explicit-only, preview-bound and destructive: the preview writes nothing, lists every page and database-only group+ * with its rows, and prints a hash over the pages' revisions, row numbers and new dates. `--apply --expect <hash> --yes`+ * recomputes the plan first and refuses `preview_changed` when it differs, then applies exactly the saved set,+ * keeping a page that moved meanwhile as `changed_since_preview`. Nothing runs on upgrade, from --all or from the+ * remediation plan.+ */+import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { factsFenceSection, factsFenceSections, normalizeClaimWhitespace, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';+import { claimDate, findBulkFactDays, type BulkFactDay } from '../facts/bulk-days.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';++const DOCS = 'docs/guides/repair.md#fact-claim-dates';+/** Rows a listing line names before it counts the rest. */+const LISTED_ROWS = 5;++type Section = 'compiled_truth' | 'timeline';+interface PlannedRow { row: number; day: string; date: string }+interface PagePlan { source_id: string; slug: string; revision: string; section: Section; rows: PlannedRow[] }+interface FactsPlan { source_id: string; entity_slug: string | null; rows: Array<{ id: number; valid_from: string; day: string; date: string }> }+interface Selection { source_ids: string[]; day: string | null }+interface Approved { selection: Selection; page?: PagePlan; facts?: FactsPlan }+interface ClaimItem extends RepairItem { approved: Approved; hash: string; last: boolean }++interface FactRow { id: number | string; entity_slug: string | null; fact: string; row_num: number | string | null; source_markdown_slug: string | null;+ valid_from: string; valid_until_day: string | null }++interface Plan { hash: string; days: BulkFactDay[]; pages: PagePlan[]; facts: FactsPlan[]; residuals: Record<string, number>; listing: RepairListing[] }++const previewCommand = (sourceId: string, day: string | null) => `gbrain repair fact-claim-dates --source ${sourceId}${day ? ` --day ${day}` : ''}`;++/** The UTC day a fence valid_from cell projects to, read the way the fence projection reads it. */+function cellDay(cell: string | undefined): string | null {+ if (!cell) return null;+ const date = new Date(cell);+ return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : null;+}++/**+ * The section's text with each planned row's valid_from cell set to its claim date, or null when the fence does not+ * parse cleanly, a planned row is gone, inactive or no longer on its bulk day, or the rewritten fence would not read+ * back as exactly the planned rows.+ */+function rewriteFence(page: Page, section: Section, rows: PlannedRow[]): string | null {+ const text = page[section] ?? '';+ const parsed = parseFactsFence(text);+ if (parsed.warnings.length) return null;+ const planned = new Map(rows.map(row => [row.row, row]));+ if (rows.some(row => { const fact = parsed.facts.find(f => f.rowNum === row.row); return !fact?.active || cellDay(fact.validFrom) !== row.day; })) return null;+ const next = parsed.facts.map(fact => planned.has(fact.rowNum) ? { ...fact, validFrom: planned.get(fact.rowNum)!.date } : fact);+ const rewritten = replaceOrInsertFactsFence(text, renderFactsTable(next));+ const reread = parseFactsFence(rewritten);+ return !reread.warnings.length && JSON.stringify(reread.facts) === JSON.stringify(next) ? rewritten : null;+}++const PAGE_RESIDUALS: Record<string, string> = {+ no_page: 'the page that holds these rows does not exist any more; nothing changed',+ segmented_page: 'the page stores its body in segments and this repair rewrites a fence by publishing the whole body; nothing changed',+ split_fences: 'the page has a facts fence on both sides of the timeline sentinel; merge them with gbrain repair split-facts, then preview again',+ unparsed: 'the facts fence does not parse cleanly; gbrain repair fences previews its repair, then preview again',+ not_conserved: 'the rewritten fence would not read back as exactly the planned rows; change these cells by hand',+};++/** The plan for one page's candidate rows: the rows to move, or the residual class that keeps the page. */+async function planPage(engine: BrainEngine, sourceId: string, slug: string, candidates: Array<{ row: FactRow; day: string; date: string }>,+ count: (key: string, n?: number) => void): Promise<{ plan: PagePlan } | { residual: string } | null> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot) return { residual: 'no_page' };+ if (isSegmentedPage(snapshot.page)) return { residual: 'segmented_page' };+ if (Object.values(factsFenceSections(snapshot.page)).every(Boolean)) return { residual: 'split_fences' };+ const section: Section = factsFenceSection(snapshot.page);+ const parsed = parseFactsFence(snapshot.page[section] ?? '');+ if (parsed.warnings.length) return { residual: 'unparsed' };+ const rows: PlannedRow[] = [];+ for (const { row, day, date } of candidates) {+ const fact = parsed.facts.find(f => f.rowNum === Number(row.row_num));+ if (fact?.active && cellDay(fact.validFrom) === day && normalizeClaimWhitespace(fact.claim) === normalizeClaimWhitespace(row.fact)) rows.push({ row: fact.rowNum, day, date });+ else count('fence_mismatch');+ }+ if (!rows.length) return null;+ rows.sort((a, b) => a.row - b.row);+ if (rewriteFence(snapshot.page, section, rows) === null) return { residual: 'not_conserved' };+ return { plan: { source_id: sourceId, slug, revision: snapshot.revision, section, rows } };+}++/** The whole plan for one source and selection, read-only, with the hash an apply must match. */+async function buildPlan(engine: BrainEngine, scope: RepairScope, selection: Selection): Promise<Plan> {+ const sourceId = selection.source_ids[0]!;+ const days = selection.day ? [] : await findBulkFactDays(engine, [sourceId]);+ const dayList = selection.day ? [selection.day] : days.map(d => d.day);+ const managed = await managedPersistenceEnabled(engine);+ const residuals: Record<string, number> = {};+ const count = (key: string, n = 1) => { residuals[key] = (residuals[key] ?? 0) + n; };+ const byPage = new Map<string, Array<{ row: FactRow; day: string; date: string }>>();+ const byEntity = new Map<string, FactsPlan>();+ for (const day of dayList) {+ const rows = await engine.executeRaw<FactRow>(`SELECT f.id, f.entity_slug, f.fact, f.row_num, f.source_markdown_slug, f.valid_from::text AS valid_from,+ to_char(f.valid_until AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS valid_until_day+ FROM facts f WHERE f.source_id = $1 AND f.expired_at IS NULL AND (f.valid_from AT TIME ZONE 'UTC')::date = $2::date ORDER BY f.id`, [sourceId, day]);+ for (const row of rows) {+ const found = claimDate(row.fact, day);+ if ('skip' in found) { count(found.skip); continue; }+ if (row.valid_until_day !== null && row.valid_until_day < found.date) { count('ends_before_claim_date'); continue; }+ if (row.row_num !== null && row.source_markdown_slug) {+ byPage.set(row.source_markdown_slug, [...(byPage.get(row.source_markdown_slug) ?? []), { row, day, date: found.date }]);+ } else if (managed) count('database_only_managed');+ else {+ const key = row.entity_slug ?? '';+ const group = byEntity.get(key) ?? { source_id: sourceId, entity_slug: row.entity_slug, rows: [] };+ group.rows.push({ id: Number(row.id), valid_from: row.valid_from, day, date: found.date });+ byEntity.set(key, group);+ }+ }+ }+ const pages: PagePlan[] = [];+ const listing: RepairListing[] = [];+ for (const slug of [...byPage.keys()].sort()) {+ const candidates = byPage.get(slug)!;+ const verdict = await planPage(engine, sourceId, slug, candidates, count);+ if (!verdict) continue;+ if ('residual' in verdict) {+ count(verdict.residual, candidates.length);+ listing.push({ item: `${sourceId}:${slug}`, class: verdict.residual, detail: `${candidates.length} row(s): ${PAGE_RESIDUALS[verdict.residual]}` });+ continue;+ }+ pages.push(verdict.plan);+ const shown = verdict.plan.rows.slice(0, LISTED_ROWS).map(row => `#${row.row} ${row.day} -> ${row.date}`).join(', ');+ const more = verdict.plan.rows.length - LISTED_ROWS;+ listing.push({ item: `${sourceId}:${slug} (revision ${verdict.plan.revision})`, class: 'rewrite',+ detail: `${verdict.plan.rows.length} fence row(s) take the date their claim states: ${shown}${more > 0 ? ` (+${more} more)` : ''}` });+ }+ const facts = [...byEntity.values()].sort((a, b) => (a.entity_slug ?? '').localeCompare(b.entity_slug ?? ''));+ for (const group of facts) {+ listing.push({ item: `${sourceId}:${group.entity_slug ?? '(no entity)'}`, class: 'update',+ detail: `${group.rows.length} database-only fact(s) take the date their claim states: ${group.rows.slice(0, LISTED_ROWS).map(row => `fact ${row.id} -> ${row.date}`).join(', ')}` });+ }+ const [brain] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id = $1', [sourceId]);+ const hash = previewHash({ kind: 'fact-claim-dates-v1', brain_id: scope.brain_id, source: { id: sourceId, incarnation: brain?.incarnation ?? null }, selection,+ days: dayList, pages: pages.map(({ slug, revision, section, rows }) => ({ slug, revision, section, rows })), facts });+ return { hash, days, pages, facts, residuals, listing };+}++function dayWarnings(plan: Plan, selection: Selection): string[] {+ if (selection.day) return [`--day ${selection.day} selects the active facts of ${selection.source_ids[0]} whose valid_from falls on that UTC day.`];+ return plan.days.map(d => `${d.source_id}: ${d.day} holds ${d.facts} of ${d.source_facts} active facts (${Math.round(100 * d.facts / d.source_facts)}%) across `+ + `${d.entities} entities${d.top_sources.length ? `, most tagged ${d.top_sources.map(top => `${top.source} (${top.facts})`).join(', ')}` : ''}. `+ + 'These dates record when the facts were loaded, not when they happened.');+}++function item(approved: Approved, index: number, hash: string, last: boolean): ClaimItem {+ const slug = approved.page?.slug ?? approved.facts?.entity_slug ?? '(no entity)';+ const rows = approved.page?.rows.length ?? approved.facts?.rows.length ?? 0;+ return { cursor: { phase: 1, id: index }, source_id: (approved.page ?? approved.facts)!.source_id, slug, chars: 0,+ action: approved.page ? `move ${rows} fence row(s) to their claim date` : `move ${rows} database-only fact(s) to their claim date`, approved, hash, last };+}++export const factClaimDatesRepair: RepairHandler = {+ kind: 'fact-claim-dates',+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ if (scope.source_ids.length !== 1) {+ throw opError('invalid_params', 'gbrain repair fact-claim-dates needs --source <id>.',+ 'A bulk load dates the facts of one source; name it, e.g. gbrain repair fact-claim-dates --source default.',+ { fix: readFix('Reports the bulk-dated days of every source, read-only.', { argv: ['gbrain', 'doctor', '--only', 'fact_bulk_dates', '--json'] }), docs: DOCS });+ }+ const selection: Selection = { source_ids: scope.source_ids, day: opts?.day ?? null };+ const command = previewCommand(scope.source_ids[0]!, selection.day);+ if (!opts?.apply) {+ const plan = await buildPlan(engine, scope, selection);+ const approved: Approved[] = [...plan.pages.map(page => ({ selection, page })), ...plan.facts.map(facts => ({ selection, facts }))];+ if (approved.length) await saveApprovedSet<Approved>(engine, { command: 'fact-claim-dates', hash: plan.hash }, approved);+ return { items: approved.map((entry, index) => item(entry, index, plan.hash, index === approved.length - 1)), preview_hash: plan.hash,+ residuals: plan.residuals, listing: plan.listing, warnings: dayWarnings(plan, selection) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair fact-claim-dates --apply moves only the set a preview printed.',+ `Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, DOCS);+ }+ // A fresh apply recomputes the plan; a resumed one replays the saved set, whose finished items moved their pages.+ const fresh = after ? null : await buildPlan(engine, scope, selection);+ if (fresh && fresh.hash !== opts.expect) throw previewChangedError(opts.expect, command);+ const approved = await loadApprovedSet<Approved>(engine, { command: 'fact-claim-dates', hash: opts.expect, previewCommand: command,+ emptyHash: async () => (fresh ?? await buildPlan(engine, scope, selection)).hash });+ if (approved.items.some(entry => entry.selection.day !== selection.day || entry.selection.source_ids.join('\u0000') !== selection.source_ids.join('\u0000'))) {+ throw previewChangedError(opts.expect, command);+ }+ return { items: approved.items.map((entry, index) => item(entry, index, opts.expect!, index === approved.items.length - 1)).filter(entry => afterCursor(entry.cursor, after)),+ preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { approved, hash, last } = entry as ClaimItem;+ const outcome = approved.page ? await movePage(ctx, entry, approved.page) : await moveFacts(ctx.engine, approved.facts!);+ if (last) await clearApprovedSet(ctx.engine, { command: 'fact-claim-dates', hash });+ return outcome;+ },+};++async function movePage(ctx: Parameters<RepairHandler['apply']>[0], entry: RepairItem, plan: PagePlan): Promise<RepairItemOutcome> {+ const snapshot = await ctx.engine.readPageSnapshot(plan.slug, { sourceId: plan.source_id });+ if (!snapshot || snapshot.revision !== plan.revision || isSegmentedPage(snapshot.page)) {+ return { applied: false, outcome: 'changed_since_preview', reason: 'the page changed since the preview' };+ }+ const text = rewriteFence(snapshot.page, plan.section, plan.rows);+ if (text === null) return { applied: false, outcome: 'changed_since_preview', reason: 'the planned fence rows no longer read their bulk day' };+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: plan.slug, source_id: plan.source_id,+ content: serializePageToMarkdown({ ...snapshot.page, [plan.section]: text }, snapshot.tags), expected_revision: snapshot.revision,+ request_id: await repairRequestId(ctx, 'fact-claim-dates', entry, snapshot.revision) } });+ return { applied: true, outcome: 'rewritten', detail: { rows: plan.rows.length } };+}++/** Database-only facts on an unmanaged brain: one maintenance transaction; a fact edited since the preview is left alone. */+async function moveFacts(engine: BrainEngine, plan: FactsPlan): Promise<RepairItemOutcome> {+ if (await managedPersistenceEnabled(engine)) return { applied: false, outcome: 'changed_since_preview', reason: 'the brain is managed now; database-only facts are kept' };+ const moved = await maintenanceTransaction(engine, tx => tx.executeRaw<{ id: number | string }>(`UPDATE facts f+ SET valid_from = (r.date || 'T00:00:00Z')::timestamptz+ FROM jsonb_to_recordset($2::text::jsonb) AS r(id bigint, valid_from text, date text)+ WHERE f.source_id = $1 AND f.id = r.id AND f.valid_from = r.valid_from::timestamptz AND f.expired_at IS NULL AND f.row_num IS NULL+ RETURNING f.id`, [plan.source_id, JSON.stringify(plan.rows.map(({ id, valid_from, date }) => ({ id, valid_from, date })))]));+ if (!moved.length) return { applied: false, outcome: 'changed_since_preview', reason: 'every fact was edited or expired since the preview' };+ return { applied: true, outcome: 'updated', detail: { facts: moved.length }, ...(moved.length < plan.rows.length+ ? { reason: `${plan.rows.length - moved.length} fact(s) were edited or expired since the preview and kept` } : {}) };+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 75722b75f7..822bf7fc85 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -81,6 +81,7 @@ import { missingTablesRepair } from './missing-tables.ts';import { urlCloneFencesRepair } from './url-clone-fences.ts';import { segmentedMirrorRepair } from './segmented-mirror.ts';import { uncommittedDeletionsRepair, UNCOMMITTED_DELETIONS_CONSENT_TEXT } from './uncommitted-deletions.ts';+import { factClaimDatesRepair } from './fact-claim-dates.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -499,6 +500,22 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'never deletes it again. Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create) can bring them back. '+ 'Runs only when named; never on upgrade.',},+ 'fact-claim-dates': {+ handler: factClaimDatesRepair, embeds: 'effect', checks: ['fact_bulk_dates'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Set the valid_from of the previewed facts to the date each one\'s claim states',+ why: 'The preview listed each facts fence row and database-only fact dated with the day a bulk load ran whose claim states exactly one earlier date; that date replaces the load day.',+ risk: 'Only the listed valid_from cells change; every other row and page stays as it is. Page edits publish through revision-bound put_page (a managed brain commits the file, so git revert undoes it; page history keeps the earlier revision). A page that changed since the preview is skipped.',+ user_message: 'Move the previewed facts to the date their claim states? Only their valid_from changes',+ },+ summary: 'Give facts that a bulk load dated with the day it ran the date their claim states (#7247). Needs --source; --day YYYY-MM-DD names the '+ + 'loaded day instead of the days doctor fact_bulk_dates detects (200+ active facts, 25%+ of the source, 20+ entities on one UTC day). Candidates '+ + 'are active facts of that day whose claim holds exactly one ISO date, a real date from 1900 to the day before; facts with none, several or one out '+ + 'of range are counted and kept. A fence row\'s valid_from cell is rewritten and the page published through revision-bound put_page, so the facts '+ + 'row follows the file; a database-only fact is updated directly on an unmanaged brain and counted database_only_managed on a managed one. '+ + 'Preview-bound and destructive: --apply --expect <hash> --yes recomputes the plan (preview_changed when it differs) and moves exactly the '+ + 'previewed rows. Runs only when named; never on upgrade.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));@@ -583,16 +600,17 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;- keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number } = {}): Promise<RepairResult> {+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number;+ day?: string } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),- ...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : [])],+ ...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : []), ...(run.day ? ['--day', run.day] : [])],explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,- held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });+ held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, day: run.day });},};}diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 9a765d5b01..01c7833b40 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -198,7 +198,7 @@ for (const backend of testBackends()) {frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift','stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity','overwritten-edits': 'gbrain repair overwritten-edits', 'legacy-twins': 'gbrain repair legacy-twins', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror',- 'uncommitted-deletions': 'gbrain repair uncommitted-deletions' };+ 'uncommitted-deletions': 'gbrain repair uncommitted-deletions', 'fact-claim-dates': 'gbrain repair fact-claim-dates' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 1e94de13dd..afc614ff22 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -130,6 +130,7 @@" [OK] conversation_outcomes_stale: No conversation extraction outcome predates extractor version 1."," [OK] captured_facts_active: No active fact from a gbrain self-capture or paste candidate remains. This counts facts in the database; the self_capture check counts corpus files."," [OK] facts_redaction_marker: No active fact holds a redaction marker.",+ " [OK] fact_bulk_dates: No calendar day holds a bulk-loaded share of any source's facts."," [OK] loop_facts_drift: Every closed commitment loop has its fact retired."," [OK] ontology_facts_fenced: No ontology observation is held by a page's Facts table."," [OK] stale_frontmatter_keys: No stored frontmatter carries a parser-reserved key (type, title, tags, slug).",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex ff1fdb6cfc..0c65acef52 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1787,6 +1787,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 3f5c059287..ee905fc141 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1966,6 +1966,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {@@ -6470,6 +6488,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex 9e75550f9c..2e5683841c 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1971,6 +1971,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {@@ -6476,6 +6494,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 3b78bfcb21..67840dcd53 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1664,6 +1664,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex c5f18ef387..8294a294d9 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1720,6 +1720,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 1234c1970d..c3e18f89ba 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1725,6 +1725,24 @@"name": "facts_redaction_marker","status": "ok"},+ {+ "category": "brain",+ "details": {+ "days": [],+ "docs": "docs/guides/repair.md#fact-claim-dates",+ "repair": "fact-claim-dates",+ "rule": {+ "min_entities": 20,+ "min_facts": 200,+ "min_share": 0.25+ },+ "source_ids": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No calendar day holds a bulk-loaded share of any source's facts.",+ "name": "fact_bulk_dates",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e4b55a8201..e18573d4c7 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -565,6 +565,10 @@"category": "brain","name": "facts_redaction_marker"},+ {+ "category": "brain",+ "name": "fact_bulk_dates"+ },{"category": "brain","name": "loop_facts_drift"diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.jsonindex cea21f666a..697343e2c4 100644--- a/test/fixtures/goldens/doctor/registry-report-remote.json+++ b/test/fixtures/goldens/doctor/registry-report-remote.json@@ -272,6 +272,10 @@{"category": "ops","name": "stale_embedding_effects"+ },+ {+ "category": "brain",+ "name": "fact_bulk_dates"}],"early_returns_after": [diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 6f8a671deb..26b0ba27a9 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -373,6 +373,7 @@ test/receipt-compaction-newest-sync-gbra130.test.tstest/remediation-manual-only.test.tstest/repair-apply-pending-6543.test.tstest/repair-embedding-effects.test.ts+test/repair-fact-claim-dates-7247.test.tstest/repair-failed-writes-conflict-6429.test.tstest/repair-failed-writes-drift-w411.test.tstest/repair-fences.test.tsdiff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 1bdcc370f6..166d6d1ee2 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions', 'fact-claim-dates'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-fact-claim-dates-7247.test.ts b/test/repair-fact-claim-dates-7247.test.tsnew file mode 100644index 0000000000..ea642cbb92--- /dev/null+++ b/test/repair-fact-claim-dates-7247.test.ts@@ -0,0 +1,232 @@+/**+ * #7247: doctor `fact_bulk_dates` and `gbrain repair fact-claim-dates`, on PGLite and Postgres (testBackends).+ *+ * Protects: a day a bulk load stamped onto a large share of a source's facts is reported read-only, with the same+ * rule the repair uses; the repair previews without writing, moves only fence rows whose claim states exactly one+ * earlier date by rewriting the page (so the facts row follows the canonical text), updates database-only facts+ * directly only on an unmanaged brain, refuses a stale preview, leaves every other row and page byte-identical and+ * finds nothing on a second preview.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName } from '../src/core/operations.ts';+import { parseFactsFence, renderFactsTable, type ParsedFact } from '../src/core/facts-fence.ts';+import { claimDate } from '../src/core/facts/bulk-days.ts';+import { factBulkDatesCheck } from '../src/commands/doctor/checks/fact-bulk-dates.ts';+import { runWaveChecks } from '../src/commands/doctor/wave-checks.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { AUTO_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const DAY = '2026-05-01';+const ACME = 'companies/acme-example';+const ALICE = 'people/alice-example';+const OTHER = 'companies/other-example';+const logger = { info() {}, warn() {}, error() {} };++const fence = (rows: Array<[number, string, string]>) => renderFactsTable(rows.map(([rowNum, claim, validFrom]) => ({ rowNum, claim, kind: 'fact', confidence: 1,+ visibility: 'world', notability: 'medium', validFrom, source: 'bulk-import', active: true })) as ParsedFact[]);+const page = (title: string, type: string, rows: Array<[number, string, string]>) =>+ `---\ntype: ${type}\ntitle: ${title}\n---\n${title} notes.\n\n## Facts\n\n${fence(rows)}\n`;++const ACME_ROWS: Array<[number, string, string]> = [+ [1, 'Acme Example closed a seed round on 2025-03-14', DAY],+ [2, 'Acme Example hired a head of sales', DAY],+ [3, 'Acme Example moved offices on 2024-01-10 and again on 2025-02-01', DAY],+ [4, 'Acme Example plans a launch on 2027-01-01', DAY],+ [5, 'Acme Example was founded on 2019-06-01', '2019-06-01'],+ [6, 'Acme Example opened a lab on 2023-02-30', DAY],+];++async function putPage(ctx: OperationContext, slug: string, content: string) {+ const prior = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' });+ await operationsByName.put_page.handler(ctx, { slug, content, ...(prior ? { expected_revision: prior.revision } : {}) });+}++/** The bulk load: 240 database-only facts over 24 entities on DAY (every 20th with an earlier date), plus two out-of-range dates. */+async function seedBulk(engine: BrainEngine) {+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from)+ SELECT 'default', 'companies/filler-' || (g % 24),+ CASE WHEN g % 20 = 0 THEN 'Filler example ' || g || ' was registered on 2024-03-15' ELSE 'Filler example ' || g || ' is a loaded claim' END,+ 'fact', 'world', 'bulk-import', $1::timestamptz+ FROM generate_series(1, 240) AS g`, [`${DAY}T00:00:00Z`]);+ for (const fact of ['Filler example dated 2023-02-30', 'Filler example dated 1899-12-31']) {+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from)+ VALUES ('default', 'companies/filler-0', $1, 'fact', 'world', 'bulk-import', $2::timestamptz)`, [fact, `${DAY}T00:00:00Z`]);+ }+}++async function seedPages(ctx: OperationContext) {+ await putPage(ctx, ACME, page('Acme Example', 'company', ACME_ROWS));+ await putPage(ctx, ALICE, page('Alice Example', 'person', [[1, 'Alice Example joined Acme Example on 2024-09-02', DAY]]));+ await putPage(ctx, OTHER, page('Other Example', 'company', [[1, 'Other Example ships quarterly', '2025-01-01']]));+}++const factState = (engine: BrainEngine) => engine.executeRaw<{ id: number; day: string; expired: boolean }>(+ `SELECT id, to_char(valid_from AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day, expired_at IS NOT NULL AS expired FROM facts ORDER BY id`);+const fenceDay = async (engine: BrainEngine, slug: string, row: number) => engine.executeRaw<{ day: string }>(+ `SELECT to_char(valid_from AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day FROM facts WHERE source_markdown_slug = $1 AND row_num = $2 AND expired_at IS NULL`, [slug, row]);+const fenceRows = async (engine: BrainEngine, slug: string) => parseFactsFence((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.compiled_truth).facts;+const revision = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;++async function preview(engine: BrainEngine, day?: string) {+ return (await repairRunner(engine, { apply: false, logger })).run('fact-claim-dates', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', day });+}+async function apply(engine: BrainEngine, expect: string, day?: string) {+ return (await repairRunner(engine, { apply: true, logger })).run('fact-claim-dates', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', expect, day });+}+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++/** Doctor: the bulk day with its counts; the SQL claim-date count agrees with claimDate on every fact of the day. */+async function expectFinding(engine: BrainEngine, dated: number) {+ const finding = await factBulkDatesCheck(engine);+ expect(finding.status).toBe('warn');+ expect(finding.message).toContain('record when the facts were loaded, not when they happened');+ expect(finding.fix).toMatchObject({ argv: ['gbrain', 'repair', 'fact-claim-dates', '--source', 'default', '--json'] });+ const [day] = finding.details!.days as Array<Record<string, any>>;+ expect(day).toMatchObject({ source_id: 'default', day: DAY, facts: 248, dated_claims: dated });+ expect(day!.entities).toBeGreaterThanOrEqual(24);+ expect(day!.top_sources[0]).toEqual({ source: 'bulk-import', facts: 248 });+ const claims = await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE expired_at IS NULL AND (valid_from AT TIME ZONE 'UTC')::date = $1::date`, [DAY]);+ expect(claims.filter(row => 'date' in claimDate(row.fact, DAY)).length).toBe(dated);+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`#7247 fact-claim-dates on a managed brain (${backend})`, () => {+ test('doctor finding; preview writes nothing; a stale preview refuses; apply rewrites exactly the planned fence rows; a second preview is empty', async () => {+ await managedBrain(async ({ engine, ctx, root }) => {+ await seedPages(ctx);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { await seedBulk(engine); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ await expectFinding(engine, 14);+ const wave = (await runWaveChecks(engine, { only: 'wave' })).find(f => f.spec.id === 'fact_bulk_dates')!;+ expect(wave.state).toBe('finding');+ expect(wave.spec.count(wave.check.details!)).toBe(248);++ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).not.toContain('fact-claim-dates');+ await expect((await repairRunner(engine, { apply: false, logger })).run('fact-claim-dates', await resolveRepairScope(engine, 'default'), { sourceFlag: 'default' }))+ .rejects.toMatchObject({ code: 'explicit_kind_required' });++ const before = await factState(engine);+ const revisions = { acme: await revision(engine, ACME), other: await revision(engine, OTHER) };+ const otherFile = readFileSync(join(root, `${OTHER}.md`), 'utf8');+ const dry = await preview(engine);+ expect(dry.affected).toBe(2);+ expect(dry.residuals).toEqual({ no_date: 229, several_dates: 1, date_not_earlier: 4, database_only_managed: 12 });+ expect(dry.listing!.map(entry => [entry.class, entry.item.split(' ')[0]])).toEqual([['rewrite', `default:${ACME}`], ['rewrite', `default:${ALICE}`]]);+ expect(dry.listing![0]!.detail).toContain(`#1 ${DAY} -> 2025-03-14`);+ expect(dry.warnings!.join('\n')).toContain('These dates record when the facts were loaded, not when they happened.');+ expect(dry.apply_command).toBe(`gbrain repair fact-claim-dates --source default --apply --expect ${dry.preview_hash} --yes`);+ expect(await factState(engine)).toEqual(before);+ expect(await revision(engine, ACME)).toBe(revisions.acme);++ expect((await refusal(() => apply(engine, 'f'.repeat(64)))).code).toBe('preview_changed');+ expect((await refusal(() => apply(engine, undefined as never))).code).toBe('invalid_params');+ // The plan moves when a candidate page does: the old hash refuses, a new preview approves the new plan.+ const stale = dry.preview_hash!;+ await putPage(ctx, ALICE, page('Alice Example', 'person', [[1, 'Alice Example joined Acme Example on 2024-09-02', DAY], [2, 'Alice Example likes tea', DAY]]));+ expect((await refusal(() => apply(engine, stale))).code).toBe('preview_changed');+ const fresh = await preview(engine);+ expect(fresh.preview_hash).not.toBe(stale);++ _resetCliExitVerdictForTests();+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try {+ await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () =>+ runRepairCommand(engine, ['fact-claim-dates', '--source', 'default', '--apply', '--expect', fresh.preview_hash!, '--yes', '--json']));+ } finally { console.log = original; }+ const applied = (JSON.parse(lines.join('\n')) as { results: Array<Record<string, any>> }).results[0]!;+ expect(applied).toMatchObject({ mode: 'apply', applied: 2, failed: [], outcomes: { rewritten: 2 } });++ const acme = await fenceRows(engine, ACME);+ expect(acme.find(row => row.rowNum === 1)!.validFrom).toBe('2025-03-14');+ expect(acme.filter(row => row.rowNum !== 1).map(row => [row.rowNum, row.claim, row.validFrom])).toEqual(ACME_ROWS.filter(([n]) => n !== 1));+ expect(await fenceDay(engine, ACME, 1)).toEqual([{ day: '2025-03-14' }]);+ expect(await fenceDay(engine, ACME, 2)).toEqual([{ day: DAY }]);+ expect(await fenceDay(engine, ALICE, 1)).toEqual([{ day: '2024-09-02' }]);+ expect(await fenceDay(engine, ALICE, 2)).toEqual([{ day: DAY }]);+ expect(readFileSync(join(root, `${ACME}.md`), 'utf8')).toContain('2025-03-14');+ // Other pages and database-only facts are untouched.+ expect(await revision(engine, OTHER)).toBe(revisions.other);+ expect(readFileSync(join(root, `${OTHER}.md`), 'utf8')).toBe(otherFile);+ const fillers = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE entity_slug LIKE 'companies/filler-%' AND expired_at IS NULL+ AND (valid_from AT TIME ZONE 'UTC')::date = $1::date`, [DAY]);+ expect(fillers[0]!.n).toBe(242);++ const again = await preview(engine);+ expect(again.affected).toBe(0);+ expect(again.residuals.database_only_managed).toBe(12);+ expect((await factBulkDatesCheck(engine)).details!.days).toMatchObject([{ day: DAY, dated_claims: 12 }]);+ }, { databaseUrl });+ }, 240_000);+ });++ describe(`#7247 fact-claim-dates on an unmanaged brain (${backend})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ let ctx: OperationContext;+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl!));+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ ctx = { engine, config: { engine: engine.kind, embedding_disabled: true } as never, sourceId: 'default', remote: false, dryRun: false, logger };+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });++ test('fence rows move through the page and database-only facts in place; scoped doctor; --day; idempotent', async () => {+ await seedPages(ctx);+ await seedBulk(engine);+ await putPage(ctx, 'companies/later-example', page('Later Example', 'company', [[1, 'Later Example signed a lease on 2025-12-01', '2026-06-10']]));+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('source-a', 'source-a') ON CONFLICT DO NOTHING`);+ await expectFinding(engine, 14);+ // A caller scoped to another source sees nothing of this one.+ expect((await factBulkDatesCheck(engine, ['source-a'])).status).toBe('ok');+ expect((await refusal(async () => (await repairRunner(engine, { apply: false, logger })).run('fact-claim-dates', await resolveRepairScope(engine), { explicit: true }))).code)+ .toBe('invalid_params');++ const revisions = { other: await revision(engine, OTHER), later: await revision(engine, 'companies/later-example') };+ const dry = await preview(engine);+ expect(dry.affected).toBe(8);+ expect(dry.residuals).toEqual({ no_date: 229, several_dates: 1, date_not_earlier: 4 });+ expect(dry.listing!.filter(entry => entry.class === 'update').map(entry => entry.detail!.split(':')[0])).toEqual(Array(6).fill('2 database-only fact(s) take the date their claim states'));++ const applied = await apply(engine, dry.preview_hash!);+ expect(applied.outcomes).toEqual({ rewritten: 2, updated: 6 });+ expect(await fenceDay(engine, ACME, 1)).toEqual([{ day: '2025-03-14' }]);+ expect(await fenceDay(engine, ALICE, 1)).toEqual([{ day: '2024-09-02' }]);+ const moved = await engine.executeRaw<{ day: string; n: number }>(`SELECT to_char(valid_from AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day, count(*)::int AS n FROM facts+ WHERE fact LIKE '%was registered on 2024-03-15' GROUP BY 1`);+ expect(moved).toEqual([{ day: '2024-03-15', n: 12 }]);+ expect(await revision(engine, OTHER)).toBe(revisions.other);+ expect(await revision(engine, 'companies/later-example')).toBe(revisions.later);+ expect((await preview(engine)).affected).toBe(0);+ expect((await factBulkDatesCheck(engine)).details!.days).toMatchObject([{ day: DAY, dated_claims: 0 }]);++ // --day names a loaded day the rule does not detect; the hash and apply command carry it.+ expect((await preview(engine)).listing!.some(entry => entry.item.includes('later-example'))).toBe(false);+ const named = await preview(engine, '2026-06-10');+ expect(named.affected).toBe(1);+ expect(named.apply_command).toContain('--day 2026-06-10');+ expect((await refusal(() => apply(engine, named.preview_hash!))).code).toBe('preview_changed');+ expect((await apply(engine, named.preview_hash!, '2026-06-10')).outcomes).toEqual({ rewritten: 1 });+ expect(await fenceDay(engine, 'companies/later-example', 1)).toEqual([{ day: '2025-12-01' }]);+ }, 240_000);+ });+}diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.tsindex c4d9fc5beb..4885f1c0d1 100644--- a/test/trust-write-gate-drift.test.ts+++ b/test/trust-write-gate-drift.test.ts@@ -56,6 +56,7 @@ const EXEMPT: Record<string, string> = {'src/core/persistence/memory-mutations.ts': 'forget (lifecycle); remember is gated in memory-prepare.ts','src/core/repair/captured-facts.ts': 'owner repair of existing rows','src/core/repair/consolidate-ties.ts': 'owner repair reopening the validity of existing facts (lifecycle)',+ 'src/core/repair/fact-claim-dates.ts': 'owner repair moving the valid_from of existing database-only facts to the date their claim states (lifecycle)','src/core/repair/extractor-facts.ts': 'owner repair of existing rows','src/core/repair/redacted-facts.ts': 'owner repair behind a preview hash: puts back into existing fact rows the words a stored source page proves; fenced rows publish through put_page, which runs the gate','src/core/repair/facts-rehome.ts': 'owner repair moving existing facts onto their entity page (placement)',