Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

get_chunks: the last chunk of a cut list carries truncated: true and next_from_index (array shape unchanged)

garrytancda197a58074
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 56e978e9af..3ce42056c5 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -584,6 +584,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'A page over 1 MiB now commits with its chunks keyword-searchable and no vectors, and is embedded after the write by the stale sweep, `gbrain embed` or the post-write embedding job, instead of embedding every chunk inline before the write commits. Each such page spends at most `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset; `off` disables it) over its lifetime per embedding model, newest chunks first; the run caps still apply and the lowest cap wins. A page the cap stopped, or one held for approval, leaves the stale queue, and doctor\'s new `partial_embedding` check names it with the approval command (`gbrain embed --held --max-usd N`, or `gbrain embed --slugs <slug> --max-usd N`). Before embedding, a large page whose head, middle and tail samples are all markup, or two of them match junk patterns, is held instead. Large pages use the free title context tier, never paid per-chunk synopses.' },
{ since: 'TBD', text: '`gbrain upgrade` now re-indexes pages an older gbrain stored without chunks because they were over 500 KB (`embed_skip: oversized`) when they fit under the effective `bytes_block`: for up to two minutes in its post-upgrade step, then `gbrain reindex --oversized` (new; `--dry-run`, `--source`, `--limit`, `--json`) finishes. It is CPU-only, works with embeddings off, makes those pages keyword-searchable at once and prints a receipt. It removes only the gate-written marker and its `content_flag: oversized`. Pages over 1 MiB are held for embedding approval; the post-upgrade notice shows their count and estimated cost and asks before anything is spent.' },
{ since: 'TBD', text: 'A page over 1 MiB keeps only its newest 5 large version snapshots in `page_versions` (each snapshot is a full copy of the body); its snapshots at or under 1 MiB, and every snapshot of a smaller page, are kept as before. The persistence journal now admits 64 MiB of outstanding write intent per principal (was 32 MiB), so a second ceiling-size write can wait behind the first. Write-through never writes a canonical file over the 25 MiB pre-push secret-scan limit: it skips with `over_push_scan_cap`, and a managed write that would produce one is refused with `request_too_large`.' },
+ // Large pages: get_chunks truncation marker (coordinator follow-up to the read contract). `since` is set at the merge-slot stamp.
+ { since: 'TBD', text: 'When `get_chunks` returns fewer chunks than the page holds, the last chunk in the list now carries `truncated: true` and `next_from_index`, so a client that reads only the array (and not `_meta.pagination` or the `listing_truncated` notice) sees the list is incomplete. The result is still a bare array; the other chunks are unchanged.' },
// Large pages A3/T44, A4/T32 (Lane 3a). `since` is set at the merge-slot stamp.
{ since: 'TBD', text: 'Replacing a page\'s chunks now writes them in bounded batches (at most 500 rows and 16 MiB of encoded rows per statement) after one prune, all in the same transaction, instead of one statement carrying every chunk. A page with thousands of chunks no longer builds one giant statement, and a failure in any batch still rolls the whole replacement back.' },
{ since: 'TBD', text: 'A chunk vector is now tied to the chunk\'s text and its full embedding input rather than its position. When an edit inserts or removes chunks above it, a projection rebuild moves the unchanged chunk to its new index with its vector instead of dropping it, so only new or changed chunks wait for embedding. An embed that finishes after the page changed now commits the vectors of the chunks that are still the same (same text, source and embedding input) and leaves the rest for the next run, instead of discarding the whole run; the page\'s embedding signature is stamped only when every chunk got its vector. A vector built under an old title or synopsis is still dropped.' },
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index eba849e7f1..8dd7d87b44 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -2950,7 +2950,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"outputRedaction": {
"exempt": "explicit chunk read by slug, the page-read twin of get_page (CEO-17 raw-read exception)"
},
- "description": "Return a page's indexed content chunks (the units search ranks), in chunk_index order, 50 at a time by default. Use when debugging why search did or did not match a page. A large page has more chunks than one call returns: _meta.pagination carries total_chunks and next_from_index, and a listing_truncated notice names the next call (from_index). Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "description": "Return a page's indexed content chunks (the units search ranks), in chunk_index order, 50 at a time by default. Use when debugging why search did or did not match a page. A large page has more chunks than one call returns: the last chunk of a cut list carries truncated: true and next_from_index, _meta.pagination carries total_chunks and next_from_index, and a listing_truncated notice names the next call (from_index). Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
"params": {
"slug": {
"type": "string",
diff --git a/src/core/ops/chunks.ts b/src/core/ops/chunks.ts
index b359390b41..cf17c1b6a1 100644
--- a/src/core/ops/chunks.ts
+++ b/src/core/ops/chunks.ts
@@ -47,7 +47,7 @@ const get_chunks: Operation = {
mutating: false,
idempotent: true,
outputRedaction: { exempt: 'explicit chunk read by slug, the page-read twin of get_page (CEO-17 raw-read exception)' },
- description: `Return a page's indexed content chunks (the units search ranks), in chunk_index order, ${GET_CHUNKS_DEFAULT_LIMIT} at a time by default. Use when debugging why search did or did not match a page. A large page has more chunks than one call returns: _meta.pagination carries total_chunks and next_from_index, and a listing_truncated notice names the next call (from_index). Needs read scope. On page_not_found: resolve the slug with resolve_slugs.`,
+ description: `Return a page's indexed content chunks (the units search ranks), in chunk_index order, ${GET_CHUNKS_DEFAULT_LIMIT} at a time by default. Use when debugging why search did or did not match a page. A large page has more chunks than one call returns: the last chunk of a cut list carries truncated: true and next_from_index, _meta.pagination carries total_chunks and next_from_index, and a listing_truncated notice names the next call (from_index). Needs read scope. On page_not_found: resolve the slug with resolve_slugs.`,
params: {
slug: { type: 'string', required: true, description: 'Slug of the page whose content chunks to return.' },
min_trust: MIN_TRUST_PARAM,
@@ -72,8 +72,9 @@ const get_chunks: Operation = {
const { floor } = await resolveReadEligibility(ctx, { minTrust: p.min_trust });
const chunks = (await stampPageTrust(ctx.engine, page.chunks.map(c => ({ ...c, slug: p.slug as string })), floor))
.map(({ slug: _slug, ...chunk }) => chunk);
- reportChunkPage(ctx, p, { fromIndex, limit, clampedFrom, returned: chunks.length, totalChunks: page.total_chunks, maxChunkIndex: page.max_chunk_index });
- return chunks;
+ const next = reportChunkPage(ctx, p, { fromIndex, limit, clampedFrom, returned: chunks.length, totalChunks: page.total_chunks, maxChunkIndex: page.max_chunk_index });
+ if (next === undefined || chunks.length === 0) return chunks;
+ return [...chunks.slice(0, -1), { ...chunks[chunks.length - 1], truncated: true, next_from_index: next }];
},
scope: 'read',
};
diff --git a/src/core/ops/read-paging.ts b/src/core/ops/read-paging.ts
index 48161e2f31..273a9ce21f 100644
--- a/src/core/ops/read-paging.ts
+++ b/src/core/ops/read-paging.ts
@@ -9,7 +9,11 @@
* - the model-visible `listing_truncated` notice for remote callers when more
* rows remain, whose fix is the exact next call;
* - one stderr line for the trusted local CLI when the caller named no limit
- * and the default cut the result.
+ * and the default cut the result;
+ * - get_chunks only: the last chunk of a cut list carries `truncated: true`
+ * and `next_from_index`, so a client that reads only the array (and ignores
+ * `_meta` and notices) still sees the list is incomplete. Additive fields on
+ * one element keep the array shape older clients parse.
*/
import type { Notice } from '../agent-output.ts';
import type { OperationContext } from './contract.ts';
@@ -39,10 +43,10 @@ function emitTruncated(ctx: OperationContext, why: string, fix: Notice['fix']):
ctx.emitNotice?.({ code: 'listing_truncated', kind: 'info', why, ...(fix ? { fix } : {}) });
}
-/** get_chunks: meta, notice and local stderr for one page of chunks. */
+/** get_chunks: meta, notice and local stderr for one page of chunks; returns next_from_index when more chunks remain. */
export function reportChunkPage(ctx: OperationContext, p: Record<string, unknown>, page: {
fromIndex: number; limit: number; clampedFrom?: number; returned: number; totalChunks: number; maxChunkIndex: number | null;
-}): void {
+}): number | undefined {
const more = page.maxChunkIndex !== null && page.maxChunkIndex >= page.fromIndex + page.limit;
const next = more ? page.fromIndex + page.limit : undefined;
ctx.emitResponseMeta?.('pagination', {
@@ -50,12 +54,12 @@ export function reportChunkPage(ctx: OperationContext, p: Record<string, unknown
...(page.clampedFrom !== undefined ? { clamped_from: page.clampedFrom } : {}),
...(next !== undefined ? { next_from_index: next } : {}),
});
- if (next === undefined) return;
+ if (next === undefined) return undefined;
if (ctx.remote === false) {
if (p.limit === undefined || p.limit === null) {
console.error(`[get_chunks] output truncated at ${page.limit} chunks (default ${GET_CHUNKS_DEFAULT_LIMIT}) of ${page.totalChunks}. Pass --limit <n>, or continue with --from-index ${next}.`);
}
- return;
+ return next;
}
const clamp = page.clampedFrom !== undefined ? ` (limit ${page.clampedFrom} was capped at ${page.limit})` : '';
emitTruncated(ctx, `The page has ${page.totalChunks} chunks; chunks from chunk_index ${page.fromIndex} below ${next} were returned${clamp}, so this list is not complete.`, {
@@ -63,6 +67,7 @@ export function reportChunkPage(ctx: OperationContext, p: Record<string, unknown
consent: [], actor: 'agent', requires_exclusive: false,
why: 'Fetches the next chunks; every other parameter stays the same. Keep paging until no listing_truncated notice comes back.',
});
+ return next;
}
/** get_versions: meta, notice and local stderr when the limit cut the history. */
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 1bcee22712..827f6ef252 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": 236239,
- "stdoutSha256": "9f6aab59c8b33e9f2318241460f39bafd43ad8aaeeafa2e88cea1bf9e808b2db",
+ "stdoutBytes": 236313,
+ "stdoutSha256": "26539b9ecb02409420c3852d7f5660943a4aff8a522362dcb6d56ede7f7ed1b7",
"toolNames": [
"remember",
"entity",
@@ -3488,7 +3488,7 @@
"scope": "read"
},
{
- "description": "Return a page's indexed content chunks (the units search ranks), in chunk_index order, 50 at a time by default. Use when debugging why search did or did not match a page. A large page has more chunks than one call returns: _meta.pagination carries total_chunks and next_from_index, and a listing_truncated notice names the next call (from_index). Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "description": "Return a page's indexed content chunks (the units search ranks), in chunk_index order, 50 at a time by default. Use when debugging why search did or did not match a page. A large page has more chunks than one call returns: the last chunk of a cut list carries truncated: true and next_from_index, _meta.pagination carries total_chunks and next_from_index, and a listing_truncated notice names the next call (from_index). Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
"idempotent": true,
"local_only": false,
"mutating": false,
diff --git a/test/get-chunks-paging.test.ts b/test/get-chunks-paging.test.ts
index 07bcae78d8..96b8852edd 100644
--- a/test/get-chunks-paging.test.ts
+++ b/test/get-chunks-paging.test.ts
@@ -79,6 +79,19 @@ describe('get_chunks paging', () => {
expect(c.notices[0].fix?.mcp).toEqual({ tool: 'get_chunks', arguments: { slug: BIG, from_index: 50, limit: 50 } });
});
+ test('a default call on a page with more than 50 chunks marks the cut in the array itself (clients that ignore _meta)', async () => {
+ for (const remote of [true, false]) {
+ const rows = await chunks(remote, { slug: BIG }) as Array<{ chunk_index: number; truncated?: boolean; next_from_index?: number }>;
+ expect(rows).toHaveLength(50);
+ expect(rows[49]).toMatchObject({ chunk_index: 49, truncated: true, next_from_index: 50 });
+ expect(rows.slice(0, 49).some(row => 'truncated' in row || 'next_from_index' in row)).toBe(false);
+ }
+ const whole = await chunks(true, { slug: SMALL }) as Array<Record<string, unknown>>;
+ expect(whole.some(row => 'truncated' in row || 'next_from_index' in row)).toBe(false);
+ const last = await chunks(true, { slug: BIG, from_index: 600, limit: 50 }) as Array<Record<string, unknown>>;
+ expect(last.some(row => 'truncated' in row)).toBe(false);
+ });
+
test('paging boundaries: consecutive pages cover every chunk exactly once', async () => {
const seen: number[] = [];
let from: number | undefined = 0;
@@ -164,6 +177,7 @@ describe('get_chunks paging', () => {
const body = JSON.parse(res.content[0].text);
expect(Array.isArray(body)).toBe(true);
expect(body).toHaveLength(100);
+ expect(body[99]).toMatchObject({ chunk_index: 99, truncated: true, next_from_index: 100 });
expect(res._meta?.pagination).toEqual({ from_index: 0, limit: 100, returned: 100, total_chunks: BIG_CHUNKS, next_from_index: 100 });
const notice = res.content.slice(1).map(b => b.text).find(t => t.startsWith('[gbrain notice listing_truncated'));
expect(notice).toContain(`fix: get_chunks {"slug":"${BIG}","from_index":100,"limit":100}`);