Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: extract-conversation-facts parses plain user:/assistant: transcripts and exits 0 on partial success with a failed-page summary; remember takes valid_from and fact date headers use the source page observation date (write time never shown as valid-from); query page lanes size hits to the budget. docs: preregister the query facts arm gates

garrytan020fae9245b6
diff --git a/docs/eval/decisions/query-facts-arm/README.md b/docs/eval/decisions/query-facts-arm/README.md
new file mode 100644
index 0000000000..9991861669
--- /dev/null
+++ b/docs/eval/decisions/query-facts-arm/README.md
@@ -0,0 +1,62 @@
+# Facts arm in query: preregistered gates
+
+Not built and not measured. The gates below were written and pushed before any code or gated run. The arm will
+sit behind `search.query_facts_arm`, which is off by default. With the key off, `query` returns what it returns
+today.
+
+## Why
+
+A correction made through `remember` does not win in `query`. In the B2 corrections suite's forget-then-remember
+arm (gbrain-evals `eval/workload-suites`, `bun run eval:corrections`), 0 of 100 answers were correct and about
+90 repeated the stale value. Two things cause this:
+
+- The remembered fact does not surface when the question is worded differently from the fact.
+- The page text that still states the old value ranks first.
+
+`query` reads pages and chunks only. Facts are reachable through `recall`, but `query` never ranks them.
+
+## The change
+
+With the key on, `query` adds a facts arm:
+
+- **Candidates.** Active facts only: not expired, not superseded, and valid now. They are filtered by the
+ caller's read policy, the same way `recall` filters them: source scope, private facts withheld from remote
+ callers, and the takes holder allow-list.
+- **Matching.** Facts are matched to the query by embedding similarity and keyword, then ordered newest
+ `valid_from` first among matches.
+- **Delivery.** Matched facts are added as fact rows inside the caller's token budget and row count. Facts never
+ enlarge either.
+- **Superseded page claims.** A page row is stamped `superseded_claim` when a newer active fact covers the same
+ entity and slot. Slot here means the typed claim columns: `claim_metric`, plus `claim_period` when both rows
+ carry it. Pages without typed claims are never stamped.
+- **No model call** is added on the read path.
+
+The touch points will be additive in the `query` op, as with entity anchoring. `hybridSearch` ranking is left
+alone.
+
+## Gates
+
+1. **B2 corrections** (gbrain-evals `eval/workload-suites`, `bun run eval:corrections`).
+ - Setup: the forget-then-remember arm, run at the measured build with `search.query_facts_arm` on and off.
+ Same seed (`corrections-v1`, seed 20261006, 100 items), same reader and same retrieval budget as the B2
+ preregistration.
+ - Metrics: corrected-value accuracy and stale-answer rate after 1 and after 5 unrelated writes.
+ - **Rule:** the key-on arm wins gate 1 if its corrected-value accuracy is higher at both checkpoints and its
+ stale-answer rate is not higher at either.
+ - In the same run, the edit-sync and append arms must not lose more than 2 points of corrected-value accuracy
+ with the key on.
+2. **No regression on the evals that cover `query`.** These are the corpora used for entity anchoring
+ (`evals/entity-anchoring/regression.ts`): NamedThingBench, the relational retrieval-quality fixture and the
+ LongMemEval nightly fixture, run through the `query` op with the key on and off.
+ - Recall@10 is computed over page rows only.
+ - **Rule:** no question's recall@10 is lower with the key on.
+ - Each corpus reports how often the facts arm added a row.
+3. **Harness lane (optional, recommended).** LongMemEval knowledge-update and PersonaMem dev slices, retrieving
+ through the `query` op with the key on and off.
+
+**Decision.** The key becomes default-on only if gates 1 and 2 pass, and gate 3 too if it runs. Until then it
+stays off. The spend cap is set before the gate 1 run.
+
+## Changelog
+
+- 2026-10-05: gates preregistered before any code or gated run.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index 5c923bd24b..e8085cf50a 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -63,6 +63,11 @@ gbrain recall --query "renewal terms" --return-unit section --budget-tokens 4000
Use `page` for multi-session / temporal questions where the answer depends on
the whole conversation. Use `window` when you only need local context.
+With `return_unit: page`, `query` sizes its hit list to the budget so the
+budget fills. Autocut stays off unless you set `autocut`, and a budget above
+about 6,250 tokens raises the row count to one row per 250 tokens, up to 100.
+An explicit `limit` or `autocut` still wins.
+
## Parameters and config
Per-call params on `search`, `query`, `recall`:
@@ -112,8 +117,15 @@ renders as written, any other instant in `brain.timezone`. The header line
and its newline are part of `chunk_text`: they count in `delivered.tokens`,
`tokens_delivered` and the budget, `match_spans` offsets include them, and
`evidenceFingerprint` hashes them. `recall` facts gain
-`date_header: "[observed unknown; valid 2026-03-01 to unknown]"` (facts carry
-no observation date; an open validity end reads `unknown`). The setting
+`date_header: "[observed 2026-02-10; valid 2026-03-01 to unknown]"`. A fact's
+`observed` date is the observation date of the page it came from
+(`source_markdown_slug`, such as the conversation it was extracted from), and it
+reads `unknown` for a fact kept only in its entity page's facts fence. `valid`
+starts at the fact's `valid_from`: `remember` sets it from its `valid_from`
+parameter (when the fact was said or became true). A `valid_from` that only
+records the write time (within a minute of `created_at`) reads `unknown`, so a
+header never presents when a fact was written as when it became true. An open
+validity end reads `unknown`. The setting
applies to `search`, `query`, `recall`, `think` and `assemble_evidence`.
Config keys: `search.return_unit`, `search.return_window`,
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 368c498cab..32baef7f84 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -235,7 +235,7 @@ matched. **create_safety** (enum): `exists` (a page for this already exists)
signal). The derivation of both is implementation-defined and may improve;
the values are frozen.
-### remember(fact, provenance, ttl?, entity?, kind?, visibility?, request_id?) — write
+### remember(fact, provenance, ttl?, entity?, kind?, visibility?, valid_from?, request_id?) — write
Save ONE fact with mandatory attribution.
@@ -244,6 +244,10 @@ Save ONE fact with mandatory attribution.
Empty ⇒ `provenance_required` error with a fix.
- `entity`: set whenever the fact is about a specific person/company/project —
entity-scoped recall will not find unattributed facts.
+- `valid_from` (additive, ISO 8601 date or time): when the fact was said or
+ became true, such as the date of the conversation it comes from. Omitted, the
+ fact is recorded with the write time, and date headers read its start of
+ validity as `unknown`. Not ISO 8601 ⇒ `invalid_params`.
- `infer_entity` (additive, boolean, default `true`): when `entity` is omitted,
the server may link the fact to the one entity page its text names exactly
(zero LLM; a second competing name, a bare first name or an ambiguous match
diff --git a/llms-full.txt b/llms-full.txt
index 3017f901ce..37aba8a2a3 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9008,7 +9008,7 @@ matched. **create_safety** (enum): `exists` (a page for this already exists)
signal). The derivation of both is implementation-defined and may improve;
the values are frozen.
-### remember(fact, provenance, ttl?, entity?, kind?, visibility?, request_id?) — write
+### remember(fact, provenance, ttl?, entity?, kind?, visibility?, valid_from?, request_id?) — write
Save ONE fact with mandatory attribution.
@@ -9017,6 +9017,10 @@ Save ONE fact with mandatory attribution.
Empty ⇒ `provenance_required` error with a fix.
- `entity`: set whenever the fact is about a specific person/company/project —
entity-scoped recall will not find unattributed facts.
+- `valid_from` (additive, ISO 8601 date or time): when the fact was said or
+ became true, such as the date of the conversation it comes from. Omitted, the
+ fact is recorded with the write time, and date headers read its start of
+ validity as `unknown`. Not ISO 8601 ⇒ `invalid_params`.
- `infer_entity` (additive, boolean, default `true`): when `entity` is omitted,
the server may link the fact to the one entity page its text names exactly
(zero LLM; a second competing name, a bare first name or an ambiguous match
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 0ca447aed7..334043d9e0 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli.ts 3212 ratchet +3 agent operator gate fixes: repair-failed connect wrap
src/commands/autopilot.ts 1642 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)
src/commands/doctor.ts 667 ratchet +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
src/commands/embed.ts 2219 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)
-src/commands/extract-conversation-facts.ts 2182 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)
+src/commands/extract-conversation-facts.ts 2186 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); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts
src/commands/extract.ts 2541 ratchet 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)
src/commands/jobs.ts 662 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
src/commands/serve-http.ts 926 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)
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 727900d5bb..651f683066 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -64,6 +64,7 @@
* `--override-disabled` to force-run.
*/
+import { extractExitCode, extractRunStatus, recordFailedPage, reportFailedPage } from '../core/facts/conversation-run-status.ts';
import type { BrainEngine, NewFact } from '../core/engine.ts';
import type { Page } from '../core/types.ts';
import {
@@ -301,6 +302,8 @@ export interface ExtractConversationFactsCoreOpts {
extractor?: (input: ExtractInput) => Promise<ExtractedFact[]>;
}
+export { extractExitCode, extractRunStatus };
+
export interface ExtractConversationFactsResult {
pages_considered: number;
pages_processed: number;
@@ -324,6 +327,8 @@ export interface ExtractConversationFactsResult {
pages_skipped_unrecognized_speaker: number;
/** Pages whose claim reached extraction but failed before durable outcome. */
pages_failed: number;
+ /** The failed pages (first 50) with the error each one hit; they stay unfinished and retry next run. */
+ failed_pages: Array<{ slug: string; error: string }>;
/**
* Pages whose built-in parse returned `no_match` and whose messages were
* recovered by the explicitly enabled LLM fallback.
@@ -1218,8 +1223,8 @@ async function processPage(
`[extract-conversation-facts] ${page.slug} changed during extraction; leaving it unfinished for replay\n`,
);
// #4869: no terminal, no checkpoint — this claim did not reach a durable
- // outcome, so it counts as failed (CLI exit 1 / cycle 'warn'), not processed.
- state.result.pages_failed++;
+ // outcome, so it counts as failed (cycle 'warn'), not processed.
+ state.result.pages_failed++; recordFailedPage(state.result, page.slug, 'the page changed during extraction; left unfinished for replay');
return { newEndIso: null };
}
@@ -1325,6 +1330,7 @@ export async function runExtractConversationFactsCore(
pages_marked_non_extractable: 0,
pages_skipped_unrecognized_speaker: 0,
pages_failed: 0,
+ failed_pages: [],
pages_llm_fallback: 0,
pages_lock_skipped: 0,
orphan_facts_cleaned: 0,
@@ -1582,9 +1588,7 @@ export async function runExtractConversationFactsCore(
const message = failure.error instanceof Error
? failure.error.message
: String(failure.error);
- process.stderr.write(
- `[extract-conversation-facts] ${failure.label} failed: ${message}\n`,
- );
+ reportFailedPage(result, failure.label, message);
}
processedPagesCount += claimable.length;
@@ -1893,6 +1897,11 @@ Options:
--yes Auto-confirm cost preview in non-TTY contexts.
--help, -h Show this help.
+Exit status: 0 when the run finished, including a partial run where some pages
+failed (they are listed, stay unfinished and retry on the next run; --json
+reports status "partial" with failed_pages). 1 when every attempted page failed,
+a model has no pricing, or the gateway is unavailable.
+
Multi-source: when --source-id is omitted, the command iterates ALL
sources from gbrain sources list. Per-source budget cap defaults to
--max-cost-usd; the brain-wide cap when running via the autopilot cycle
@@ -1980,6 +1989,7 @@ export async function runExtractConversationFacts(
pages_marked_non_extractable: 0,
pages_skipped_unrecognized_speaker: 0,
pages_failed: 0,
+ failed_pages: [],
pages_llm_fallback: 0,
pages_lock_skipped: 0,
orphan_facts_cleaned: 0,
@@ -2034,6 +2044,7 @@ export async function runExtractConversationFacts(
aggregate.pages_marked_non_extractable += perSource.pages_marked_non_extractable;
aggregate.pages_skipped_unrecognized_speaker += perSource.pages_skipped_unrecognized_speaker;
aggregate.pages_failed += perSource.pages_failed;
+ for (const failed of perSource.failed_pages) recordFailedPage(aggregate, failed.slug, failed.error);
aggregate.pages_llm_fallback += perSource.pages_llm_fallback;
aggregate.pages_lock_skipped += perSource.pages_lock_skipped;
aggregate.orphan_facts_cleaned += perSource.orphan_facts_cleaned;
@@ -2059,9 +2070,12 @@ export async function runExtractConversationFacts(
// #5448: --json is a universal cli-flag-registry flag, so scripts add it
// expecting an envelope. Emit the same counters as the Done: summary as one
// JSON object on stdout; progress and diagnostics stay on stderr.
+ const runStatus = extractRunStatus(aggregate);
if (parsed.json) {
console.log(JSON.stringify({
...aggregate,
+ status: runStatus,
+ ...(aggregate.pages_failed > 0 ? { next: { action: 'rerun', why: 'Failed pages stay unfinished and are retried by re-running the same command; pages that succeeded are not redone.' } } : {}),
sources: sourceIds,
dry_run: parsed.dryRun ?? false,
outcome,
@@ -2100,7 +2114,8 @@ export async function runExtractConversationFacts(
console.log(` Marked ${aggregate.pages_marked_non_extractable} page(s) as scanned, not extractable.`);
}
if (aggregate.pages_failed > 0) {
- console.error(` Failed ${aggregate.pages_failed} page(s); they remain unfinished and will retry.`);
+ console.error(` Failed ${aggregate.pages_failed} page(s); they remain unfinished and will retry. Re-run the same command to retry them:`);
+ for (const failed of aggregate.failed_pages) console.error(` ${failed.slug}: ${failed.error}`);
}
if (aggregate.pages_llm_fallback > 0) {
console.log(` Parsed ${aggregate.pages_llm_fallback} page(s) with the opt-in LLM fallback.`);
@@ -2131,7 +2146,11 @@ export async function runExtractConversationFacts(
// anyBudgetExhausted doesn't trigger exit 3; the budget message
// above already tells the user what to do, and exit 0 is the right
// signal for "ran to the cap intentionally."
- if (aggregate.pages_failed > 0 || unpricedModels.size > 0) {
+ // Partial success (some pages extracted, some failed) exits 0: the failed
+ // pages are listed above / in the JSON envelope and retry on the next run.
+ // Nonzero is reserved for a run where every attempted page failed, or for
+ // missing model pricing (a configuration problem a re-run cannot fix).
+ if (extractExitCode(aggregate, unpricedModels.size) !== 0) {
process.exit(1);
}
if (aggregate.pages_lock_skipped > 0 && !anyBudgetExhausted) {
@@ -2144,6 +2163,7 @@ export async function runExtractConversationFacts(
// Helpers.
// ---------------------------------------------------------------------------
+
function pickLaterIso(
a: string | null | undefined,
b: string | null | undefined,
diff --git a/src/core/conversation-parser/builtins.ts b/src/core/conversation-parser/builtins.ts
index 32862b390f..3281c7cbdf 100644
--- a/src/core/conversation-parser/builtins.ts
+++ b/src/core/conversation-parser/builtins.ts
@@ -448,6 +448,50 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [
'ChatGPT web export → Markdown conversion: `**You:**` / `**ChatGPT:**` turn labels with multi-paragraph bodies separated by blank lines',
},
+ {
+ // Agent and harness transcripts: plain role-prefixed lines
+ // (`user: ...` / `assistant: ...`), the form chat logs and memory
+ // harnesses write. NARROW BY CONSTRUCTION like chatgpt-export: the
+ // speaker is a closed role enumeration, so prose labels (`Note:`,
+ // `Owner:`) never anchor. multi_line + continuation scoring absorbs
+ // multi-paragraph replies, and the two-speaker and preamble guards keep
+ // one illustrative pair inside an article from reading as a transcript.
+ id: 'plain-role-no-time',
+ origin: 'builtin',
+ // Matches: user: text / Assistant: text / human: text / AI: text / system: text
+ regex: /^(user|assistant|human|ai|system)\s*:\s*(.*)$/i,
+ captures: {
+ speaker_group: 1,
+ text_group: 2,
+ },
+ date_source: 'frontmatter',
+ time_format: '24h',
+ timezone_policy: 'utc_assumed_with_warn',
+ multi_line: true,
+ score_continuations_as_body: true,
+ score_continuations_min_distinct_speakers: 2,
+ score_continuations_max_preamble_lines: 5,
+ score_full_body: true,
+ quick_reject: /^(?:user|assistant|human|ai|system)\s*:/i,
+ test_positive: [
+ 'user: I moved to Lisbon last month.',
+ 'assistant: Congratulations on the move.',
+ 'User: thanks',
+ 'Human: what changed?',
+ 'AI: the office moved.',
+ ],
+ test_negative: [
+ '**User:** bold shape belongs to bold-name-no-time',
+ 'Username: alice',
+ 'Users: plural label',
+ 'Note: a prose label',
+ 'Speaker A: phone-call shape',
+ 'the user: inline mention',
+ ],
+ source_doc:
+ 'Agent / harness transcript shape: plain `user:` / `assistant:` role prefixes with multi-line bodies',
+ },
+
{
// Modern meeting-transcription tools (Circleback, Granola, Zoom)
// emit `**Speaker Name:** message text` with NO per-line
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 98fe57acfe..aa679f3739 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -236,6 +236,7 @@ export async function runPhaseConversationFactsBackfill(
pages_marked_non_extractable: 0,
pages_skipped_unrecognized_speaker: 0,
pages_failed: 0,
+ failed_pages: [],
pages_llm_fallback: 0,
// v0.41.15.0 (D6 + D11): new counters from the per-page lock
// + delete-orphans-first replay safety.
diff --git a/src/core/facts/conversation-run-status.ts b/src/core/facts/conversation-run-status.ts
new file mode 100644
index 0000000000..a8a6756332
--- /dev/null
+++ b/src/core/facts/conversation-run-status.ts
@@ -0,0 +1,31 @@
+/**
+ * Run status and exit semantics for `gbrain extract-conversation-facts`:
+ * a partial run (some pages extracted, some failed) is a success that lists
+ * its failed pages; only a run where every attempted page failed, or a model
+ * without pricing, exits nonzero.
+ */
+interface RunCounts { pages_failed: number; pages_processed: number }
+interface FailedPages { failed_pages: Array<{ slug: string; error: string }> }
+
+const FAILED_PAGES_LISTED = 50;
+
+/** ok: nothing failed; partial: some pages extracted and some failed; failed: every attempted page failed. */
+export function extractRunStatus(r: RunCounts): 'ok' | 'partial' | 'failed' {
+ return r.pages_failed === 0 ? 'ok' : r.pages_processed > 0 ? 'partial' : 'failed';
+}
+
+/** CLI exit status: 0 for ok and partial runs; 1 when every attempted page failed or a model has no pricing. */
+export function extractExitCode(r: RunCounts, unpricedModels: number): 0 | 1 {
+ return extractRunStatus(r) === 'failed' || unpricedModels > 0 ? 1 : 0;
+}
+
+/** Keep the first 50 failed pages with their error for the summary and the JSON envelope. */
+export function recordFailedPage(result: FailedPages, slug: string, error: string): void {
+ if (result.failed_pages.length < FAILED_PAGES_LISTED) result.failed_pages.push({ slug, error: error.slice(0, 300) });
+}
+
+/** A failed page as it happens: one stderr line, plus its entry in the summary. */
+export function reportFailedPage(result: FailedPages, slug: string, error: string): void {
+ process.stderr.write(`[extract-conversation-facts] ${slug} failed: ${error}\n`);
+ recordFailedPage(result, slug, error);
+}
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 8889fa0ad8..c8836bee86 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -30,7 +30,7 @@ import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { projectRows, resultRowsFor } from '../search/lean-rows.ts';
-import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
+import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, pagePlanHits, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
@@ -837,7 +837,7 @@ const query: Operation = {
// `(p.limit as number) || undefined` keeps 0 in that same "unset"
// bucket rather than requesting a literal empty result — see the
// `limit` param description above for why.
- limit: (p.limit as number) || undefined,
+ limit: (p.limit as number) || pagePlanHits(plan).limit,
offset: (p.offset as number) || 0,
excludePrivate,
requireSafeChunks: ctx.remote !== false, decide: { remote: ctx.remote !== false, answerability: true },
@@ -878,7 +878,7 @@ const query: Operation = {
adaptiveReturn: typeof p.adaptive_return === 'boolean' ? (p.adaptive_return as boolean) : undefined,
// v0.42.3.0 — autocut ceiling override. Omitted = smart default (ON in
// reranked modes). `false` forces the full top-K.
- autocut: typeof p.autocut === 'boolean' ? (p.autocut as boolean) : undefined,
+ autocut: typeof p.autocut === 'boolean' ? (p.autocut as boolean) : pagePlanHits(plan).autocut,
// v0.43 — relational recall override. Omitted = smart default (mode bundle).
relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
});
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 1a36dd4480..ce7daed1f4 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -162,7 +162,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null);
const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,
slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,
- intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,
+ intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: typeof p.valid_from === 'string' ? new Date(p.valid_from).toISOString() : new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,
...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}) },
authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs));
diff --git a/src/core/search/evidence-date.ts b/src/core/search/evidence-date.ts
index 9c9ece9dd1..b08933bbef 100644
--- a/src/core/search/evidence-date.ts
+++ b/src/core/search/evidence-date.ts
@@ -70,13 +70,26 @@ export function pageDateHeader(observed: string | null): string {
return `[observed ${observed ?? UNKNOWN_DATE}]`;
}
+/** A valid_from within this of created_at is the write-time default, not a known start of validity. */
+const WRITE_TIME_DEFAULT_MS = 60_000;
+
+/**
+ * `observed` is when the fact was said: the observation date of the page it
+ * came from, when the caller supplies it. `valid FROM` is the fact's
+ * valid_from, except a valid_from that only records the write time (the
+ * default when `remember` gets no date) renders `unknown`: the header never
+ * presents when a fact was written as when it became true.
+ */
export function factDateHeader(
- fact: { valid_from?: Date | string | null; valid_until?: Date | string | null },
+ fact: { valid_from?: Date | string | null; valid_until?: Date | string | null; created_at?: Date | string | null },
timeZone?: string | null,
+ observed?: string | null,
): string {
- const from = formatBrainDay(fact.valid_from, timeZone) ?? UNKNOWN_DATE;
+ const writeTimeDefault = fact.valid_from && fact.created_at
+ && Math.abs(new Date(fact.valid_from).getTime() - new Date(fact.created_at).getTime()) < WRITE_TIME_DEFAULT_MS;
+ const from = (writeTimeDefault ? null : formatBrainDay(fact.valid_from, timeZone)) ?? UNKNOWN_DATE;
const until = formatBrainDay(fact.valid_until, timeZone) ?? UNKNOWN_DATE;
- return `[observed ${UNKNOWN_DATE}; valid ${from} to ${until}]`;
+ return `[observed ${observed ?? UNKNOWN_DATE}; valid ${from} to ${until}]`;
}
/**
@@ -103,13 +116,48 @@ export async function loadPageDateHeaders(
}
/** `recall` fact rows plus `date_header` when `search.evidence_date_header` is on; unchanged otherwise. */
-export async function withFactDateHeaders<T extends { valid_from: string | null; valid_until: string | null }>(
- engine: { getConfig(key: string): Promise<string | null> },
+export async function withFactDateHeaders<T extends { id: number; valid_from: string | null; valid_until: string | null; created_at?: string | null; entity_slug?: string | null; source_id?: string }>(
+ engine: { getConfig(key: string): Promise<string | null>; executeRaw<R>(sql: string, params?: unknown[]): Promise<R[]> },
facts: T[],
): Promise<Array<T & { date_header?: string }>> {
if (!await evidenceDateHeaderEnabled(engine)) return facts;
const timeZone = (await engine.getConfig('brain.timezone').catch(() => null))?.trim() || null;
- return facts.map(f => ({ ...f, date_header: factDateHeader(f, timeZone) }));
+ const observed = await factObservationDates(engine, facts, timeZone).catch(() => new Map<number, string>());
+ return facts.map(f => ({ ...f, date_header: factDateHeader(f, timeZone, observed.get(f.id)) }));
+}
+
+/**
+ * When each fact was said: the observation date of the page the fact came
+ * from (`facts.source_markdown_slug`, e.g. the conversation it was extracted
+ * from). A fact stored in its own entity page's facts fence has no such page,
+ * so it stays unknown. One facts read and one pages read per call.
+ */
+async function factObservationDates(
+ engine: { executeRaw<R>(sql: string, params?: unknown[]): Promise<R[]> },
+ facts: Array<{ id: number; entity_slug?: string | null }>,
+ timeZone: string | null,
+): Promise<Map<number, string>> {
+ const out = new Map<number, string>();
+ const ids = facts.map(f => f.id).filter(id => Number.isInteger(id) && id > 0);
+ if (!ids.length) return out;
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string | null; entity_slug: string | null }>(
+ 'SELECT id, source_id, source_markdown_slug AS slug, entity_slug FROM facts WHERE id = ANY($1::bigint[])', [ids]);
+ const wanted = rows.filter(r => r.slug && r.slug !== r.entity_slug);
+ if (!wanted.length) return out;
+ const pages = await engine.executeRaw<{ source_id: string; slug: string; frontmatter: unknown; import_filename: string | null }>(
+ `SELECT p.source_id, p.slug, p.frontmatter, p.import_filename FROM pages p
+ JOIN unnest($1::text[], $2::text[]) AS w(source_id, slug) ON p.source_id = w.source_id AND p.slug = w.slug WHERE p.deleted_at IS NULL`,
+ [wanted.map(r => r.source_id), wanted.map(r => r.slug!)]);
+ const byKey = new Map(pages.map(p => {
+ const fm = typeof p.frontmatter === 'string' ? JSON.parse(p.frontmatter) : p.frontmatter;
+ const day = formatBrainDay(pageObservationDate({ slug: p.slug, frontmatter: fm && typeof fm === 'object' ? fm as Record<string, unknown> : null, filename: p.import_filename, timeZone }), timeZone);
+ return [`${p.source_id}\u0000${p.slug}`, day] as const;
+ }));
+ for (const r of wanted) {
+ const day = byKey.get(`${r.source_id}\u0000${r.slug}`);
+ if (day) out.set(Number(r.id), day);
+ }
+ return out;
}
/** `search.evidence_date_header` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index 9926e79dc9..d0c8295060 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -267,6 +267,19 @@ export function conversationSignal(hit: { type?: string | null; slug: string }):
* conversations stay byte-identical. An explicit `auto` always runs and
* reports its per-result decision.
*/
+/**
+ * A page-unit plan fills a token budget, so its hits are not cut for
+ * precision first: autocut stays off unless the caller asks for it, and a
+ * budget larger than the default row count can fill raises the row count (one
+ * row per ~250 tokens, at most 100). Otherwise the page lane stopped at the
+ * default rows (often ~10 after autocut) with half its budget unused.
+ */
+export function pagePlanHits(plan: EvidencePlan | null): { limit?: number; autocut?: false } {
+ if (!plan || plan.unit !== 'page' || !(plan.budgetTokens > 0)) return {};
+ const rows = Math.min(100, Math.ceil(plan.budgetTokens / 250));
+ return { autocut: false, ...(rows > 25 ? { limit: rows } : {}) };
+}
+
export function effectivePlan(plan: EvidencePlan | null, hits: SearchResult[]): EvidencePlan | null {
if (!plan || plan.unit !== 'auto' || plan.explicitUnit) return plan;
return hits.some(h => conversationSignal(h) !== null) ? plan : null;
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 1f419ff13e..ca110fc4b6 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -75,6 +75,10 @@ const remember: Operation = {
type: 'string',
description: '"30d", "12h" or ISO 8601 time; omit = never.',
},
+ valid_from: {
+ type: 'string',
+ description: 'ISO 8601 date or time the fact was said or became true (e.g. the conversation date); omit = unknown, recorded as now.',
+ },
entity: {
type: 'string',
description: 'Who or what it is about (name or slug).',
@@ -138,6 +142,13 @@ const remember: Operation = {
'Use "world" (default — agents can recall it) or "private" (local CLI reads only).',
);
}
+ if (p.valid_from !== undefined && (typeof p.valid_from !== 'string' || !Number.isFinite(Date.parse(p.valid_from)))) {
+ throw verbError(
+ 'invalid_params',
+ 'valid_from must be an ISO 8601 date or time.',
+ 'Pass when the fact was said or became true, e.g. valid_from: "2026-03-01", or omit it.',
+ );
+ }
if (ctx.dryRun) {
parseTtlParam(p.ttl); // Dry runs still validate without admitting intent.
return {
diff --git a/test/evidence-date-header.test.ts b/test/evidence-date-header.test.ts
index 93f60148fd..0b31ade5ed 100644
--- a/test/evidence-date-header.test.ts
+++ b/test/evidence-date-header.test.ts
@@ -25,6 +25,9 @@ describe('header grammar and dates', () => {
expect(factDateHeader({ valid_from: new Date('2026-03-01T00:00:00Z'), valid_until: null })).toBe('[observed unknown; valid 2026-03-01 to unknown]');
expect(factDateHeader({ valid_from: null, valid_until: '2026-04-01T00:00:00.000Z' })).toBe('[observed unknown; valid unknown to 2026-04-01]');
for (const h of [pageDateHeader(null), factDateHeader({})]) expect(h).not.toContain('\n');
+ // A valid_from that only records the write time is not a known start of validity.
+ expect(factDateHeader({ valid_from: '2026-10-05T12:00:00.000Z', valid_until: null, created_at: '2026-10-05T12:00:00.400Z' })).toBe('[observed unknown; valid unknown to unknown]');
+ expect(factDateHeader({ valid_from: '2026-03-01T00:00:00.000Z', valid_until: null, created_at: '2026-10-05T12:00:00.000Z' }, null, '2026-02-10')).toBe('[observed 2026-02-10; valid 2026-03-01 to unknown]');
});
test('formatBrainDay: midnight UTC renders as written, other instants in brain.timezone', () => {
@@ -154,6 +157,39 @@ describe('ops on PGLite', () => {
}
});
+ test('on: a fact from a dated source page is observed on that date; a fact written without a date does not show the write time as valid-from', async () => {
+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');
+ try {
+ const fromChat = await engine.insertFact({ fact: 'Walrus moved its launch to April', kind: 'fact', entity_slug: 'notes/walrus-undated', source: 'test', visibility: 'world',
+ valid_from: new Date('2026-02-10T00:00:00Z') }, { source_id: 'default' });
+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $2 WHERE id = $1', [fromChat.id, 'chat/2026-02-10-walrus']);
+ const undated = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;
+ expect(undated.facts.find((f: any) => f.fact.includes('April')).date_header).toBe('[observed 2026-02-10; valid 2026-02-10 to unknown]');
+ const written = await engine.insertFact({ fact: 'Walrus hired a new lead', kind: 'fact', entity_slug: 'notes/walrus-undated', source: 'test', visibility: 'world' }, { source_id: 'default' });
+ const again = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;
+ expect(again.facts.find((f: any) => f.id === written.id).date_header).toBe('[observed unknown; valid unknown to unknown]');
+ } finally {
+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);
+ }
+ });
+
+ test('remember with valid_from stores it, and the header shows it as the start of validity', async () => {
+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');
+ try {
+ await op('remember').handler(ctxOf(), { fact: 'Walrus opened a Porto office', provenance: 'chat on 2026-03-01', entity: 'notes/walrus-undated', valid_from: '2026-03-01' });
+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;
+ const row = recall.facts.find((f: any) => f.fact.includes('Porto'));
+ expect(row.valid_from.slice(0, 10)).toBe('2026-03-01');
+ expect(row.date_header).toBe('[observed unknown; valid 2026-03-01 to unknown]');
+ } finally {
+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);
+ }
+ });
+
+ test('remember rejects a valid_from that is not an ISO 8601 date', async () => {
+ await expect(op('remember').handler(ctxOf(), { fact: 'Walrus is in Lisbon', provenance: 'test', valid_from: 'last spring' })).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+
test('remote clamp: 32k by default and reported; a trusted eval brain raises it with search.return_budget_max_remote', async () => {
await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });
expect(lastMeta!.delivery.budget_clamped).toEqual({ requested: 90000, max: 32000 });
diff --git a/test/extract-conversation-facts-plain-role.test.ts b/test/extract-conversation-facts-plain-role.test.ts
new file mode 100644
index 0000000000..a5c1413e4e
--- /dev/null
+++ b/test/extract-conversation-facts-plain-role.test.ts
@@ -0,0 +1,83 @@
+/**
+ * Conversation-facts extraction over plain role-prefixed transcripts
+ * (`user: ...` / `assistant: ...`, the form agents and harnesses write) and
+ * the bold form (`**User:** ...`), plus partial-success accounting: a run
+ * where some pages fail lists them and exits 0; only a run where every
+ * attempted page failed exits nonzero. Injected extractor; no network.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { parseConversation } from '../src/core/conversation-parser/parse.ts';
+import { extractExitCode, extractRunStatus, runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import type { ExtractedFact } from '../src/core/facts/extract.ts';
+
+const PLAIN = [
+ 'user: I moved to Lisbon last month for the new job.',
+ 'assistant: Congratulations! How is the new job going?',
+ 'user: Great, I lead the platform team now.',
+ 'Most days I start at eight.',
+ 'assistant: That sounds like a big step.',
+].join('\n');
+const BOLD = PLAIN.replace(/^(user|assistant):/gm, (_, role: string) => `**${role[0]!.toUpperCase()}${role.slice(1)}:**`);
+const fact = (text: string): ExtractedFact => ({ fact: text, kind: 'fact', entity_slug: null, source: 'test', source_session: null, confidence: 1, notability: 'medium' });
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+});
+
+const seed = (slug: string, body: string) => engine.putPage(slug, { type: 'conversation', title: slug, compiled_truth: body, timeline: '', frontmatter: { date: '2026-03-01' } });
+
+describe('plain role-prefixed transcripts', () => {
+ test('parse with both roles and multi-line bodies; the bold form still parses', () => {
+ const plain = parseConversation(PLAIN, { page: { slug: 'chat/plain', frontmatter: { date: '2026-03-01' }, compiled_truth: PLAIN } as never });
+ expect(plain.matched_pattern_id).toBe('plain-role-no-time');
+ expect(plain.messages.map(m => m.speaker)).toEqual(['user', 'assistant', 'user', 'assistant']);
+ expect(plain.messages[2]!.text).toContain('Most days I start at eight.');
+ const bold = parseConversation(BOLD, { page: { slug: 'chat/bold', frontmatter: { date: '2026-03-01' }, compiled_truth: BOLD } as never });
+ expect(bold.messages).toHaveLength(4);
+ });
+
+ test('an article with one illustrative pair deep inside is not a transcript', () => {
+ // Past the five-line preamble guard the pair gets no continuation immunity, so plain density (2 of 62 lines) is under the 5% floor.
+ const article = [...Array.from({ length: 60 }, (_, i) => `Paragraph ${i} about how chat assistants work in practice.`), 'user: hello', 'assistant: hi'].join('\n');
+ const r = parseConversation(article, { page: { slug: 'notes/article', frontmatter: {}, compiled_truth: article } as never });
+ expect(r.matched_pattern_id).not.toBe('plain-role-no-time');
+ });
+
+ test('extract-conversation-facts extracts from plain and bold transcripts alike', async () => {
+ await seed('sessions/plain', PLAIN);
+ await seed('sessions/bold', BOLD);
+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', types: ['conversation'], sleepMs: 0, extractor: async () => [fact('The user lives in Lisbon')] });
+ expect(result.pages_skipped_unparsed).toBe(0);
+ expect(result.pages_processed).toBe(2);
+ expect(result.facts_inserted).toBeGreaterThanOrEqual(2);
+ });
+});
+
+describe('partial success', () => {
+ test('a run with some failed pages lists them and exits 0; a run where every page failed exits 1', async () => {
+ await seed('sessions/ok', PLAIN);
+ await seed('sessions/broken', BOLD.replace('Lisbon', 'Porto'));
+ const result = await runExtractConversationFactsCore(engine, {
+ sourceId: 'default', types: ['conversation'], sleepMs: 0,
+ extractor: async (input) => { if (input.turnText.includes('Porto')) throw new Error('synthetic provider outage'); return [fact('The user lives in Lisbon')]; },
+ });
+ expect(result).toMatchObject({ pages_processed: 1, pages_failed: 1 });
+ expect(result.failed_pages).toEqual([{ slug: 'sessions/broken', error: expect.stringContaining('synthetic provider outage') }]);
+ expect(extractRunStatus(result)).toBe('partial');
+ expect(extractExitCode(result, 0)).toBe(0);
+ expect(extractExitCode({ pages_processed: 0, pages_failed: 2 }, 0)).toBe(1);
+ expect(extractExitCode({ pages_processed: 3, pages_failed: 0 }, 1)).toBe(1);
+ expect(extractRunStatus({ pages_processed: 3, pages_failed: 0 })).toBe('ok');
+ });
+});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 934f75850b..1a0656b291 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 208390,
- "stdoutSha256": "a6ca01d48a4d10f68e29a441b5771fee06e1aa415b343f8b95ecd4baf24ada15",
+ "stdoutBytes": 208629,
+ "stdoutSha256": "c6830adde6b192f5d86b0f7fcff33714af4725d9d8dc33e52f3a65d8a043f677",
"toolNames": [
"remember",
"entity",
@@ -187,6 +187,7 @@
"request_id": "string?",
"source_id": "string?",
"ttl": "string?",
+ "valid_from": "string?",
"visibility": "string?"
},
"required_scopes": [],
@@ -239,6 +240,10 @@
"description": "\"30d\", \"12h\" or ISO 8601 time; omit = never.",
"type": "string"
},
+ "valid_from": {
+ "description": "ISO 8601 date or time the fact was said or became true (e.g. the conversation date); omit = unknown, recorded as now.",
+ "type": "string"
+ },
"visibility": {
"description": "world (default) or private (local CLI only).",
"enum": [
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 72f4004d0f..34e6899d5b 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -780,6 +780,7 @@
"isConversationLabels",
"locateChunks",
"pageEvidenceText",
+ "pagePlanHits",
"parseReturnUnit",
"parseReturnWindow",
"resolveEvidencePlan",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 7886443b9a..a9ee4d0b44 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6743,6 +6743,13 @@
"(page: { compiled_truth: string; timeline: string; }, includeTimeline: boolean) => { text: string; timelineAt: number; }"
]
},
+ {
+ "kind": "function",
+ "name": "pagePlanHits",
+ "signature": [
+ "(plan: EvidencePlan | null) => { limit?: number; autocut?: false; }"
+ ]
+ },
{
"kind": "function",
"name": "parseReturnUnit",
diff --git a/test/query-page-budget-fill.test.ts b/test/query-page-budget-fill.test.ts
new file mode 100644
index 0000000000..ed3aa7a337
--- /dev/null
+++ b/test/query-page-budget-fill.test.ts
@@ -0,0 +1,48 @@
+/**
+ * `query` with return_unit page fills its token budget: the hit list is sized
+ * to the budget (about one row per 250 tokens, at most 100) and autocut stays
+ * off unless the caller sets it, so a page lane is not cut at the default row
+ * count with half its budget unused. An explicit limit or autocut still wins.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { pagePlanHits, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';
+
+let engine: PGLiteEngine;
+let meta: Record<string, any> | null = null;
+const ctx = () => ({ engine, config: { engine: 'pglite', embedding_disabled: true }, remote: false, sourceId: 'default', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} }, emitResponseMeta: (k: string, v: unknown) => { if (k === 'retrieval') meta = v as Record<string, any>; } }) as unknown as OperationContext;
+const query = operations.find(o => o.name === 'query')!;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (let i = 0; i < 40; i++) {
+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: `notes/garden-${i}`,
+ content: `---\ntype: note\ntitle: Garden note ${i}\n---\nThe garden tomato harvest note ${i}. ` + 'We planted tomatoes and basil in the garden beds this season. '.repeat(20) } });
+ }
+}, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+
+describe('page-unit budget fill', () => {
+ test('pagePlanHits: autocut off and rows sized to large budgets, for page plans only', () => {
+ const plan = (unit: EvidencePlan['unit'], budgetTokens: number) => ({ requestedUnit: unit, unit, window: 1, budgetTokens, explicitUnit: true }) as EvidencePlan;
+ expect(pagePlanHits(null)).toEqual({});
+ expect(pagePlanHits(plan('window', 8000))).toEqual({});
+ expect(pagePlanHits(plan('page', 4000))).toEqual({ autocut: false });
+ expect(pagePlanHits(plan('page', 8000))).toEqual({ autocut: false, limit: 32 });
+ expect(pagePlanHits(plan('page', 100_000))).toEqual({ autocut: false, limit: 100 });
+ });
+
+ test('an 8k page lane delivers close to its budget; an explicit limit still caps it', async () => {
+ const rows = await query.handler(ctx(), { query: 'garden tomato harvest', return_unit: 'page', token_budget: 8000, expand: false }) as unknown[];
+ expect(rows.length).toBeGreaterThan(25);
+ expect(meta!.delivery.tokens_delivered ?? meta!.delivery.budget_used).toBeGreaterThan(7000);
+ const capped = await query.handler(ctx(), { query: 'garden tomato harvest', return_unit: 'page', token_budget: 8000, expand: false, limit: 10 }) as unknown[];
+ expect(capped.length).toBeLessThanOrEqual(10);
+ });
+});