Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: wave review follow-ups (semgrep, module size, remember content_origin, currency dates, behavior notices)

garrytan4b113dd1ea6c
diff --git a/docs/architecture/key-files/core-memory.md b/docs/architecture/key-files/core-memory.md
index d02aa116c3..c4582623af 100644
--- a/docs/architecture/key-files/core-memory.md
+++ b/docs/architecture/key-files/core-memory.md
@@ -54,7 +54,8 @@ notice). User guide: [core memory](../../guides/core-memory.md).
- `src/core/remember-batch.ts`: `remember` with `items[]` (all-or-none
validation, deterministic child request ids, per-item status; #7248: an
item still publishing is `pending` with its `target`, not `failed`; #7432:
- a top-level `entity` is the default subject of every item that sets none).
+ every item field but `fact` and `replaces`, `entity`, `content_origin` and
+ `valid_from` included, is also a top-level default an item's own value overrides).
- `src/commands/core.ts` (`gbrain core`), `src/commands/doctor/checks/core-memory.ts`
(`core_memory`), schema `src/core/core-memory-schema.ts` + migration v213.
- Tests: `test/core-memory.test.ts`, `test/core-guard.test.ts`,
diff --git a/docs/guides/core-memory.md b/docs/guides/core-memory.md
index 2b578828a9..d63d70476b 100644
--- a/docs/guides/core-memory.md
+++ b/docs/guides/core-memory.md
@@ -120,9 +120,10 @@ Two pieces cover that:
- `remember` takes `items`: up to 20 facts in one call, each with the usual
fields (`fact`, optional `entity`, `kind`, `ttl`, `visibility`,
- `provenance`); top-level `entity`, `kind`, `ttl`, `visibility` and
- `provenance` are the defaults for items that omit them. Every item is
- validated before anything is written; each item is then saved as its own write and reported with its own status, and
+ `provenance`, `content_origin`, `valid_from`); the same top-level fields
+ are the defaults for items that omit them. Every item is validated before
+ anything is written; each item is then saved as its own write and reported
+ with its own status, and
`partial: true` marks a batch where some items failed. Replaying the same
`request_id` replays the same per-item outcomes.
- When a session's context is about 80% full, or sooner when it is growing
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 7b82c8e83b..694028ab5d 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -386,9 +386,9 @@ Optional response fields; clients must ignore any they do not know.
`items` (1 to 20) replaces `fact` for a batch, typically right before
context compaction. Each item is a fact string or an object with `fact` plus
optional `entity`, `kind`, `ttl`, `visibility`, `provenance`,
-`infer_entity` and `replaces`; top-level `provenance`, `entity`,
-`kind`, `ttl`, `visibility` and `infer_entity` are the defaults for items that
-omit them, so top-level `provenance` is optional when every item carries its own. `replaces` names one
+`content_origin`, `valid_from`, `infer_entity` and `replaces`; top-level
+`provenance`, `entity`, `kind`, `ttl`, `visibility`, `content_origin`,
+`valid_from` and `infer_entity` are the defaults for items that omit them, so top-level `provenance` is optional when every item carries its own. `replaces` names one
fact, so it goes on its item; passing both `fact` and `items`, or a top-level
`replaces` with `items`, is `invalid_params`.
diff --git a/llms-full.txt b/llms-full.txt
index 15b0fbc1ba..3d1c709bb5 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9245,9 +9245,9 @@ Optional response fields; clients must ignore any they do not know.
`items` (1 to 20) replaces `fact` for a batch, typically right before
context compaction. Each item is a fact string or an object with `fact` plus
optional `entity`, `kind`, `ttl`, `visibility`, `provenance`,
-`infer_entity` and `replaces`; top-level `provenance`, `entity`,
-`kind`, `ttl`, `visibility` and `infer_entity` are the defaults for items that
-omit them, so top-level `provenance` is optional when every item carries its own. `replaces` names one
+`content_origin`, `valid_from`, `infer_entity` and `replaces`; top-level
+`provenance`, `entity`, `kind`, `ttl`, `visibility`, `content_origin`,
+`valid_from` and `infer_entity` are the defaults for items that omit them, so top-level `provenance` is optional when every item carries its own. `replaces` names one
fact, so it goes on its item; passing both `fact` and `items`, or a top-level
`replaces` with `items`, is `invalid_params`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d80c32e3c9..3b92139c06 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli/main.ts 2955 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SEL
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
-src/commands/extract-conversation-facts.ts 2046 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts)
+src/commands/extract-conversation-facts.ts 2049 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts); +3 #7438: ExtractConversationFactsResult.facts_skipped_purged (interface field) and one notePurgedSkips call (the count and log live in core/facts/conversation-publication.ts)
src/commands/extract.ts 2700 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured; +16 #7394: --type/--since/--infer-dates on the file walk refuse with the --source db command beside the other --source db refusals, and the help says so; +5 GBRA-161 PR 5 (T-2, L-6): timeline retraction and the mention rebuild sweep are bound to the revision they read (PageRevisionConflictError import, the scanned-revision read and its FOR SHARE check); +2 GBRA-133: ExtractOpts.timeBudgetMs, forwarded to the managed stale-page pass so the cycle bounds a pass with no slug list
src/commands/jobs.ts 687 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts); +20 #7242 jobs wait: subcommand row, import, usage lines and its --help text with the exit codes (logic in jobs/wait.ts)
src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index e597d5544a..417dae4bb7 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -78,7 +78,7 @@ import {
import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';
import { writeDerivedFacts } from '../core/persistence/derived-facts.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
-import { countConversationFacts, enqueueManagedPage, flushManagedBatch, managedConversationPublisher, publishConversationFacts, startManagedPage, stopsRun, type ConversationScope, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';
+import { countConversationFacts, enqueueManagedPage, flushManagedBatch, managedConversationPublisher, notePurgedSkips, publishConversationFacts, startManagedPage, stopsRun, type ConversationScope, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';
import { ConversationRunClaims, listConversationPagesBySlug } from '../core/facts/conversation-enumeration.ts';
import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';
import { noPricingMessage } from '../core/budget/no-pricing.ts';
@@ -1138,10 +1138,7 @@ async function processPage(
state.result.facts_inserted += published.facts_inserted;
state.result.orphan_facts_cleaned += published.deleted;
if (published.duplicates_skipped) process.stderr.write(`[extract-conversation-facts] ${page.slug}: skipped ${published.duplicates_skipped} fact(s) an active fact of the source already states (#7043)\n`);
- if (published.purged_skipped) {
- state.result.facts_skipped_purged = (state.result.facts_skipped_purged ?? 0) + published.purged_skipped;
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: left out ${published.purged_skipped} extracted fact(s) that match a purge tombstone (#7438)\n`);
- }
+ notePurgedSkips(state.result, page.slug, published.purged_skipped);
if (published.facts_inserted + published.duplicates_skipped + published.purged_skipped < pageRows.filter(row => row.source !== TERMINAL_AUDIT_SOURCE).length) {
process.stderr.write(`[extract-conversation-facts] ${page.slug}: kept its prior facts; this ${scope} run's facts were not published over them (#7013)\n`);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 722d9c8be4..ae60bbf8d7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1224,6 +1224,14 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-175 (stable channel, upgrade restarts every process). `since` is stamped at the merge slot.
{ since: '0.60.428.0', id: 'upgrade_restarts_7245', text: '`gbrain upgrade` now restarts every gbrain process this brain runs on the host onto the new build (serve and autopilot through their installed services, the jobs supervisor and its worker with `gbrain jobs supervisor stop` then `start --detach`) and verifies that they all report one build and that the warm CLI socket accepts it. Before installing anything it refuses with `restart_refused` (exit 3) when a process cannot be restarted automatically: a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started (rerun with `--stop-mcp` to stop those; reconnect gbrain in each harness afterwards). `--no-restart` installs without restarting; `gbrain upgrade --restart-only` restarts onto the installed build (`--dry-run` previews). The autopilot `--swap-only` channel is unchanged.' },
{ since: '0.60.428.0', id: 'runtime_build_skew_fails_7245', text: 'doctor `runtime_build_skew` now fails (was a warning) when two or more gbrain builds run on this host, and its fix asks the user before running `gbrain upgrade --restart-only`; one process older than its install alone still warns. New release channel: `gbrain upgrade --channel stable` or `gbrain config set self_upgrade.channel stable` installs only releases a maintainer promoted after the production-shaped soak passed on their exact tree, and the update checks then offer only that release; the default channel (`latest`) is unchanged.' },
+ // GBRA-190 (verified-bug wave). `since` is stamped at the merge slot.
+ { since: '0.60.428.0', text: 'Upgrading builds the index `pages_source_created_idx` (migration v270) over live pages by source and creation time: on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. With it, `gbrain facts relink --conversation` (dry runs included) and doctor `unlinked_facts` check for a page created since each relink attempt with one index probe instead of reading every live page of the source, which ran into `statement_timeout` on large brains (#7379).' },
+ { since: '0.60.428.0', text: 'A `remember` items batch now applies the top-level `entity`, `content_origin` and `valid_from` to every item that does not set its own, as it already did for `provenance`, `kind`, `ttl` and `visibility`, and accepts `content_origin` and `valid_from` on an item. Before, a top-level `entity` was ignored (the items were saved with no subject and a `NO_ENTITY` warning), a top-level `content_origin: tool_output` was ignored, so batched tool output was stored at the writer\'s trust tier instead of `external_untrusted`, and an item carrying `content_origin` or `valid_from` was refused (#7432).' },
+ { since: '0.60.428.0', text: 'Conversation-facts extraction leaves out an extracted claim that matches a purge tombstone and publishes the rest of the page (the run reports `facts_skipped_purged`). Before, that one claim made the facts insert guard refuse the page\'s whole insert after the model call was paid for, and on a managed brain every page in the same batch request failed with it and was blocked after three attempts until it changed (#7438).' },
+ { since: '0.60.428.0', text: 'The extract_atoms backlog (doctor, `dream --phase extract_atoms --drain` and autopilot drains) now counts a page whose last extraction was cut at a lower `cycle.extract_atoms.max_input_chars` than the current cap, so raising the cap re-extracts those pages, with model calls, instead of the drain reporting drained with 0 batches. At an unchanged or lowered cap nothing changes (#7391).' },
+ { since: '0.60.428.0', text: 'Hermes transcript import keeps the answers a user gave in a `clarify` form (answered responses of a submitted form, or the answers a timed-out form had already locked) as user turns, each after its question as the assistant\'s turn. A Hermes session imported before re-renders on its next import scan when it holds such answers, which can run fact extraction for that page again (#7396).' },
+ { since: '0.60.428.0', text: 'Fact subject inference links more facts and fewer wrong ones: a currency code next to an amount (`CHF 80`) and a record label opening a sentence (`Invoice ...`, `Work session ...`) no longer block a fact that names one person or company, and an entity introduced only as an example (`including X notes`, `for example, X`) is never chosen as the subject. A page named like the code or label still competes. A sentence that opens with `For example, X ...` no longer takes X as its subject (#7405).' },
+ { since: '0.60.428.0', text: '`gbrain think` gives reasoning models from gpt-5 on 16,000 output tokens behind any provider or router prefix, as it already did for gpt-5 and the o-series on their own provider; gpt-6 ids get it too. Before, those got 4,000 and long answers came back truncated (`LLM_OUTPUT_TRUNCATED`). Providers bill the tokens used, not the cap (#7421).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index 78c9a57f45..e8dab83253 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -795,14 +795,18 @@ async function enqueueEntry(state: ManagedRunState, entry: ConversationPageEntry
if (m.batch.length >= batchCaps.pages || factPages >= batchCaps.factPages || m.bytes >= cap) await flushManagedBatch(state);
}
+/** #7438: counts and logs a page's extracted claims left out because they match a purge tombstone. */
+export function notePurgedSkips(counters: { facts_skipped_purged?: number }, slug: string, skipped: number): void {
+ if (!skipped) return;
+ counters.facts_skipped_purged = (counters.facts_skipped_purged ?? 0) + skipped;
+ log(`${slug}: left out ${skipped} extracted fact(s) that match a purge tombstone (#7438)`);
+}
+
/** Books one member's committed-batch result into the run's counters. */
function bookPage(state: ManagedRunState, result: ConversationPageResult): void {
state.result.orphan_facts_cleaned += Number(result.deleted ?? 0);
state.result.facts_inserted += Number(result.facts_inserted ?? 0);
- if (result.facts_skipped_purged) {
- state.result.facts_skipped_purged = (state.result.facts_skipped_purged ?? 0) + result.facts_skipped_purged;
- log(`${result.slug}: left out ${result.facts_skipped_purged} extracted fact(s) that match a purge tombstone (#7438)`);
- }
+ notePurgedSkips(state.result, result.slug, result.facts_skipped_purged ?? 0);
if (result.status === 'skipped') {
state.result.pages_failed++;
log(`${result.slug} changed during extraction (${result.reason}); its prior facts were kept and it stays unfinished for the next run`);
diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.ts
index 7c4bd1d634..07a16b599f 100644
--- a/src/core/facts/subject-infer.ts
+++ b/src/core/facts/subject-infer.ts
@@ -189,18 +189,27 @@ function isNonName(query: string): boolean {
return isCommonCapitalizedWord(query) || ROLE_AND_TERM_TOKENS.has(query.toLowerCase());
}
-/** Every whole-word use of `query` in the fact, case-insensitive. */
-function referenceUses(fact: string, query: string): RegExpMatchArray[] {
- const literal = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- return [...fact.matchAll(new RegExp(`(?<![\\p{L}\\p{N}_/-])${literal}(?![\\p{L}\\p{N}_/-])`, 'giu'))];
+const WORD_CHAR = /[\p{L}\p{N}_/-]/u;
+/** The start offsets of every whole-word use of `query` in the fact, case-insensitive. */
+function referenceUses(fact: string, query: string): number[] {
+ const haystack = fact.toLowerCase(), needle = query.toLowerCase(), starts: number[] = [];
+ if (!needle || haystack.length !== fact.length) return starts;
+ for (let at = haystack.indexOf(needle); at !== -1; at = haystack.indexOf(needle, at + 1)) {
+ if (!WORD_CHAR.test(fact.charAt(at - 1)) && !WORD_CHAR.test(fact.charAt(at + needle.length))) starts.push(at);
+ }
+ return starts;
}
-/** #7405: a currency code is a unit only when every use is next to an amount; resolution runs first, so a page named CHF still competes. */
+/**
+ * #7405: a currency code is a unit only when every use is next to an amount ("CHF 80", "80 CHF"), never a date or time
+ * ("2025-01-01 CHF"); resolution runs first, so a page named CHF still competes.
+ */
+const AMOUNT_AFTER = /^\s*\d[\d,.']*(?![\d/:-])/u;
+const AMOUNT_BEFORE = /(?:^|[^\d,.'/:-])\d[\d,.']*\s*$/u;
function isAmountUnit(fact: string, query: string): boolean {
if (!CURRENCY_CODES.has(query)) return false;
const uses = referenceUses(fact, query);
- return uses.length > 0 && uses.every(m =>
- /^\s*\d/u.test(fact.slice(m.index! + m[0].length)) || /\d\s*$/u.test(fact.slice(0, m.index)));
+ return uses.length > 0 && uses.every(at => AMOUNT_AFTER.test(fact.slice(at + query.length)) || AMOUNT_BEFORE.test(fact.slice(0, at)));
}
/**
@@ -211,7 +220,7 @@ function isAmountUnit(fact: string, query: string): boolean {
const EXAMPLE_LIST_LEAD = /(?:^|[^\p{L}])(?:[Ii]ncluding|[Ss]uch as|[Ff]or example|[Ff]or instance|[Ee]\.g\.)[,:]?\s+(?:\p{Lu}[\p{L}\p{N}'’./-]*(?:\s+\p{Lu}[\p{L}\p{N}'’./-]*)*\s*(?:,\s*(?:and\s+|or\s+)?|\s+(?:and|or)\s+))*$/u;
function onlyExampleUses(fact: string, query: string): boolean {
const uses = referenceUses(fact, query);
- return uses.length > 0 && uses.every(m => EXAMPLE_LIST_LEAD.test(fact.slice(0, m.index)));
+ return uses.length > 0 && uses.every(at => EXAMPLE_LIST_LEAD.test(fact.slice(0, at)));
}
async function liveFactEntityPage(engine: BrainEngine, sourceId: string, slug: string, excludePrivate?: boolean): Promise<string | null> {
diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.ts
index e742a8c127..f539e20b3c 100644
--- a/src/core/remember-batch.ts
+++ b/src/core/remember-batch.ts
@@ -25,7 +25,9 @@ import { OperationError } from './ops/contract.ts';
import { clientRequestIdOf, parseWriteRequestId } from './persistence/preconditions.ts';
export const REMEMBER_BATCH_MAX = 20;
-const ITEM_KEYS = new Set(['fact', 'provenance', 'entity', 'infer_entity', 'kind', 'ttl', 'visibility', 'replaces']);
+const ITEM_KEYS = new Set(['fact', 'provenance', 'entity', 'infer_entity', 'kind', 'ttl', 'visibility', 'content_origin', 'valid_from', 'replaces']);
+/** #7432: every per-item field but the claim and `replaces` is also a top-level default (an item's own value wins); `source_id` is top-level only. */
+const SHARED_KEYS = [...ITEM_KEYS].filter(key => key !== 'fact' && key !== 'replaces').concat('source_id');
/** Deterministic UUID for child `index` of a batch request (stable across replays). */
export function childRequestId(requestId: string, index: number): string {
@@ -61,13 +63,12 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,
// #6280: an unusable request_id refuses the batch before any write (F6 accepts a UUID or a printable client id).
if (p.request_id !== undefined) parseWriteRequestId(p.request_id);
const shared: Record<string, unknown> = {};
- // #7432: a top-level entity is every item's default subject, like provenance; an item's own entity wins.
- for (const key of ['provenance', 'source_id', 'entity', 'kind', 'ttl', 'visibility', 'infer_entity']) if (p[key] !== undefined) shared[key] = p[key];
+ for (const key of SHARED_KEYS) if (p[key] !== undefined) shared[key] = p[key];
const normalized = items.map((raw, index) => {
// A bare string is the common shorthand for one fact.
if (typeof raw === 'string') return { ...shared, fact: raw };
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
- throw verbError('invalid_params', `items[${index}] must be an object.`, 'Each item is { "fact": "...", optional entity, kind, ttl, visibility, provenance }.');
+ throw verbError('invalid_params', `items[${index}] must be an object.`, 'Each item is { "fact": "...", optional entity, kind, ttl, visibility, provenance, content_origin, valid_from }.');
}
const extra = Object.keys(raw).filter(k => !ITEM_KEYS.has(k));
if (extra.length) throw verbError('invalid_params', `items[${index}] has unknown field(s): ${extra.join(', ')}.`, `Allowed item fields: ${[...ITEM_KEYS].join(', ')}.`);
diff --git a/test/facts-subject-infer-7405.test.ts b/test/facts-subject-infer-7405.test.ts
index 17b95e82c6..f1ab67b4dd 100644
--- a/test/facts-subject-infer-7405.test.ts
+++ b/test/facts-subject-infer-7405.test.ts
@@ -72,6 +72,9 @@ const CASES: Array<{ id: string; fact: string; expect: string | null }> = [
{ id: 'including-not-introducing', fact: 'Has notes including weekly sync items that belong to Alice Example', expect: ALICE },
{ id: 'example-literal', fact: 'Has research notes including concepts/automation-example', expect: null },
{ id: 'currency-without-amount', fact: 'CHF billed Alice Example CHF 80', expect: null },
+ { id: 'currency-after-date', fact: 'On 2025-01-01 CHF billed Alice Example', expect: null },
+ { id: 'currency-before-date', fact: 'Alice Example met CHF 2025-01-01', expect: null },
+ { id: 'amount-with-separators', fact: 'Alice Example paid CHF 1,250.50 for gardening', expect: ALICE },
{ id: 'label-mid-sentence', fact: 'Alice Example joined Work Example last year', expect: null },
{ id: 'subject-also-named-as-example', fact: 'concepts/automation-example lists 17 documents including concepts/automation-example notes', expect: 'concepts/automation-example' },
];
diff --git a/test/remember-batch-entity-7432.test.ts b/test/remember-batch-entity-7432.test.ts
index 6f81d4973d..e106d610b2 100644
--- a/test/remember-batch-entity-7432.test.ts
+++ b/test/remember-batch-entity-7432.test.ts
@@ -67,5 +67,25 @@ for (const backend of testBackends()) {
'SELECT fact, entity_slug FROM facts WHERE expired_at IS NULL ORDER BY id');
expect(rows.map(row => row.entity_slug)).toEqual([SHARED, SHARED, OWN]);
}, 120_000);
+
+ for (const remote of [false, true]) {
+ test(`content_origin and valid_from reach every item as they reach a single fact (remote=${remote})`, async () => {
+ const ctx = { engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default' } as unknown as OperationContext;
+ const fact = (text: string) => engine.executeRaw<{ trust_tier: string; valid_from: string }>(
+ 'SELECT trust_tier, valid_from::text AS valid_from FROM facts WHERE fact=$1 AND expired_at IS NULL', [text]);
+ await operationsByName.remember!.handler(ctx, { fact: `Single synthetic tool claim ${remote}.`, entity: SHARED, provenance: 'synthetic tool',
+ content_origin: 'tool_output', valid_from: '2026-03-01' });
+ const [single] = await fact(`Single synthetic tool claim ${remote}.`);
+ expect(single!.trust_tier).toBe('external_untrusted');
+ const out = await operationsByName.remember!.handler(ctx, { entity: SHARED, provenance: 'synthetic tool', content_origin: 'tool_output', valid_from: '2026-03-01',
+ items: [`Batched synthetic tool claim ${remote}.`, { fact: `Per-item synthetic tool claim ${remote}.`, content_origin: 'tool_output', valid_from: '2026-03-02', entity: OWN }] }) as { failed: number };
+ expect(out.failed).toBe(0);
+ const [batched] = await fact(`Batched synthetic tool claim ${remote}.`);
+ const [perItem] = await fact(`Per-item synthetic tool claim ${remote}.`);
+ expect(batched).toEqual(single);
+ expect(perItem!.trust_tier).toBe('external_untrusted');
+ expect(perItem!.valid_from.startsWith('2026-03-02')).toBe(true);
+ }, 120_000);
+ }
});
}