Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sweep): date corpus facts by the session file's write time (#6159)

garrytanabeff1cf699b
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 5ed19b80b1..02aaa001c3 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -21,7 +21,7 @@
- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; a `writer_busy_requeued` retry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and the `gbrain sweep --once` recovery; `details.corpus_backlog` counts corpus files with no `.ingested` sidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
-- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
+- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. `corpusFactTime(mtimeMs)` (#6159) validates the session file's write time (finite, from 2000, at most 60 s ahead); the sweep passes it as the facts pipeline's `turnAt`, which `facts/event-time.ts` `factEventTime` uses after the extractor's date and `validFrom`, so corpus facts are dated when the session was written and the observation date says so; `turnAt` stays out of the managed batch key, and a rejected time logs why and dates facts at extraction. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts`, `test/sweep-corpus-fact-time.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index f565e22d28..be9c9f1b4f 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -29,7 +29,7 @@
- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.
-- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`.
+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`.
- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired.
- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 370e1645e8..68bbb3d116 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -258,6 +258,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
{ since: '0.0.0-wave11', text: 'Frontmatter validation and `--fix` no longer flag or rewrite valid YAML (a block-scalar line shaped like `Key: "a", then "b"`); a file an earlier `gbrain frontmatter validate --fix` rewrote can be restored from its backup under ~/.gbrain/backups/frontmatter/.' },
+ { since: '0.0.0-wave11', text: 'Facts the sweep extracts from a saved session file are dated when the file was written, not when the sweep ran; facts saved earlier keep their dates.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.ts
index e808156333..0484df6622 100644
--- a/src/core/context/corpus-windows.ts
+++ b/src/core/context/corpus-windows.ts
@@ -278,6 +278,25 @@ export async function readCorpusProgress(full: string): Promise<CorpusProgress |
}
}
+/** The earliest file time trusted as when a session was written. */
+const MIN_FACT_TIME_MS = Date.UTC(2000, 0, 1);
+/** Clock skew a future file time may carry and still be trusted. */
+const FACT_TIME_SKEW_MS = 60_000;
+
+export type CorpusFactTime = { at: Date } | { rejected: 'invalid' | 'before_2000' | 'future' };
+
+/**
+ * #6159: the session file's write time as the time its facts happened. A time
+ * that is not finite, before 2000 or more than a minute ahead of now is not
+ * trusted, and the caller dates the facts at extraction instead.
+ */
+export function corpusFactTime(mtimeMs: number, nowMs: number = Date.now()): CorpusFactTime {
+ if (!Number.isFinite(mtimeMs)) return { rejected: 'invalid' };
+ if (mtimeMs < MIN_FACT_TIME_MS) return { rejected: 'before_2000' };
+ if (mtimeMs > nowMs + FACT_TIME_SKEW_MS) return { rejected: 'future' };
+ return { at: new Date(mtimeMs) };
+}
+
export function corpusFileStat(st: { size: number; mtimeMs: number; ino: number }): CorpusFileStat {
return { size: st.size, mtime_ms: st.mtimeMs, ino: st.ino };
}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 7e6f990b96..4cc65ff5d5 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -38,6 +38,7 @@
*/
import { observationDateFrom, resolveObservationDate, type ObservationDate } from '../ai/date-grounding.ts';
+import { factEventTime } from './event-time.ts';
import type { BrainEngine, FactInsertStatus, NewFact } from '../engine.ts';
import type { ResolutionSource } from '../entities/resolve.ts';
import { isFactsBackstopEligible } from './eligibility.ts';
@@ -135,7 +136,11 @@ export interface FactsBackstopCtx {
* context_pack / delta projections surface the provenance.
*/
sourceSlug?: string;
- /** #5888: when the source turn happened, for the capture-lane dedup window (default: now). */
+ /**
+ * #5888: when the source turn happened, for the capture-lane dedup window
+ * (default: now). #6159: also the facts' event time after validFrom (see
+ * factEventTime); unlike validFrom it is not part of the managed batch key.
+ */
turnAt?: Date;
/**
* #6048: with no request id (the batch is keyed by its input), re-admit the
@@ -642,7 +647,7 @@ async function runPipelineBodyInner(
engine: ctx.engine,
abortSignal,
model: ctx.model,
- notabilityAdmission, observationDate: input.observationDate ?? observationDateFrom(ctx.validFrom ?? null),
+ notabilityAdmission, observationDate: input.observationDate ?? observationDateFrom(ctx.validFrom ?? ctx.turnAt ?? null),
...(managed ? { embedding: managed.embedding ?? null } : {}),
});
const outcome = managed ? await withAIInvocationPreflight(async call => {
@@ -814,7 +819,7 @@ async function runPipelineBodyInner(
// #4206: caller event-time fallback + provenance context. #4819: a
// DB-only row has no fence to name the page it came from, so the page
// path's slug fills context when the caller passed no sourceSlug.
- valid_from: f.valid_from ?? ctx.validFrom,
+ valid_from: factEventTime(f, ctx),
context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource, f.entity_inferred),
};
const result = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)
@@ -848,7 +853,7 @@ async function runPipelineBodyInner(
confidence: f.confidence,
// #4206: extractor-derived date wins; then the caller's event time
// (historical imports); then import time.
- validFrom: f.valid_from ?? ctx.validFrom ?? new Date(),
+ validFrom: factEventTime(f, ctx) ?? new Date(),
embedding: f.embedding ?? null,
embedding_model: f.embedding_model ?? null, attributedTo: f.attributed_to ?? undefined,
sessionId: f.source_session ?? null,
@@ -901,7 +906,7 @@ async function runPipelineBodyInner(
embedding: f.embedding ?? null,
embedding_model: f.embedding_model ?? null, attributed_to: f.attributed_to ?? null,
// #4206: caller event-time fallback + provenance context.
- valid_from: f.valid_from ?? ctx.validFrom,
+ valid_from: factEventTime(f, ctx),
context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
const legacyResult = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)
@@ -934,7 +939,7 @@ async function runPipelineBodyInner(
embedding: f.embedding ?? null,
embedding_model: f.embedding_model ?? null, attributed_to: f.attributed_to ?? null,
// #4206: caller event-time fallback + provenance context.
- valid_from: f.valid_from ?? ctx.validFrom,
+ valid_from: factEventTime(f, ctx),
context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
const legacyResult = await maintenanceTransaction(ctx.engine, tx => tx.insertFact(newFact, { source_id: ctx.sourceId })); // gbrain-allow-direct-insert: DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)
diff --git a/src/core/facts/event-time.ts b/src/core/facts/event-time.ts
new file mode 100644
index 0000000000..76182cf401
--- /dev/null
+++ b/src/core/facts/event-time.ts
@@ -0,0 +1,10 @@
+/**
+ * When an extracted fact happened: the extractor's own date, then the
+ * caller's event time (`validFrom`), then the source turn's time (`turnAt`;
+ * #6159: a session-corpus file's write time). Undefined lets the writer fall
+ * back to now. `turnAt` is not part of the managed facts batch key, so using
+ * it never re-keys a batch already tried.
+ */
+export function factEventTime(fact: { valid_from?: Date | null }, ctx: { validFrom?: Date; turnAt?: Date }): Date | undefined {
+ return fact.valid_from ?? ctx.validFrom ?? ctx.turnAt;
+}
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 6cff7dc029..dd86faf89b 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -2,6 +2,7 @@ import { isConnectorSourceKind } from './connector-identity.ts';
import type { BrainEngine, NewFact } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { FactsBackstopCtx } from '../facts/backstop.ts';
+import { factEventTime } from '../facts/event-time.ts';
import { ENTITY_HINTS_CAP, type ExtractedFact, type FactEmbeddingSignature } from '../facts/extract.ts';
import { readFactsEmbeddingDim } from '../embedding-dim-check.ts';
import type { OperationContext } from '../ops/contract.ts';
@@ -371,7 +372,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
// #5836: an inferred subject carries its provenance note into the fence cell and the row.
group.push({ ...fact, entity_slug: attributed, visibility, context: fact.entity_inferred ? appendContextNote(context, inferenceNote(fact.entity_inferred)) : context,
embedding: fact.embedding ? Array.from(fact.embedding) : null,
- valid_from: (fact.valid_from ?? ctx.validFrom ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });
+ valid_from: (factEventTime(fact, ctx) ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });
groups.set(slug, group);
}
const inputs: ManagedFactsEntityInput[] = [];
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index ef921014e7..d72a67cc7c 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -756,6 +756,11 @@ async function runCorpusIngestPass(
const wbSourceId = wbMeta?.sourceId && isValidSourceId(wbMeta.sourceId)
? wbMeta.sourceId
: sourceId;
+ // #6159: facts happened when the session file was written, not when this (possibly late) sweep runs.
+ const factTime = windows.corpusFactTime(fileStat.mtime_ms);
+ if ('rejected' in factTime) {
+ log(`[sweep] ${name}: file time not trusted (${factTime.rejected}); its facts are dated at extraction time.`);
+ }
const pipelineCtx: FactsBackstopCtx = {
engine,
sourceId: wbMeta ? wbSourceId : sourceId,
@@ -769,8 +774,9 @@ async function runCorpusIngestPass(
mode: 'inline',
remote: false,
abortSignal: signal,
- // #5888: the file's write time anchors the capture dedup window, not the (possibly late) sweep.
- turnAt: await stat(full).then(st => st.mtime, () => undefined),
+ // #5888/#6159: the file's write time anchors the capture dedup window and dates the facts
+ // (turnAt, never validFrom: validFrom is part of the managed batch key).
+ turnAt: 'at' in factTime ? factTime.at : undefined,
reAdmitFileRefusals: true,
...(wbMeta && wbCfg.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),
// visibility deliberately unset → resolveDefaultVisibility [ENG-8]
diff --git a/test/managed-sweep-corpus-windows.test.ts b/test/managed-sweep-corpus-windows.test.ts
index ccbeac55a2..1851a85c77 100644
--- a/test/managed-sweep-corpus-windows.test.ts
+++ b/test/managed-sweep-corpus-windows.test.ts
@@ -16,7 +16,7 @@
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -143,3 +143,44 @@ test('managed: every window commits its own coordinated facts batch; a resume su
}
}
}, 180_000);
+
+// #6159: on a managed brain the coordinated facts batch carries the session file's write time as
+// valid_from (facts-maintenance.ts), without putting it in the batch key.
+test('managed: facts from a session file written 8 days ago are dated that day', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-sweep-fact-time-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const corpusDir = join(dir, 'corpus'); mkdirSync(corpusDir);
+ const sourceId = `facttime-${randomUUID().slice(0, 8)}`;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);
+ await claimWorktree(engine, sourceId, root);
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/alice-example',
+ content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n', request_id: randomUUID() } });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+
+ const file = join(corpusDir, 'backdated-session.txt');
+ writeFileSync(file, corpus(1));
+ const written = new Date(Date.now() - 8 * 86_400_000);
+ utimesSync(file, written, written);
+ await runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000 });
+ const rows = await engine.executeRaw<{ valid_from: Date }>(
+ `SELECT valid_from FROM facts WHERE source_id=$1 AND source='sweep:corpus' AND expired_at IS NULL`, [sourceId]);
+ expect(rows).toHaveLength(1);
+ expect(new Date(rows[0].valid_from).toISOString().slice(0, 10)).toBe(written.toISOString().slice(0, 10));
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}, 180_000);
diff --git a/test/sweep-corpus-fact-time.test.ts b/test/sweep-corpus-fact-time.test.ts
new file mode 100644
index 0000000000..c8b3b0ae1c
--- /dev/null
+++ b/test/sweep-corpus-fact-time.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #6159 — the sweep's corpus pass dates facts by the session file's write
+ * time, not by when the (possibly late) sweep ran.
+ *
+ * Protects: a backdated session file yields facts whose valid_from is the
+ * file's day, and the extractor is told that day as the observation date;
+ * a file time that cannot be trusted (in the future, or before 2000) falls
+ * back to extraction time; the file time stays out of the managed batch key
+ * (persistence/facts-maintenance.ts digests validFrom, not turnAt), so it
+ * never re-keys a window already tried.
+ * Fails when: the corpus pass stamps facts at extraction time again.
+ * Hermetic in-memory PGLite + chat-transport stub (sweep.test.ts harness).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runMaintenanceSweep } from '../src/core/sweep.ts';
+import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import type { CapabilityReport } from '../src/core/capability.ts';
+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
+import { corpusFactTime } from '../src/core/context/corpus-windows.ts';
+
+const KEYED: CapabilityReport = {
+ embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' },
+ search: 'keyword-only',
+ mode: 'keyed',
+};
+const DAY = 86_400_000;
+
+let engine: PGLiteEngine;
+let dir: string;
+let prompts: string[];
+const tmpDirs: string[] = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => {
+ await engine.disconnect();
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts').catch(() => {});
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-fact-time-'));
+ tmpDirs.push(dir);
+ await engine.setConfig('dream.synthesize.session_corpus_dir', dir);
+ prompts = [];
+ __setChatTransportForTests(async (request): Promise<ChatResult> => {
+ const content = String(request.messages[0].content);
+ prompts.push(content);
+ const tag = content.match(/KITEMARK (\w+)/)?.[1];
+ const facts = tag
+ ? [{ fact: `Keeps the ${tag} checklist in the team wiki`, kind: 'preference', entity: null, confidence: 0.9, notability: 'high' }]
+ : [];
+ return { text: JSON.stringify({ facts }), blocks: [], stopReason: 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:test-stub', providerId: 'anthropic' };
+ });
+});
+afterEach(() => { __setChatTransportForTests(null); });
+
+const sweep = () => runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED, budgetMs: 120_000, batchLimit: 20 });
+const session = (name: string, mtime: Date): void => {
+ const file = join(dir, name);
+ writeFileSync(file, toCorpusText([{ role: 'user', text: `KITEMARK ${name.replace(/\W.*/, '')} I keep that checklist in the team wiki.` }]));
+ utimesSync(file, mtime, mtime);
+};
+const factDates = async () => (await engine.executeRaw<{ valid_from: Date }>(
+ "SELECT valid_from FROM facts WHERE source = 'sweep:corpus'")).map((r) => new Date(r.valid_from));
+
+describe('corpus fact time (#6159)', () => {
+ test('a session file written 8 days ago yields facts dated that day, and the extractor is told so', async () => {
+ const written = new Date(Date.now() - 8 * DAY);
+ session('backdated.txt', written);
+ await sweep();
+ const dates = await factDates();
+ expect(dates).toHaveLength(1);
+ expect(Math.abs(dates[0].getTime() - written.getTime())).toBeLessThan(2_000);
+ expect(prompts.join('\n')).toContain(`Observation date: ${written.toISOString().slice(0, 10)}`);
+ });
+
+ test('an untrusted file time (future, or before 2000) dates facts at extraction', async () => {
+ session('future.txt', new Date(Date.now() + 3 * DAY));
+ session('ancient.txt', new Date('1990-01-01T00:00:00Z'));
+ const before = Date.now();
+ await sweep();
+ const dates = await factDates();
+ expect(dates).toHaveLength(2);
+ for (const d of dates) expect(d.getTime()).toBeGreaterThanOrEqual(before - 1_000);
+ });
+
+ test('corpusFactTime accepts a sane file time and rejects the rest with a reason', () => {
+ const now = Date.parse('2026-10-06T12:00:00Z');
+ expect(corpusFactTime(now - DAY, now)).toEqual({ at: new Date(now - DAY) });
+ expect(corpusFactTime(now + 30_000, now)).toEqual({ at: new Date(now + 30_000) });
+ expect(corpusFactTime(now + 61_000, now)).toEqual({ rejected: 'future' });
+ expect(corpusFactTime(Date.parse('1999-12-31T23:59:59Z'), now)).toEqual({ rejected: 'before_2000' });
+ expect(corpusFactTime(Number.NaN, now)).toEqual({ rejected: 'invalid' });
+ });
+});