Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search,get): an exact top hit with a current projection drops projection_pending from the human line (top_hit_exact); get --lines/--bytes take N-M and N
garrytan5a35c31e6f31
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 482d1aa7dc..b581e00cd5 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -155,7 +155,9 @@ headings above it. If no heading matches, the error lists the page's headings(plain text, not a pattern) plus `--context` paragraphs either side (default1, at most 5), with line numbers and `total_matches`. It returns at most 50matching paragraphs and 100,000 characters, and says `truncated` when it-stops early. The line numbers are the ones a `--body window` read takes.+stops early. The line numbers are the ones a `--body window` read takes:+`gbrain get <slug> --body window --lines 100-140` reads lines 100 to 140+(`--lines 100` reads one line, `--bytes 0-999` the first 1,000 bytes).Both read the same text a window does, so they show a remote caller nothing awindow would not, and they work on segmented pages one segment at a time.Every `get_page` response carries `chars`, the characters of page text itdiff --git a/src/cli/op-param-values.ts b/src/cli/op-param-values.tsindex e5413afa98..88f1c9ac4d 100644--- a/src/cli/op-param-values.ts+++ b/src/cli/op-param-values.ts@@ -41,9 +41,9 @@ export function opFlagValue(op: Operation, key: string, def: ParamDef | undefine/*** An object/array param from its CLI text: JSON, or for a string-item array- * a comma list (`--types person,company`), or for a `cliKeyValue` object+ * a comma list (`--types person,company`), for a `cliKeyValue` object* repeated `key=value` pairs, where `key=a,b` is a list and a repeated key- * merges. Other values pass through.+ * merges, or for a `cliRange` window `N-M` (inclusive) or `N`. Other values pass through.*/export function opStructuredValue(key: string, def: ParamDef, value: unknown): unknown {const flag = `--${key.replace(/_/g, '-')}`;@@ -63,8 +63,16 @@ export function opStructuredValue(key: string, def: ParamDef, value: unknown): u}const text = def.cliKeyValue && Array.isArray(value) ? value[0] : value;if ((def.type !== 'object' && def.type !== 'array') || typeof text !== 'string') return value;+ const range = def.cliRange && /^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/.exec(text);+ if (def.cliRange && range) {+ const start = Number(range[1]), end = range[2] === undefined ? start : Number(range[2]);+ if (end < start) throw usageError(`${flag} ${inertText(text, 40)} ends before it starts.`, `Pass ${flag} N-M with N <= M, e.g. ${flag} 100-140.`);+ return { [def.cliRange[0]]: start, [def.cliRange[1]]: end - start + 1 };+ }if (def.type === 'array' && def.items?.type === 'string' && !text.trimStart().startsWith('[')) return text.split(',').map(v => v.trim()).filter(Boolean);- const jsonError = () => usageError(`${flag} requires a JSON ${def.type}.`, `Pass JSON, e.g. ${flag} '${def.type === 'array' ? '["a","b"]' : '{"key":"value"}'}'.`);+ const jsonError = () => def.cliRange+ ? usageError(`${flag} takes a range N-M (inclusive) or N, or a JSON object.`, `Pass ${flag} 100-140, or ${flag} '{"${def.cliRange[0]}":100,"${def.cliRange[1]}":41}'.`)+ : usageError(`${flag} requires a JSON ${def.type}.`, `Pass JSON, e.g. ${flag} '${def.type === 'array' ? '["a","b"]' : '{"key":"value"}'}'.`);let parsed: unknown;try { parsed = JSON.parse(text); } catch { throw jsonError(); }if (def.type === 'array' ? !Array.isArray(parsed) : parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw jsonError();diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 5c5e19a608..68f2a1ac1f 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -265,6 +265,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"lines": {"type": "object",+ "cliRange": [+ "from",+ "count"+ ],"description": "Window: 1-based lines.","properties": {"from": {@@ -280,6 +284,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"bytes": {"type": "object",+ "cliRange": [+ "offset",+ "length"+ ],"description": "Window: UTF-8 bytes of size.total_bytes, not body_bytes (snapped to a line start).","properties": {"offset": {diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 26d36ed953..ad86004427 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -258,6 +258,8 @@ export interface ParamDef {fullSurfaceOnly?: boolean;/** An object param the CLI takes as repeated `--flag key=value` (`key=a,b` is a list); MCP passes the object. */cliKeyValue?: boolean;+ /** An object window the CLI also takes as `N-M` (inclusive) or `N`: the [start, length] member names. */+ cliRange?: readonly [string, string];}export interface Logger {diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex 76787ae57a..dcf8db17d5 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -68,8 +68,8 @@ export const LARGE_PAGES_CAPABILITY = 'large_pages_v1';export const GET_PAGE_BODY_PARAMS: Record<string, ParamDef> = {body: { type: 'string', enum: [...BODY_MODES], description: 'auto: whole up to 256 KB, else outline + window; a window\'s edit_target is edit_page `within`. none: revision + size + tail_sha256 (append_page expected_tail_sha256).', fullSurfaceOnly: true },- lines: { type: 'object', description: 'Window: 1-based lines.', properties: { from: { type: 'number', required: true }, count: { type: 'number', required: true } }, fullSurfaceOnly: true },- bytes: { type: 'object', description: 'Window: UTF-8 bytes of size.total_bytes, not body_bytes (snapped to a line start).', properties: { offset: { type: 'number', required: true }, length: { type: 'number', required: true } }, fullSurfaceOnly: true },+ lines: { type: 'object', cliRange: ['from', 'count'], description: 'Window: 1-based lines.', properties: { from: { type: 'number', required: true }, count: { type: 'number', required: true } }, fullSurfaceOnly: true },+ bytes: { type: 'object', cliRange: ['offset', 'length'], description: 'Window: UTF-8 bytes of size.total_bytes, not body_bytes (snapped to a line start).', properties: { offset: { type: 'number', required: true }, length: { type: 'number', required: true } }, fullSurfaceOnly: true },around_chunk_id: { type: 'number', description: 'Window around a search hit chunk_id.', fullSurfaceOnly: true },context_lines: { type: 'number', description: 'Lines around around_chunk_id (20).', fullSurfaceOnly: true },cursor: { type: 'string', description: 'next_cursor: read on.', fullSurfaceOnly: true },diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 17fb879c64..e9a364157b 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -448,7 +448,7 @@ async function buildRetrievalResponseMeta(const readinessScope = { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes };// #6721: these reads depend on nothing but the inputs above, so they run at once: on a pooled Postgres// the wall time is the slowest read's round trips, not their sum. The answer-feedback write still runs last.- const [safeIndexPending, [readiness, pending], entityFacts, matchedFacts, held, sourceFreshness, embeddingHeld, filterNotice] = await Promise.all([+ const [safeIndexPending, [readiness, pendingCount], entityFacts, matchedFacts, held, sourceFreshness, embeddingHeld, filterNotice] = await Promise.all([ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes }),probeProjectionReadiness(ctx.engine, readinessScope).then(async r =>[r, r.status === 'projection_pending' ? await countPendingProjections(ctx.engine, readinessScope, relevance) : null] as const),@@ -462,6 +462,8 @@ async function buildRetrievalResponseMeta(opts.filterHintFor ? searchFilterHint(ctx, scope, excludePrivate, queryText, results as SearchResult[], opts.types, opts.filterHintFor) : null,]);const heldFiles = held.coverage;+ const topHitExact = pendingCount?.top_counted === false;+ const pending = topHitExact ? { ...pendingCount!, could_affect: 0 } : pendingCount;if (filterNotice) ctx.emitNotice?.(filterNotice);const heldBySource = new Map(heldFiles.map(h => [h.source_id, h.missing + h.stale]));const freshness = sourceFreshness.map(f => ({ ...f, held_count: heldBySource.get(f.source_id) ?? 0 }));@@ -478,6 +480,7 @@ async function buildRetrievalResponseMeta(could_affect: { ...(pending ? { pending_projection: pending.could_affect } : {}), ...(heldTotal && held.couldAffect !== null ? { held_files: held.couldAffect } : {}),...(embedding ? { embedding_held: embedding.could_affect } : {}) },...(pending?.capped || embedding?.capped ? { capped: true as const } : {}),+ ...(topHitExact ? { top_hit_exact: true as const } : {}),} : undefined;const heldNotice = heldFilesNotice(held.couldAffect === 0 ? [] : heldFiles, ctx.remote !== false, held.couldAffect ?? undefined,embedding?.could_affect ? embedding : undefined);diff --git a/src/core/search/retrieval-coverage.ts b/src/core/search/retrieval-coverage.tsindex 263c87634f..d3cb3241df 100644--- a/src/core/search/retrieval-coverage.ts+++ b/src/core/search/retrieval-coverage.ts@@ -26,6 +26,8 @@ export interface CoverageRelevance {/** Lowercase LIKE patterns, one per query word. */patterns: string[];pageIds: number[];+ /** The top result's page when it is an exact slug, title or alias match for the query, else null. */+ exactTopPageId: number | null;}/** `_meta.retrieval.coverage`: counts in the read scope and how many of them could affect this query. */@@ -35,13 +37,15 @@ export interface RetrievalCoverage {embedding_held?: number;could_affect: { pending_projection?: number; held_files?: number; embedding_held?: number };capped?: true;+ /** The top result is the page the query named (exact slug, title or alias) and its projection is current: pending pages are not counted as able to affect this answer. */+ top_hit_exact?: true;}-export interface ScopedCount { total: number; could_affect: number; capped: boolean }+export interface ScopedCount { total: number; could_affect: number; capped: boolean; /** With an exact top hit: whether that page is itself counted. */ top_counted?: boolean }/** What could make a pending or held item relevant to this query (see the module comment). */export function coverageRelevance(- results: ReadonlyArray<{ type?: unknown; page_id?: unknown }>,+ results: ReadonlyArray<{ type?: unknown; page_id?: unknown; exact_lookup?: unknown; alias_hit?: unknown }>,queryText: string,queryTypes: readonly string[] | undefined,stopwords: ReadonlySet<string>,@@ -53,6 +57,7 @@ export function coverageRelevance(types: [...new Set([...(queryTypes ?? []), ...results.flatMap(r => (typeof r.type === 'string' ? [r.type] : []))])],patterns: terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`),pageIds: [...new Set(results.flatMap(r => (typeof r.page_id === 'number' ? [r.page_id] : [])))],+ exactTopPageId: results[0] && (results[0].exact_lookup || results[0].alias_hit === true) && typeof results[0].page_id === 'number' ? results[0].page_id : null,};}@@ -82,10 +87,13 @@ async function countInScope(engine: Pick<BrainEngine, 'executeRaw'>, scope: Projconst filters = coverageScopeFilters(scope, params);params.push(relevance.all, relevance.types, relevance.patterns, relevance.pageIds);const n = params.length;+ const top = relevance.exactTopPageId;+ if (top !== null) params.push(top);try {- const [row] = await engine.executeRaw<{ total: number | string; could_affect: number | string }>(+ const [row] = await engine.executeRaw<{ total: number | string; could_affect: number | string; top_counted?: boolean | null }>(`SELECT count(*)::int AS total,- count(*) FILTER (WHERE $${n - 3}::boolean OR x.type = ANY($${n - 2}::text[]) OR x.haystack LIKE ANY($${n - 1}::text[]) OR x.id = ANY($${n}::int[]))::int AS could_affect+ count(*) FILTER (WHERE $${n - 3}::boolean OR x.type = ANY($${n - 2}::text[]) OR x.haystack LIKE ANY($${n - 1}::text[]) OR x.id = ANY($${n}::int[]))::int AS could_affect${top === null ? '' : `,+ EXISTS (SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id ${join} WHERE p.id = $${n + 1}::int AND p.deleted_at IS NULL AND ${where}) AS top_counted`}FROM (SELECT p.id, p.type, lower(COALESCE(p.title, '') || ' ' || p.slug) AS haystackFROM pages p JOIN sources s ON s.id = p.source_id ${join}WHERE p.deleted_at IS NULL AND ${where} AND ${filters.join(' AND ')}@@ -94,7 +102,7 @@ async function countInScope(engine: Pick<BrainEngine, 'executeRaw'>, scope: Proj);const total = Number(row?.total), couldAffect = Number(row?.could_affect);if (!Number.isFinite(total) || !Number.isFinite(couldAffect)) return null;- return { total, could_affect: couldAffect, capped: total >= COVERAGE_COUNT_CAP };+ return { total, could_affect: couldAffect, capped: total >= COVERAGE_COUNT_CAP, ...(top === null ? {} : { top_counted: row?.top_counted === true }) };} catch {return null;}diff --git a/test/cli-range-param.test.ts b/test/cli-range-param.test.tsnew file mode 100644index 0000000000..75f1e0bfaa--- /dev/null+++ b/test/cli-range-param.test.ts@@ -0,0 +1,34 @@+/**+ * `gbrain get --lines 100-140` (and `--lines 100`, `--bytes 0-999`) take the+ * range form an agent tries first. Before, the generic parser JSON-parsed the+ * object param and refused with "--lines requires a JSON object".+ */+import { describe, expect, test } from 'bun:test';+import { operations } from '../src/core/operations.ts';+import { parseOpArgs } from '../src/cli/main.ts';++const getPage = operations.find(o => o.name === 'get_page')! as never;++describe('get_page window ranges on the CLI', () => {+ test('--lines N-M is the inclusive line range', () => {+ expect(parseOpArgs(getPage, ['notes/acme-example', '--lines', '100-140']).lines).toEqual({ from: 100, count: 41 });+ expect(parseOpArgs(getPage, ['notes/acme-example', '--lines=100 - 140']).lines).toEqual({ from: 100, count: 41 });+ });++ test('--lines N is one line', () => {+ expect(parseOpArgs(getPage, ['notes/acme-example', '--lines', '100']).lines).toEqual({ from: 100, count: 1 });+ });++ test('--bytes N-M is the inclusive byte range', () => {+ expect(parseOpArgs(getPage, ['notes/acme-example', '--bytes', '0-999']).bytes).toEqual({ offset: 0, length: 1000 });+ });++ test('JSON still works', () => {+ expect(parseOpArgs(getPage, ['notes/acme-example', '--lines', '{"from":5,"count":10}']).lines).toEqual({ from: 5, count: 10 });+ });++ test('a reversed range and an unparseable value are usage errors that name the range form', () => {+ expect(() => parseOpArgs(getPage, ['notes/acme-example', '--lines', '140-100'])).toThrow('--lines 140-100 ends before it starts.');+ expect(() => parseOpArgs(getPage, ['notes/acme-example', '--lines', 'first'])).toThrow('--lines takes a range N-M (inclusive) or N, or a JSON object.');+ });+});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 2e8fe931d1..9379781f83 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6488,6 +6488,7 @@"kind": "interface","members": ["cliKeyValue?: boolean | undefined",+ "cliRange?: readonly [string, string] | undefined","default?: unknown","description?: string | undefined","enum?: string[] | undefined",diff --git a/test/retrieval-coverage-notices.test.ts b/test/retrieval-coverage-notices.test.tsindex 06cb8ec8ad..5373779082 100644--- a/test/retrieval-coverage-notices.test.ts+++ b/test/retrieval-coverage-notices.test.ts@@ -140,6 +140,41 @@ describe('projection_pending is scoped to the query', () => {expect(c.meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });}));+ test('an exact top hit whose projection is current drops projection_pending from the human-facing line (top_hit_exact)', eachEngine(async () => {+ await page('notes/acme-example-plan', 'note', 'Acme-example renewal plan', 'acme-example renewal plan draft');+ await pending('notes/acme-example-plan');+ // The exact-lookup tier runs on the hybrid path, which keyword-only search skips.+ await engine.setConfig('search.mcp_keyword_only', 'false');+ try {+ const c = call('default');+ const results = await search.handler(c.ctx, { query: 'companies/acme-example' }) as Array<{ slug: string; exact_lookup?: string }>;+ expect(results[0]).toMatchObject({ slug: 'companies/acme-example', exact_lookup: 'slug' });+ expect(c.meta.retrieval.coverage).toEqual({ pending_projection: 2, could_affect: { pending_projection: 0 }, top_hit_exact: true });+ expect(c.meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });+ expect(String(c.meta.retrieval.hint ?? '')).not.toContain('projections are pending');+ captureRetrievalMeta('retrieval', c.meta.retrieval);+ try { expect(formatResult('search', results, {})).not.toContain('Retrieval incomplete'); } finally { resetRetrievalMetaForTests(); }+ } finally {+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'notes/acme-example-plan'");+ await engine.setConfig('search.mcp_keyword_only', 'true');+ }+ }));++ test('an exact top hit that is itself pending keeps projection_pending counted', eachEngine(async () => {+ await pending('companies/acme-example');+ await engine.setConfig('search.mcp_keyword_only', 'false');+ try {+ const c = call('default');+ const results = await search.handler(c.ctx, { query: 'companies/acme-example' }) as Array<{ slug: string }>;+ expect(results[0]?.slug).toBe('companies/acme-example');+ expect(c.meta.retrieval.coverage.top_hit_exact).toBeUndefined();+ expect(c.meta.retrieval.coverage.could_affect.pending_projection).toBeGreaterThan(0);+ } finally {+ await engine.executeRaw("UPDATE pages SET text_projection_revision = knowledge_revision WHERE slug = 'companies/acme-example' AND source_id = 'default'");+ await engine.setConfig('search.mcp_keyword_only', 'true');+ }+ }));+test('the query --types scope counts pending pages of those types', eachEngine(async () => {const c = call('default');await search.handler(c.ctx, { query: QUERY, types: ['image', 'company'] });