Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): lean rows carry id only when fetch is callable; score at 4 significant digits

garrytan3c7c3549a1b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb9e2da9a2..05d91f51be 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,14 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased] - low-hanging fruit wave lane B: leaner search rows (GBRA-81)
+
+### Itemized changes
+
+- **Lean search rows drop `id` where `fetch` is not callable.** Remote `search` and `query` lean rows carry `id` (the deep-research `fetch` key, base64 of `source_id` and `slug`, so a duplicate of two fields already in the row) only when `fetch` is callable on the caller's surface at call time. MCP dispatch threads one `isCallable(op)` predicate into `OperationContext`, built from the same check tools/list uses: the stdio session's surface after any `request_tools` widening, the HTTP client's effective surface and scopes under the server ceiling. `fields: "full"`, `mcp.result_rows: full`, gbrain's thin client and the local CLI are unchanged. On the committed Cat 40 Hard transcripts (served on `starter`, 3,169 `search` calls) a keyless replay (`scripts/replay-lean-row-savings.ts`) saves 9.52% of `search` characters on the starter surface and 1.35% on the full surface, where `id` stays and only score rounding applies.
+- **Lean-row `score` prints 4 significant digits.** Rounding happens only in `leanRow`, so full rows and trusted local callers keep the raw float; RRF-scale scores are small, so fixed decimals would have collapsed them. Two scores print equal only when they agree to 4 significant digits, and order never inverts.
+- **`fetch` without an id names both routes.** The refusal says to re-run `search` once `fetch` is callable, or to pass the row's slug (accepted when unambiguous in the caller's read scope).
+
## [0.60.178.0] - 2026-10-12
**Batch entity lookups respect quarantine.** `entity` with `names` now hides quarantined pages from remote callers the way a single-name `entity` lookup and `get_page` already do, whichever way the name resolves, and a quarantined identity sibling no longer appears beside a page for remote callers, in batch rows or in a single-name card. Trusted local callers see the same results as before. No migration, no paid call.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 66aadb8a55..387b2d2194 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -48,7 +48,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.
-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`).
+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`).
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
diff --git a/docs/mcp/README.md b/docs/mcp/README.md
index a14fc3f16f..dc7990d7c7 100644
--- a/docs/mcp/README.md
+++ b/docs/mcp/README.md
@@ -68,10 +68,16 @@ block. Remote callers get **lean rows** by default: the fields an agent acts
on, without the ranking diagnostics that would make each row several times
longer than its evidence text.
-A lean row keeps `id` (the `fetch` key), `slug`, `title`, `type`,
-`chunk_text`, `score`, `effective_date`, `source_id`, `chunk_id` (with
-`slug` and `source_id`, the `assemble_evidence` hit), `evidence` and
-`create_safety` (the duplicate-page guard). It also keeps every safety or
+A lean row keeps `slug`, `title`, `type`, `chunk_text`, `score` (4
+significant digits), `effective_date`, `source_id`, `chunk_id` (with `slug`
+and `source_id`, the `assemble_evidence` hit), `evidence`, `create_safety`
+(the duplicate-page guard), `trust_tier` and `origin`. It keeps `id` (the
+`fetch` key) only when this connection can call `fetch` at that moment: a
+`full` surface, a stdio session `request_tools` widened, or an HTTP client
+whose surface and scopes include it (`starter` and `verbs` do not list
+`fetch`). After `fetch` becomes callable, re-run `search` for `id` or pass
+the row's `slug` to `fetch` (accepted when unambiguous); `fields: "full"`
+returns every field. It also keeps every safety or
provenance marker that is present: `injection_suspected`, `injection_p`,
`unverified`, `content_flag`, `status`, `superseded`, `superseded_by`,
`message_id`, `thread_id`, `source_subject`, `modality` when not `text`,
diff --git a/scripts/replay-lean-row-savings.ts b/scripts/replay-lean-row-savings.ts
new file mode 100644
index 0000000000..13c890f6e1
--- /dev/null
+++ b/scripts/replay-lean-row-savings.ts
@@ -0,0 +1,141 @@
+#!/usr/bin/env bun
+/**
+ * Keyless replay of recorded `search`/`query` tool results through the lean
+ * row change (no `id` where `fetch` is not callable, `score` at 4
+ * significant digits), to measure the characters it saves.
+ *
+ * bun scripts/replay-lean-row-savings.ts <transcripts.jsonl[.gz]> [--results <results.jsonl>] [--json]
+ *
+ * Input: Cat 40 transcripts (gbrain-evals `--transcripts`): one JSON object
+ * per attempt with `tools: [{ name, args, result }]`, where `result` is the
+ * tool's text blocks joined by newlines (content[0] JSON first, then the
+ * `[gbrain search]` / `[gbrain dates]` trailers and notices). The runner
+ * stores at most 40,000 characters of each result; `--results` reads each
+ * call's real size from the cell results (`sessions[].run.tool_calls[].chars`),
+ * so a clipped call's saving is the saving measured on its stored prefix,
+ * scaled to its real size (reported as estimated).
+ *
+ * Two surfaces per call: `starter` (fetch not callable: `id` dropped, unless
+ * an earlier `request_tools {surface: "full"}` in the attempt widened it) and
+ * `full` (fetch callable: only score rounding). The row edit is applied to the
+ * serialized JSON text; on every unclipped call whose content[0] parses, the
+ * result is checked against leanRow's own projection, and any difference is
+ * reported as a mismatch. Characters are JavaScript string length.
+ */
+import { readFileSync } from 'node:fs';
+import { gunzipSync } from 'node:zlib';
+import { leanRow, leanScore } from '../src/core/search/lean-rows.ts';
+
+interface ToolCall { name: string; args?: Record<string, unknown>; result?: string }
+interface Attempt { attempt_id?: string; key: string; tools?: ToolCall[] }
+interface Cell { attempt_id: string; sessions?: Array<{ run?: { tool_calls?: Array<{ name: string; chars: number }> } }> }
+
+const REPLAYED_OPS = new Set(['search', 'query']);
+const ID_FIELD = /,"id":"gbrain-page:v1:[A-Za-z0-9_-]+"/g;
+const SCORE_FIELD = /"score":(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g;
+
+function lines(path: string): string[] {
+ const raw = readFileSync(path);
+ return (path.endsWith('.gz') ? gunzipSync(raw).toString('utf8') : raw.toString('utf8')).split('\n').filter(l => l.trim());
+}
+
+function rewrite(text: string, keepId: boolean): string {
+ const scored = text.replace(SCORE_FIELD, (_m, n: string) => `"score":${JSON.stringify(leanScore(Number(n)))}`);
+ return keepId ? scored : scored.replace(ID_FIELD, '');
+}
+
+/** leanRow's projection of content[0], plus the untouched trailers; null when content[0] is not a row array. */
+function projected(result: string, keepId: boolean): string | null {
+ const nl = result.indexOf('\n');
+ const head = nl < 0 ? result : result.slice(0, nl);
+ try {
+ const rows = JSON.parse(head) as unknown;
+ if (!Array.isArray(rows)) return null;
+ return JSON.stringify(rows.map(r => leanRow(r as Record<string, unknown>, { keepId }))) + (nl < 0 ? '' : result.slice(nl));
+ } catch { return null; }
+}
+
+function main(): void {
+ const args = process.argv.slice(2);
+ const resultsAt = args.indexOf('--results');
+ const resultsPath = resultsAt >= 0 ? args[resultsAt + 1] : undefined;
+ const path = args.find((a, i) => !a.startsWith('--') && (resultsAt < 0 || i !== resultsAt + 1));
+ if (!path) {
+ process.stderr.write('usage: bun scripts/replay-lean-row-savings.ts <transcripts.jsonl[.gz]> [--results <results.jsonl>] [--json]\n');
+ process.exit(2);
+ }
+ const realChars = new Map<string, number[]>();
+ if (resultsPath) {
+ for (const l of lines(resultsPath)) {
+ const cell = JSON.parse(l) as Cell;
+ realChars.set(cell.attempt_id, (cell.sessions ?? []).flatMap(s => (s.run?.tool_calls ?? []).map(c => c.chars)));
+ }
+ }
+ const ops: Record<string, { calls: number; clipped: number; mismatches: number; before: number; starter: number; full: number; before_exact: number; starter_exact: number; full_exact: number }> = {};
+ let gbrainToolChars = 0;
+ let joinFailures = 0;
+ for (const l of lines(path)) {
+ const attempt = JSON.parse(l) as Attempt;
+ const tools = attempt.tools ?? [];
+ const sizes = attempt.attempt_id ? realChars.get(attempt.attempt_id) : undefined;
+ if (resultsPath && sizes?.length !== tools.length) joinFailures++;
+ const usable = sizes?.length === tools.length ? sizes : undefined;
+ const gbrainArm = tools.some(t => REPLAYED_OPS.has(t.name));
+ let widened = false;
+ tools.forEach((call, i) => {
+ const recorded = call.result ?? '';
+ const real = Math.max(usable?.[i] ?? recorded.length, recorded.length);
+ if (gbrainArm) gbrainToolChars += real;
+ if (call.name === 'request_tools' && call.args?.surface === 'full' && !recorded.startsWith('{"error"')) widened = true;
+ if (!REPLAYED_OPS.has(call.name)) return;
+ const t = (ops[call.name] ??= { calls: 0, clipped: 0, mismatches: 0, before: 0, starter: 0, full: 0, before_exact: 0, starter_exact: 0, full_exact: 0 });
+ const starterText = rewrite(recorded, widened);
+ const fullText = rewrite(recorded, true);
+ t.calls++;
+ t.before += real;
+ if (real > recorded.length) {
+ t.clipped++;
+ t.starter += Math.round(real * starterText.length / recorded.length);
+ t.full += Math.round(real * fullText.length / recorded.length);
+ return;
+ }
+ for (const [text, keepId] of [[starterText, widened], [fullText, true]] as const) {
+ const check = projected(recorded, keepId);
+ if (check !== null && check !== text) t.mismatches++;
+ }
+ t.starter += starterText.length;
+ t.full += fullText.length;
+ t.before_exact += real;
+ t.starter_exact += starterText.length;
+ t.full_exact += fullText.length;
+ });
+ }
+ const pct = (saved: number, of: number) => (of === 0 ? 0 : Math.round((saved / of) * 10_000) / 100);
+ const report = {
+ input: path,
+ results: resultsPath ?? null,
+ join_failures: joinFailures,
+ gbrain_arm_tool_result_chars: gbrainToolChars,
+ ops: Object.fromEntries(Object.entries(ops).map(([op, t]) => [op, {
+ ...t,
+ starter_saved_pct: pct(t.before - t.starter, t.before),
+ full_saved_pct: pct(t.before - t.full, t.before),
+ starter_saved_pct_exact_calls: pct(t.before_exact - t.starter_exact, t.before_exact),
+ full_saved_pct_exact_calls: pct(t.before_exact - t.full_exact, t.before_exact),
+ starter_saved_pct_of_gbrain_tool_chars: pct(t.before - t.starter, gbrainToolChars),
+ full_saved_pct_of_gbrain_tool_chars: pct(t.before - t.full, gbrainToolChars),
+ }])),
+ };
+ if (args.includes('--json')) {
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ return;
+ }
+ process.stdout.write(`gbrain-arm tool-result characters: ${gbrainToolChars}${resultsPath ? ` (real sizes from ${resultsPath}; ${joinFailures} attempts not joined)` : ' (stored sizes)'}\n`);
+ for (const [op, r] of Object.entries(report.ops)) {
+ process.stdout.write(`${op}: ${r.calls} calls, ${r.clipped} clipped in the transcript (estimated), ${r.mismatches} projection mismatches; ${r.before} chars\n`
+ + ` starter (no fetch): ${r.starter} chars, saves ${r.before - r.starter} = ${r.starter_saved_pct}% of ${op} (${r.starter_saved_pct_exact_calls}% on unclipped calls), ${r.starter_saved_pct_of_gbrain_tool_chars}% of gbrain tool results\n`
+ + ` full (fetch callable): ${r.full} chars, saves ${r.before - r.full} = ${r.full_saved_pct}% of ${op} (${r.full_saved_pct_exact_calls}% on unclipped calls), ${r.full_saved_pct_of_gbrain_tool_chars}% of gbrain tool results\n`);
+ }
+}
+
+main();
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 13077c7ba1..3fdeab2c41 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -467,6 +467,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },
// Fix wave 15 group 1 (managed sync authority and data safety).
{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
+ // Low-hanging fruit wave lane B (GBRA-81, items 2 and 3). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.178.0', text: 'Lean `search` and `query` rows (remote callers) now carry `id`, the `fetch` key, only when the connection can call `fetch` at that moment: a `full` surface, a stdio session `request_tools` widened, or an HTTP client whose surface and scopes include it. On `starter` and `verbs` connections, `fetch` was never callable, so the row\'s `slug` and `source_id` identify the page; `fields: "full"` returns every field, `id` included, and the `mcp.result_rows: full` host setting does so for every remote caller. Lean-row `score` now prints 4 significant digits. The local CLI and gbrain\'s thin client keep full rows, unchanged. `fetch` called without an id now says to re-run `search` once `fetch` is callable, or to pass the row\'s slug.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 83c5464844..cb1dac1e39 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -545,6 +545,15 @@ export interface OperationContext {
* Shape only, never authority: nothing security-relevant reads it.
*/
resultRows?: 'lean' | 'full';
+ /**
+ * Whether this caller can call `opName` on its surface right now: the MCP
+ * dispatch predicate (the stdio session's surface after any `request_tools`
+ * widening, the HTTP client's effective surface and scopes under the
+ * server ceiling). Set by MCP dispatch only; publish-gated ops read as not
+ * callable. Unset on local and in-process callers. Shape only, never
+ * authority: dispatch enforces callability itself.
+ */
+ isCallable?: (opName: string) => boolean;
/**
* Resolved global CLI options (--quiet / --progress-json / --progress-interval).
* CLI callers populate this from `getCliOptions()`. MCP / library callers
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 72ae272e22..c0acff15de 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -236,7 +236,7 @@ const fetch_page: Operation = {
handler: async (ctx, p) => {
const id = p.id as string;
if (typeof id !== 'string' || !id.trim()) {
- throw opError('invalid_params', 'fetch requires a non-empty id', 'Pass the `id` field from a `search` result.');
+ throw opError('invalid_params', 'fetch requires a non-empty id', 'Pass the `id` field from a `search` result. Search rows carry `id` only when `fetch` is callable on this connection, so a row from a search run before `fetch` was callable has none: re-run `search` now that `fetch` is callable, or pass the row\'s `slug` as `id` (accepted when it is unambiguous within your read scope).');
}
let identity: ReturnType<typeof decodeDeepResearchId>;
try { identity = decodeDeepResearchId(id); }
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index e7560743b0..4cbf333b8d 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -31,7 +31,7 @@ import type { HybridSearchMeta, SearchResult } from '../types.ts';
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 { leanRowsKeepId, projectRows, resultRowsFor } from '../search/lean-rows.ts';
import { buildScoreDetails } from '../search/explain-formatter.ts';
import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, effectivePlan, pagePlanHits, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
@@ -109,6 +109,7 @@ function thinkScopeFromQueryScope(scope: SourceScope): { sourceId?: string; allo
function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number,
evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean }): SearchResult[] {
const rows = resultRowsFor(ctx, p.fields);
+ const lean = { keepId: leanRowsKeepId(ctx) };
// `explain: true` — every row carries its score breakdown (kept in lean rows).
if (p.explain === true) for (const r of results) r.score_details = buildScoreDetails(r);
// The shape is reported where it can vary: remote callers, or an explicit `fields`.
@@ -116,7 +117,7 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results
if (!evidence) {
const output = redactRetrievalOutput(results, { ...meta, ...shown });
ctx.emitResponseMeta?.('retrieval', output.meta);
- return projectRows(applySnippetCap(output.results, snippetCap).map(factRowOutput), rows);
+ return projectRows(applySnippetCap(output.results, snippetCap).map(factRowOutput), rows, lean);
}
// Evidence delivery: explicit snippet_chars wins over the delivered blocks;
// otherwise the blocks are returned whole (their budget already bounds
@@ -126,7 +127,7 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results
// markers and redaction recounted); without one both are no-ops.
const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : capEvidenceToBudget(output.results, output.meta.delivery);
ctx.emitResponseMeta?.('retrieval', output.meta);
- return projectRows(capped.map(factRowOutput), rows);
+ return projectRows(capped.map(factRowOutput), rows, lean);
}
/** C1: the per-call row-shape escape hatch shared by `search` and `query` (`detail` is query's low/medium/high). */
diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.ts
index d078c3db45..a82a228c11 100644
--- a/src/core/search/lean-rows.ts
+++ b/src/core/search/lean-rows.ts
@@ -6,10 +6,12 @@
* chunk_source, keyword_hit, cosine, base_score, boosts, rerank and graph
* signals) that agents do not read but pay for on every later turn. A lean
* row keeps what an agent acts on:
- * - identity and text: id (the deep-research fetch key), slug, title, type,
- * chunk_text, score, effective_date (with effective_date_source, which
+ * - identity and text: slug, title, type, chunk_text, score (rounded to 4
+ * significant digits), effective_date (with effective_date_source, which
* says what kind of date it is), source_id, chunk_id (assemble_evidence
- * takes {source_id, slug, chunk_id});
+ * takes {source_id, slug, chunk_id}); id (the deep-research fetch key,
+ * base64 of source_id and slug) only when `fetch` is callable on the
+ * caller's surface at call time (`ctx.isCallable`, unset = kept);
* - the duplicate-page guard: evidence and create_safety;
* - safety and provenance markers whenever present: injection_suspected,
* injection_p, unverified, content_flag, status, superseded, superseded_by,
@@ -28,7 +30,7 @@ import type { OperationContext } from '../ops/contract.ts';
export type ResultRows = 'lean' | 'full';
const KEPT_FIELDS: ReadonlySet<string> = new Set([
- 'id', 'slug', 'title', 'type', 'chunk_text', 'score', 'effective_date', 'effective_date_source', 'source_id', 'chunk_id',
+ 'slug', 'title', 'type', 'chunk_text', 'effective_date', 'effective_date_source', 'source_id', 'chunk_id',
'evidence', 'create_safety',
'injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by',
'message_id', 'thread_id', 'source_subject', 'relational', 'matched_alias', 'result_type', 'fact_id', 'page_slug', 'follow_up',
@@ -47,11 +49,23 @@ export function resultRowsFor(ctx: Pick<OperationContext, 'remote' | 'resultRows
return ctx.resultRows ?? 'lean';
}
-export function leanRow(row: Record<string, unknown>): Record<string, unknown> {
+/** Lean rows carry `id` only for a caller that can pass it to `fetch`; a caller without the predicate keeps it. */
+export function leanRowsKeepId(ctx: Pick<OperationContext, 'isCallable'>): boolean {
+ return ctx.isCallable?.('fetch') ?? true;
+}
+
+/** 4 significant digits: RRF-scale scores are small, so fixed decimals would collapse them. */
+export function leanScore(score: unknown): unknown {
+ return typeof score === 'number' && Number.isFinite(score) ? Number(score.toPrecision(4)) : score;
+}
+
+export function leanRow(row: Record<string, unknown>, opts: { keepId?: boolean } = {}): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(row)) {
if (value === undefined || (value === null && key !== 'effective_date')) continue;
- if (KEPT_FIELDS.has(key)) out[key] = value;
+ if (key === 'id') { if (opts.keepId !== false) out[key] = value; }
+ else if (key === 'score') out[key] = leanScore(value);
+ else if (KEPT_FIELDS.has(key)) out[key] = value;
else if (key === 'stale' && (value === true || (typeof value === 'object' && value !== null))) out[key] = value;
else if (key === 'modality' && value !== 'text') out[key] = value;
else if (key === 'provenance' && value === 'generated') out[key] = value;
@@ -60,6 +74,6 @@ export function leanRow(row: Record<string, unknown>): Record<string, unknown> {
return out;
}
-export function projectRows<T>(rows: T[], shape: ResultRows): T[] {
- return shape === 'full' ? rows : rows.map(r => leanRow(r as Record<string, unknown>) as T);
+export function projectRows<T>(rows: T[], shape: ResultRows, opts: { keepId?: boolean } = {}): T[] {
+ return shape === 'full' ? rows : rows.map(r => leanRow(r as Record<string, unknown>, opts) as T);
}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 2398f7405d..7fed99b8cd 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -713,6 +713,7 @@ export function buildOperationContext(
(typeof opts.sessionId === 'string' && opts.sessionId.length > 0
? opts.sessionId.slice(0, SESSION_ID_MAX_CHARS)
: undefined) ?? metaSessionIdFrom(params);
+ let render: RenderContext | undefined;
return {
engine,
config: opts.config ?? loadConfig() ?? { engine: 'postgres' },
@@ -734,6 +735,7 @@ export function buildOperationContext(
...(opts.revealTools ? { revealTools: opts.revealTools } : {}),
...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
...(opts.resultRows ? { resultRows: opts.resultRows } : {}),
+ isCallable: (opName: string) => (render ??= dispatchRenderContext(opts)).isCallable(opName),
auth: opts.auth,
};
}
diff --git a/test/helpers/evidence-delivery-fixture.ts b/test/helpers/evidence-delivery-fixture.ts
index 79865e3e63..42773eaba1 100644
--- a/test/helpers/evidence-delivery-fixture.ts
+++ b/test/helpers/evidence-delivery-fixture.ts
@@ -126,7 +126,7 @@ export function withCostWave(key: string, frozen: string): string {
if (base === 'search-remote') {
const v = JSON.parse(frozen) as { result: Record<string, unknown>[]; meta: Array<{ key: string; value: Record<string, unknown> }> };
return JSON.stringify({
- result: v.result.map(leanRow),
+ result: v.result.map(r => leanRow(r)),
meta: v.meta.map(m => m.key === 'retrieval' ? { key: m.key, value: leanRetrieval(m.value) } : m),
});
}
@@ -134,7 +134,7 @@ export function withCostWave(key: string, frozen: string): string {
const res = JSON.parse(frozen) as { content: Array<{ type: string; text: string }>; _meta?: Record<string, Record<string, unknown>> };
const body = JSON.parse(res.content[0].text);
const lean = base === 'mcp-search' || base === 'mcp-query';
- res.content[0].text = JSON.stringify(lean ? (body as Record<string, unknown>[]).map(leanRow) : base === 'mcp-recall' ? withFactsOrder(body) : body);
+ res.content[0].text = JSON.stringify(lean ? (body as Record<string, unknown>[]).map(r => leanRow(r)) : base === 'mcp-recall' ? withFactsOrder(body) : body);
if (lean && res._meta?.retrieval) res._meta.retrieval = leanRetrieval(res._meta.retrieval);
return JSON.stringify(res);
}
diff --git a/test/mcp-advertised-surface.test.ts b/test/mcp-advertised-surface.test.ts
index 95ccc913d9..fedda4e385 100644
--- a/test/mcp-advertised-surface.test.ts
+++ b/test/mcp-advertised-surface.test.ts
@@ -91,6 +91,39 @@ describe('stdio session', () => {
});
}, 120_000);
+ test('search rows carry id when fetch is callable: callable full / advertised starter yes, a starter session only after request_tools widens it', async () => {
+ const rowsOf = (res: unknown) => JSON.parse((res as { content: Array<{ text: string }> }).content[0].text) as Array<Record<string, unknown>>;
+ const advertise = await gbrain(['config', 'set', 'mcp.advertised_surface', 'starter']);
+ expect(advertise.code).toBe(0);
+ try {
+ await session([], async (client) => {
+ const listed = (await client.listTools()).tools.map(t => t.name);
+ expect(listed).toContain('search');
+ expect(listed).not.toContain('fetch');
+ const put = await client.callTool({ name: 'put_page', arguments: { slug: 'notes/lean-id', content: '---\ntype: note\ntitle: Lean id\n---\nThe quokka ledger lives here.\n' } });
+ expect(put.isError).toBeFalsy();
+ const rows = rowsOf(await client.callTool({ name: 'search', arguments: { query: 'quokka ledger' } }));
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.every(r => typeof r.id === 'string')).toBe(true);
+ });
+ await session(['--surface', 'starter'], async (client) => {
+ const before = rowsOf(await client.callTool({ name: 'search', arguments: { query: 'quokka ledger' } }));
+ expect(before.length).toBeGreaterThan(0);
+ expect(before.some(r => 'id' in r)).toBe(false);
+ expect(before.every(r => typeof r.slug === 'string' && typeof r.source_id === 'string')).toBe(true);
+ const widen = await client.callTool({ name: 'request_tools', arguments: { surface: 'full' } });
+ expect(widen.isError).toBeFalsy();
+ const after = rowsOf(await client.callTool({ name: 'search', arguments: { query: 'quokka ledger' } }));
+ expect(after.every(r => typeof r.id === 'string')).toBe(true);
+ const fetched = await client.callTool({ name: 'fetch', arguments: { id: after[0].id } });
+ expect(fetched.isError).toBeFalsy();
+ });
+ } finally {
+ const restore = await gbrain(['config', 'set', 'mcp.advertised_surface', 'verbs']);
+ expect(restore.code).toBe(0);
+ }
+ }, 180_000);
+
test('the callable ceiling still blocks', async () => {
await session(['--surface', 'verbs'], async (client) => {
const put = await client.callTool({ name: 'put_page', arguments: { slug: 'notes/blocked', content: 'x' } });
diff --git a/test/mcp-result-rows-skew.test.ts b/test/mcp-result-rows-skew.test.ts
index 8b8334a56a..605d516fa9 100644
--- a/test/mcp-result-rows-skew.test.ts
+++ b/test/mcp-result-rows-skew.test.ts
@@ -13,6 +13,7 @@
* `mcp.result_rows: full` -> full;
* reject mode accepts `fields`
* Old CLI renderers read slug/score/chunk_text/stale only, which lean rows keep.
+ * Lean rows carry `id` only where `fetch` is callable (a starter client gets none).
*
* Fails when: the thin client loses full rows (renderers, --explain), the
* host-wide escape hatch stops working on a transport, or strict hosts
@@ -118,6 +119,21 @@ describe('OAuth HTTP host', () => {
expect(isFull(JSON.parse((await rawCall('search', { query: 'ocelot pricing', fields: 'full' })).content[0].text))).toBe(true);
});
+ test('a starter client (fetch not callable) gets lean rows without id; the thin client on the same row keeps full rows with id', async () => {
+ await engine.executeRaw(`UPDATE oauth_clients SET surface = 'starter' WHERE client_id = $1`, [clientId]);
+ try {
+ const lean = JSON.parse((await rawCall('search', { query: 'ocelot pricing' })).content[0].text) as Row[];
+ expect(lean.length).toBeGreaterThan(0);
+ expect(lean.every(r => !('page_id' in r) && 'chunk_id' in r && 'slug' in r && !('id' in r))).toBe(true);
+ const thin = await thinCall('search', { query: 'ocelot pricing' });
+ expect(isFull(thin)).toBe(true);
+ expect(thin.every(r => typeof r.id === 'string')).toBe(true);
+ } finally {
+ await engine.executeRaw(`UPDATE oauth_clients SET surface = NULL WHERE client_id = $1`, [clientId]);
+ }
+ expect(isLean(JSON.parse((await rawCall('search', { query: 'ocelot pricing' })).content[0].text))).toBe(true);
+ });
+
test('a header naming another client is not the thin client', async () => {
const res = await rawCall('search', { query: 'ocelot pricing' }, { 'X-Gbrain-Client': 'someone-else/1.0' });
expect(isLean(JSON.parse(res.content[0].text))).toBe(true);
diff --git a/test/search-lean-rows.test.ts b/test/search-lean-rows.test.ts
index aed87d03f2..83b84fa4d5 100644
--- a/test/search-lean-rows.test.ts
+++ b/test/search-lean-rows.test.ts
@@ -6,21 +6,28 @@
* "full"`, the transport's `resultRows`, trusted local callers), the
* `_meta.retrieval.rows` report, and the two follow-up calls a lean row must
* still feed: `assemble_evidence` ({source_id, slug, chunk_id}) and `fetch`
- * (`id`).
+ * (`id`, present only when `fetch` is callable on the caller's surface at
+ * call time: the registered surface, a `request_tools` widening, or an HTTP
+ * client's surface and scopes). `score` prints 4 significant digits.
* Fails when: a kept field is dropped, a diagnostic leaks back into lean rows,
- * an escape hatch stops restoring full rows, or a lean row can no longer be
- * widened or fetched.
+ * an escape hatch stops restoring full rows, a lean row can no longer be
+ * widened or fetched, `id` rides a row on a surface that cannot call
+ * `fetch` (or is missing where it can), or rounding merges two scores that
+ * differ in their first 4 significant digits.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';
import { operations } from '../src/core/operations.ts';
-import { leanRow, resultRowsFor } from '../src/core/search/lean-rows.ts';
+import { leanRow, leanScore, resultRowsFor } from '../src/core/search/lean-rows.ts';
+import { allowedOpNames, createStdioSurfaceState } from '../src/mcp/surface.ts';
import { stampEvidence } from '../src/core/search/evidence.ts';
import { seedOffPath } from './helpers/evidence-delivery-fixture.ts';
import { withEnv } from './helpers/with-env.ts';
-const REMOTE: DispatchOpts = { remote: true, transport: 'http', sourceId: 'default' };
+// An HTTP client on the full surface with a read grant: `fetch` is callable, so lean rows carry `id`.
+const REMOTE: DispatchOpts = { remote: true, transport: 'http', sourceId: 'default', auth: { token: 't', clientId: 'client-a', clientName: 'a', scopes: ['read'], expiresAt: Date.now() / 1000 + 3600 } };
+const HTTP_STARTER: DispatchOpts = { ...REMOTE, surface: 'starter', surfaceCeiling: 'full', allowedOps: allowedOpNames(operations, 'starter') };
const LEAN_ALWAYS = ['id', 'slug', 'title', 'type', 'chunk_text', 'score', 'source_id', 'chunk_id', 'evidence', 'create_safety'];
const DIAGNOSTICS = ['page_id', 'chunk_index', 'chunk_source', 'keyword_hit', 'stale'];
@@ -110,6 +117,73 @@ describe('lean rows still feed the follow-up calls', () => {
});
});
+describe('id rides a lean row only when fetch is callable at call time', () => {
+ const params = { query: 'ocelot pricing', return_unit: 'chunk' };
+ const ids = (rows: Array<Record<string, unknown>>) => rows.map(r => 'id' in r);
+
+ test('an HTTP starter client (fetch not callable) gets no id; slug and source_id still identify the page', async () => {
+ const { rows, meta } = await call('search', params, HTTP_STARTER);
+ expect(rows.length).toBeGreaterThan(0);
+ expect(ids(rows).every(x => !x)).toBe(true);
+ for (const r of rows) for (const key of ['slug', 'source_id', 'chunk_id', 'score']) expect(r, key).toHaveProperty(key);
+ expect(meta?.rows).toBe('lean');
+ });
+
+ test('an HTTP full-surface client without a read grant cannot call fetch, so gets no id', async () => {
+ const { rows } = await call('search', params, { ...REMOTE, auth: { ...REMOTE.auth!, scopes: ['agent'] } });
+ expect(ids(rows).every(x => !x)).toBe(true);
+ });
+
+ test('fetch on the registered surface (HTTP full, stdio full) keeps id on every row', async () => {
+ expect(ids((await call('search', params, REMOTE)).rows).every(Boolean)).toBe(true);
+ expect(ids((await call('search', params, { remote: true, transport: 'stdio', sourceId: 'default', surface: 'full' })).rows).every(Boolean)).toBe(true);
+ });
+
+ test('fields "full" restores id on a starter client', async () => {
+ const { rows, meta } = await call('search', { ...params, fields: 'full' }, HTTP_STARTER);
+ expect(meta?.rows).toBe('full');
+ expect(ids(rows).every(Boolean)).toBe(true);
+ expect(rows[0]).toHaveProperty('page_id');
+ });
+
+ test('stdio: a starter session gets no id, request_tools widens it to full mid-session, the next search carries id', async () => {
+ const session = createStdioSurfaceState(operations, { surface: 'starter', source: 'flag', readOnly: false });
+ // What src/mcp/server.ts hands dispatch on every call: the session's surface and allow-set as they stand now.
+ const stdioOpts = (): DispatchOpts => ({
+ remote: true, transport: 'stdio', sourceId: 'default',
+ ...(session.allowedOps ? { allowedOps: session.allowedOps } : {}), surface: session.surface, surfaceCeiling: session.surface, stdioSurface: session,
+ });
+ expect(ids((await call('search', params, stdioOpts())).rows).every(x => !x)).toBe(true);
+ const widen = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'request_tools', { surface: 'full' }, stdioOpts()));
+ expect(widen.isError, widen.content[0]?.text).not.toBe(true);
+ expect(session.surface).toBe('full');
+ const { rows } = await call('search', params, stdioOpts());
+ expect(ids(rows).every(Boolean)).toBe(true);
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'fetch', { id: rows[0].id }, stdioOpts()));
+ expect(res.isError, res.content[0]?.text).not.toBe(true);
+ });
+
+ test('trust_tier and origin ride every lean row on both surfaces', async () => {
+ for (const opts of [REMOTE, HTTP_STARTER]) {
+ for (const r of (await call('search', params, opts)).rows) {
+ expect(r, 'trust_tier').toHaveProperty('trust_tier');
+ expect(r, 'origin').toHaveProperty('origin');
+ }
+ }
+ });
+
+ test('fetch refused for a missing id names both routes: re-run search, or pass the slug', async () => {
+ const op = operations.find(o => o.name === 'fetch')!;
+ const err = await op.handler({ engine, remote: true, sourceId: 'default' } as never, { id: ' ' }).then(() => null, e => e as { code: string; suggestion: string });
+ expect(err?.code).toBe('invalid_params');
+ expect(err?.suggestion).toContain('re-run `search` now that `fetch` is callable');
+ expect(err?.suggestion).toContain("pass the row's `slug`");
+ const { rows } = await call('search', params, HTTP_STARTER);
+ const bySlug = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, 'fetch', { id: rows[0].slug }, REMOTE));
+ expect(bySlug.isError, bySlug.content[0]?.text).not.toBe(true);
+ });
+});
+
describe('delivered.truncated survives in lean rows whenever delivery truncated (DX-13)', () => {
const truncatedConversation = (rows: Array<Record<string, unknown>>) => {
const row = rows.find(r => r.slug === 'chat/session-a');
@@ -155,6 +229,41 @@ describe('leanRow field contract', () => {
delivered: { unit: 'page', chunk_ids: [3], match_spans: [], tokens: 9, truncated: false },
};
+ test('keepId: false drops only id; trust_tier and origin stay', () => {
+ const lean = leanRow({ ...full, trust_tier: 'owner', origin: 'human' }, { keepId: false });
+ expect(lean).not.toHaveProperty('id');
+ expect(lean).toMatchObject({ slug: 's', source_id: 'default', trust_tier: 'owner', origin: 'human' });
+ expect(Object.keys(leanRow(full)).filter(k => k !== 'id').sort()).toEqual(Object.keys(lean).filter(k => k !== 'trust_tier' && k !== 'origin').sort());
+ });
+
+ test('score prints 4 significant digits; non-finite and non-number scores pass through', () => {
+ expect(leanRow({ ...full, score: 0.016393442622950821 }).score).toBe(0.01639);
+ expect(leanRow({ ...full, score: 12.345678 }).score).toBe(12.35);
+ expect(leanRow({ ...full, score: 0 }).score).toBe(0);
+ expect(leanScore(Number.NaN)).toBeNaN();
+ expect(leanScore('0.5')).toBe('0.5');
+ });
+
+ test('tie: two different scores print equal only when they agree to 4 significant digits, and order never inverts', () => {
+ // RRF-scale scores (1/(k+rank) sums), cosine-scale scores and boosted scores, plus adjacent doubles.
+ const scores: number[] = [];
+ for (let rank = 1; rank <= 200; rank++) scores.push(1 / (60 + rank), 2 / (60 + rank), 1 / (60 + rank) + 1 / (61 + rank));
+ let seed = 7;
+ const rand = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
+ for (let i = 0; i < 2000; i++) scores.push(rand(), rand() * 1e-3, rand() * 50);
+ for (const s of [0.1, 0.01639, 0.016395, 1 / 3]) scores.push(s, s + Number.EPSILON, s * (1 + 1e-5), s * (1 - 1e-5));
+ const sorted = [...new Set(scores)].sort((a, b) => b - a);
+ for (let i = 0; i < sorted.length; i++) {
+ for (const j of [i + 1, i + 2, i + 7]) {
+ if (j >= sorted.length) continue;
+ const [a, b] = [sorted[i], sorted[j]];
+ const printedEqual = JSON.stringify(leanRow({ score: a }).score) === JSON.stringify(leanRow({ score: b }).score);
+ expect(printedEqual, `${a} vs ${b}`).toBe(a.toPrecision(4) === b.toPrecision(4));
+ expect(leanRow({ score: a }).score as number).toBeGreaterThanOrEqual(leanRow({ score: b }).score as number);
+ }
+ }
+ });
+
test('keeps identity, text, the duplicate guard and every present safety/provenance marker; drops diagnostics', () => {
expect(leanRow(full)).toEqual({
id: 'gbrain-page:v1:x', slug: 's', title: 't', type: 'note', chunk_text: 'body', chunk_id: 3, score: 0.5, source_id: 'default',