Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (a failed cursor falls through, markdown sets around_chunk_id aside, set-aside include_content says the window is not the page)

garrytan80aaff05277f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8c54f003b..7a6a1b940f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,9 +16,9 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
-- `src/core/ops/get-page-body.ts`: `parseBodyRequest` still validates each selector on its own, then orders them cursor, around_chunk_id, lines, bytes, and the first one applies. `body: "full"`, `include_content` and `content_only` beside a selector are set aside, while `body: "none"` or `"outline"` beside one still refuses. When an `around_chunk_id`'s chunk is no longer on the page and another selector was sent, the read falls back to that selector; on its own, such an id still refuses `revision_changed`. A read that set anything aside returns `window_selector {applied, ignored, note}`.
+- `src/core/ops/get-page-body.ts`: `parseBodyRequest` still validates each selector on its own, then orders them cursor, around_chunk_id, lines, bytes, and the first one applies. `body: "full"`, `include_content` and `content_only` beside a selector are set aside, while `body: "none"` or `"outline"` beside one still refuses. When a cursor can't read this page (another page's, another view's, or issued before the page changed) or an `around_chunk_id`'s chunk is no longer on the page, and another selector was sent, the read falls back to the next one; on its own, each still refuses as before. With `view: "markdown"`, `around_chunk_id` beside another selector is set aside. A read that set anything aside returns `window_selector {applied, ignored, note}`; when that includes `include_content` or `content_only`, the note says the window is not the page's content and that edits go through `edit_page`.
- get_page's tool description states the order, and the four selector descriptions drop "One window selector only". `docs/guides/windowed-reads.md` and `docs/mcp/TOOL_REFERENCE.md` describe the rule.
-- Tests: `test/tool-args-empty-optional-sol.test.ts` replays Sol's recorded argument shape on every entry point (MCP over HTTP and stdio, `gbrain call`, the subagent registry and both SkillOpt registries). `test/get-page-body-modes.test.ts` checks the order, that the read equals the applied selector sent alone (`edit_target` included), and that a whole-page ask beside a selector returns no page body.
+- Tests: `test/tool-args-empty-optional-sol.test.ts` replays Sol's recorded argument shape on every entry point (MCP over HTTP and stdio, `gbrain call`, the subagent registry and both SkillOpt registries). `test/get-page-body-modes.test.ts` checks the order, that the read equals the applied selector sent alone (`edit_target` included), that a whole-page ask beside a selector returns no page body, and that a failed cursor or stale chunk falls through to the next selector.
## [0.60.569.0] - 2026-11-04
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 6c8ce35311..543cf73910 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -51,4 +51,4 @@ Writes that change part of a page in time proportional to the change (Wave B spe
- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end (`read-range.ts` `hiddenBefore`).
Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.
-- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (a selector → window, setting aside body full/include_content/content_only beside it; else explicit body; include_content/content_only → full; the thin client and the local CLI → full; else auto). Several selectors read one window, `SELECTOR_ORDER` cursor > around_chunk_id > lines > bytes (GBRA-280); an around_chunk_id not on the page falls back to the next one (`fallback`), and the response's `window_selector {applied, ignored, note}` reports what was set aside. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` for local and MCP callers alike with `segmentedReadFix` (`body: 'auto'`, argv and mcp; local `gbrain get` with no `--body` streams it instead), and `page_too_large_for_inline` only for gbrain's thin client, its paging signal (`segmentedFullReadError`); `grammar_diagnostics` on it is `line_grammar: { state: 'skipped', reason: 'page_body_segmented' }` (`segmentedGrammarSkip`, line-grammar-report.ts); window byte offsets are coordinates of the view's `size.total_bytes`, never `body_bytes`, and an offset past the end is an empty window on both storages; `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts. `section`/`grep`: `ops/get-page-slice.ts` ([continued](core-services-2-continued.md)).
+- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (a selector → window, setting aside body full/include_content/content_only beside it; else explicit body; include_content/content_only → full; the thin client and the local CLI → full; else auto). Several selectors read one window, `SELECTOR_ORDER` cursor > around_chunk_id > lines > bytes (GBRA-280); an around_chunk_id not on the page falls back to the next one (`fallbacks`, tried in order: a cursor for another page or view, or issued before the page changed, falls back too, and `view: markdown` drops around_chunk_id beside another selector), and the response's `window_selector {applied, ignored, note}` reports what was set aside. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` for local and MCP callers alike with `segmentedReadFix` (`body: 'auto'`, argv and mcp; local `gbrain get` with no `--body` streams it instead), and `page_too_large_for_inline` only for gbrain's thin client, its paging signal (`segmentedFullReadError`); `grammar_diagnostics` on it is `line_grammar: { state: 'skipped', reason: 'page_body_segmented' }` (`segmentedGrammarSkip`, line-grammar-report.ts); window byte offsets are coordinates of the view's `size.total_bytes`, never `body_bytes`, and an offset past the end is an empty window on both storages; `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts. `section`/`grep`: `ops/get-page-slice.ts` ([continued](core-services-2-continued.md)).
diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.md
index 4078d451c5..4be87773b2 100644
--- a/docs/guides/windowed-reads.md
+++ b/docs/guides/windowed-reads.md
@@ -42,8 +42,12 @@ with a partial mode and no selector, is `invalid_params` with an example. With
several selectors, one window is read: `cursor`, then `around_chunk_id`, then
`lines`, then `bytes`. `body: "full"`, `include_content` and `content_only` beside a
selector are set aside too, so the read is still a window, never the whole page.
-An `around_chunk_id` whose chunk is no longer on the page gives way to the next
-selector. The response's `window_selector {applied, ignored, note}` says what was
+A cursor that can't read this page (another page's, another view's, or issued
+before the page changed) or an `around_chunk_id` whose chunk is no longer on the
+page gives way to the next selector; with `view: "markdown"`, `around_chunk_id`
+beside another selector is set aside. When `include_content` or `content_only` is
+set aside, the note says the window is not the page's content, so edit it with
+`edit_page` and `edit_target` rather than putting it back with `put_page`. The response's `window_selector {applied, ignored, note}` says what was
read and what was set aside; a call with one selector has no `window_selector`. A window response
carries `window {text, byte_start, byte_end, line_start, line_end}`,
`size {total_bytes, total_lines}`, `truncated`, and when more follows
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index 191365462c..61d6cf5b65 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -186,7 +186,7 @@ Read a page by slug (supports optional fuzzy matching). Slug aliases left by ren
| `grep` | string | Only the paragraphs containing this text (case-insensitive substring, not a regex), with line numbers and `total_matches`. Accepted on the starter surface; advertised on full. |
| `context` | number | Applies only with grep (ignored without it): paragraphs of context either side (default 1, max 5). |
-The window parameters (`lines`, `bytes`, `around_chunk_id`, `cursor`) are advertised on the full surface. With several, one window is read: `cursor`, then `around_chunk_id`, then `lines`, then `bytes` (an `around_chunk_id` no longer on the page gives way to the next), and `body: "full"`, `include_content` and `content_only` beside a selector are set aside. The response's `window_selector` names what applied and what was ignored.
+The window parameters (`lines`, `bytes`, `around_chunk_id`, `cursor`) are advertised on the full surface. With several, one window is read: `cursor`, then `around_chunk_id`, then `lines`, then `bytes` (a cursor that can't read this page and an `around_chunk_id` no longer on it give way to the next, and `view: "markdown"` sets `around_chunk_id` aside beside another selector), and `body: "full"`, `include_content` and `content_only` beside a selector are set aside. The response's `window_selector` names what applied and what was ignored.
## `get_recent_salience`
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 71fcc33351..109a36330b 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1422,7 +1422,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.563.0', id: 'degraded_stamp_gbra200', text: 'Every degraded or partial read result now carries one stamp naming why with stable codes: an MCP result gets `_meta.degraded: { reasons: [...] }` and one extra text block, `[gbrain degraded: <reasons>] ...`, after the others; a CLI `--json` object gets a `degraded` key, and other CLI output (human text, a bare `--json` array such as search results) gets that line on stderr. It covers search, query, recall, find_experts, context_pack, delta, entity, get_page (`file_held`), think and synthesize, search_exact, open_loops and rank_entities. recall and think no longer drop their page search\'s degraded stages (an embed timeout, a failed arm, the keyword rank bound): recall reports them in `_meta.retrieval.degraded` and its `degraded_recall` notice, think and synthesize as `GATHER_DEGRADED:<stage>` warnings, and a keyword-only search or recall on Postgres reports `keyword_candidates_incomplete` when the rank bound applies. A clean result carries no stamp, and no existing field changed.' },
{ since: '0.60.569.0', id: 'skillopt_loop_deprecated_gst1251', text: 'SkillOpt\'s iterative loop is deprecated and is removed on or after 2026-12-03: `gbrain skillopt` with its loop flag, a resumed run the loop started, `run_skillopt` with `optimizer_mode: "reflect"` and a queued `skillopt` job in loop mode (including one queued before the one-shot default, which carries no mode), whose notice goes to the worker\'s stderr, each print the `skillopt_loop_deprecated` coaching notice once (MCP: once per session, muteable) and otherwise run exactly as before. The default one-shot rewrite, the cycle phase and every flag and config key are unchanged. Nothing replaces the loop: edit the skill directly, or run the default one-shot rewrite.' },
// GBRA-280 (GBEV-30 re-read) get_page window-selector precedence; release:restamp stamps since at the merge slot.
- { since: '0.60.570.0', id: 'get_page_selector_precedence_gbra280', text: 'get_page given several window selectors now reads one window instead of refusing with invalid_params: cursor, then around_chunk_id, then lines, then bytes, and an around_chunk_id no longer on the page gives way to the next. body full, include_content and content_only beside a selector are set aside, so the read stays a window and never returns the whole page. The response\'s window_selector names what applied and what was ignored; a call with one selector is unchanged.' },
+ { since: '0.60.570.0', id: 'get_page_selector_precedence_gbra280', text: 'get_page given several window selectors now reads one window instead of refusing with invalid_params: cursor, then around_chunk_id, then lines, then bytes, and a cursor that cannot read the page or an around_chunk_id no longer on it gives way to the next. body full, include_content and content_only beside a selector are set aside, so the read stays a window and never returns the whole page. The response\'s window_selector names what applied and what was ignored; a call with one selector is unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.ts
index 13981ed48e..c99481e79d 100644
--- a/src/core/ops/get-page-body.ts
+++ b/src/core/ops/get-page-body.ts
@@ -93,23 +93,25 @@ type Selector =
/** Several window selectors: the first of these applies, most specific first (GBRA-280: GPT-6.1 Sol sends them all and never followed the refusal's fix). */
const SELECTOR_ORDER: readonly Selector['kind'][] = ['cursor', 'around', 'lines', 'bytes'];
const PRECEDENCE_NOTE = 'get_page reads one window: cursor, then around_chunk_id, then lines, then bytes.';
+const CONTENT_SET_ASIDE_NOTE = "This window is not the page's content: put_page with it would replace the whole page with this window, so edit through edit_page with edit_target, or read with include_content alone.";
const selectorParam = (s: Selector) => (s.kind === 'around' ? 'around_chunk_id' : s.kind);
/** The response's account of a read that set window arguments aside: what applied, what was ignored, and the rule. */
-function selectorNote(applied: Selector, ignored: string[], staleChunk?: number): { applied: string; ignored: string[]; note: string } {
+function selectorNote(applied: Selector, ignored: string[], failed: Array<[string, string]> = []): { applied: string; ignored: string[]; note: string } {
const list = (ks: string[]) => ks.length > 1 ? `${ks.slice(0, -1).join(', ')} and ${ks[ks.length - 1]}` : ks[0]!;
- const rest = ignored.filter(k => staleChunk === undefined || k !== 'around_chunk_id');
- const what = staleChunk === undefined
- ? `Read the ${selectorParam(applied)} window; ignored ${list(rest)}`
- : `around_chunk_id ${staleChunk} is not on this page at its current revision, so this is the ${selectorParam(applied)} window${rest.length ? `; ignored ${list(rest)}` : ''}`;
- return { applied: selectorParam(applied), ignored, note: `${what}. ${PRECEDENCE_NOTE}` };
+ const rest = ignored.filter(k => !failed.some(([key]) => key === k));
+ const what = failed.length
+ ? `${failed.map(([, why]) => why).join('; ')}, so this is the ${selectorParam(applied)} window${rest.length ? `; ignored ${list(rest)}` : ''}`
+ : `Read the ${selectorParam(applied)} window; ignored ${list(rest)}`;
+ const notContent = ignored.includes('include_content') || ignored.includes('content_only') ? `${CONTENT_SET_ASIDE_NOTE} ` : '';
+ return { applied: selectorParam(applied), ignored, note: `${what}. ${notContent}${PRECEDENCE_NOTE}` };
}
export interface BodyRequest {
mode: BodyMode;
selector?: Selector;
- /** The next selector by precedence: applies when an around_chunk_id selector's chunk is not on the page. */
- fallback?: Selector;
+ /** The remaining selectors by precedence, tried in order when a cursor or around_chunk_id cannot read this page at its current revision. */
+ fallbacks?: Selector[];
/** Window arguments the read set aside: lower-precedence selectors, and body 'full', include_content or content_only beside a selector. */
ignored?: string[];
view: WindowView;
@@ -159,7 +161,10 @@ export function parseBodyRequest(ctx: Pick<OperationContext, 'remote' | 'transpo
selectors.push({ kind: 'cursor', raw: p.cursor });
}
selectors.sort((a, b) => SELECTOR_ORDER.indexOf(a.kind) - SELECTOR_ORDER.indexOf(b.kind));
- const ignored: string[] = selectors.slice(1).map(selectorParam);
+ const view = p.view === undefined ? 'read' : p.view;
+ if (view !== 'read' && view !== 'markdown') throw invalidParam(ctx, 'get_page', 'view', "get_page: view must be 'read' or 'markdown'.", { choices: ['read', 'markdown'], example: 'markdown' });
+ const usable = view === 'markdown' && selectors.length > 1 ? selectors.filter(s => s.kind !== 'around') : selectors;
+ const ignored: string[] = selectors.filter(s => s !== usable[0]).map(selectorParam);
const includeContent = p.include_content === true;
const contentOnly = p.content_only === true;
let mode: BodyMode;
@@ -177,9 +182,7 @@ export function parseBodyRequest(ctx: Pick<OperationContext, 'remote' | 'transpo
} else if (includeContent || contentOnly) mode = 'full';
else if (ctx.thinClient === true || ctx.remote === false) mode = 'full';
else mode = 'auto';
- const view = p.view === undefined ? 'read' : p.view;
- if (view !== 'read' && view !== 'markdown') throw invalidParam(ctx, 'get_page', 'view', "get_page: view must be 'read' or 'markdown'.", { choices: ['read', 'markdown'], example: 'markdown' });
- if (view === 'markdown' && (mode !== 'window' || selectors[0]?.kind === 'around')) {
+ if (view === 'markdown' && (mode !== 'window' || usable[0]?.kind === 'around')) {
throw bad('view', "get_page: view: 'markdown' pages the round-trip markdown with body: 'window' and a lines, bytes or cursor selector.", { slug: 'notes/acme-example-log', body: 'window', view: 'markdown', bytes: { offset: 0, length: 1_000_000 } });
}
let maxBytes: number | undefined;
@@ -197,7 +200,7 @@ export function parseBodyRequest(ctx: Pick<OperationContext, 'remote' | 'transpo
if (!int(p.outline_from) || p.outline_from < 0) throw bad('outline_from', 'get_page: outline_from must be a non-negative integer (the previous next_from_index).', 100);
outlineFrom = p.outline_from;
}
- return { mode, ...(selectors[0] ? { selector: selectors[0] } : {}), ...(selectors[1] ? { fallback: selectors[1] } : {}), ...(ignored.length ? { ignored } : {}), view, ...(maxBytes !== undefined ? { maxBytes } : {}), contextLines, outlineFrom,
+ return { mode, ...(usable[0] ? { selector: usable[0] } : {}), ...(usable.length > 1 ? { fallbacks: usable.slice(1) } : {}), ...(ignored.length ? { ignored } : {}), view, ...(maxBytes !== undefined ? { maxBytes } : {}), contextLines, outlineFrom,
legacyThin: typeof body !== 'string' && ctx.thinClient === true && !includeContent && !contentOnly && !selectors.length };
}
@@ -546,27 +549,44 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI
// window: chosen, then measured as the final encoded frame; text that escapes heavily shrinks the window until it fits.
let sel = req.selector;
- if (sel && req.ignored) out.window_selector = selectorNote(sel, req.ignored);
+ const fallbacks = [...(req.fallbacks ?? [])];
+ const failed: Array<[string, string]> = [];
+ const note = (applied: Selector) => {
+ const ignored = [selectorParam(req.selector!), ...(req.ignored ?? [])].filter(k => k !== selectorParam(applied));
+ out.window_selector = selectorNote(applied, ignored, failed);
+ };
+ if (sel && req.ignored) note(sel);
let cursorMax = req.maxBytes ?? DEFAULT_WINDOW_BYTES;
const select = async (maxBytes: number): Promise<WindowSlice | null> => {
+ const fallBack = (e: unknown, key: string, why: string): Promise<WindowSlice | null> => {
+ const next = fallbacks.shift();
+ if (!next) throw e;
+ failed.push([key, why]);
+ sel = next;
+ note(next);
+ return select(maxBytes);
+ };
if (!sel) return doc.from(0, maxBytes);
if (sel.kind === 'lines') return doc.lines(sel.from, sel.count, maxBytes);
if (sel.kind === 'bytes') return doc.bytes(sel.offset, Math.min(sel.length, maxBytes));
if (sel.kind === 'cursor') {
const c = decodeCursor(sel.raw);
if (!c || c.page_id !== page.id) {
- throw invalidParam(ctx, 'get_page', 'cursor', `get_page: cursor is not a window cursor for page ${page.slug}.`, { example: 'gpw1.…' });
+ return fallBack(invalidParam(ctx, 'get_page', 'cursor', `get_page: cursor is not a window cursor for page ${page.slug}.`, { example: 'gpw1.…' }),
+ 'cursor', 'the cursor is not a window cursor for this page');
}
if (c.view !== req.view) {
- throw invalidParam(ctx, 'get_page', 'view', `get_page: this cursor pages view '${c.view}'; pass view: '${c.view}' with it.`, { choices: ['read', 'markdown'], example: c.view });
+ return fallBack(invalidParam(ctx, 'get_page', 'view', `get_page: this cursor pages view '${c.view}'; pass view: '${c.view}' with it.`, { choices: ['read', 'markdown'], example: c.view }),
+ 'cursor', `the cursor pages view '${c.view}'`);
}
if (c.revision !== revision) {
const position = Math.min(c.offset, doc.total);
- throw opError('revision_changed', `Page ${page.slug} changed since this cursor was issued (revision ${c.revision}, now ${revision}).`,
+ return fallBack(opError('revision_changed', `Page ${page.slug} changed since this cursor was issued (revision ${c.revision}, now ${revision}).`,
`Continue from the same byte offset at the current revision (bytes: { offset: ${position}, length: ${c.max_bytes} }), or start over from the outline.`,
{ legacy_error: 'invalid_params', detail: JSON.stringify({ revision, cursor_revision: c.revision, offset: position }),
fix: readFix('Reads on from the same byte offset at the current revision.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],
- mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'window', ...(markdown ? { view: 'markdown' } : {}), bytes: { offset: position, length: c.max_bytes } } } }) });
+ mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'window', ...(markdown ? { view: 'markdown' } : {}), bytes: { offset: position, length: c.max_bytes } } } }) }),
+ 'cursor', 'the page changed since the cursor was issued');
}
cursorMax = c.max_bytes;
return doc.from(c.offset, Math.min(c.max_bytes, maxBytes));
@@ -575,11 +595,8 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI
let around: Awaited<ReturnType<typeof aroundChunk>>;
try { around = await aroundChunk(ctx, page, doc, chunkId, req.contextLines, maxBytes, revision); }
catch (e) {
- if (!req.fallback || !(e instanceof OperationError) || (e.canonical ?? e.code) !== 'revision_changed') throw e;
- const next = req.fallback;
- sel = next;
- out.window_selector = selectorNote(next, ['around_chunk_id', ...(req.ignored ?? []).filter(k => k !== 'around_chunk_id' && k !== selectorParam(next))], chunkId);
- return select(maxBytes);
+ if (!(e instanceof OperationError) || (e.canonical ?? e.code) !== 'revision_changed') throw e;
+ return fallBack(e, 'around_chunk_id', `around_chunk_id ${chunkId} is not on this page at its current revision`);
}
out.anchor = around.anchor;
if (around.span) out.chunk_span = around.span;
diff --git a/test/get-page-body-modes.test.ts b/test/get-page-body-modes.test.ts
index 64c74ccd63..b1934a49f9 100644
--- a/test/get-page-body-modes.test.ts
+++ b/test/get-page-body-modes.test.ts
@@ -167,6 +167,53 @@ describe('several window selectors (GBRA-280)', () => {
const r = await get(local(), { slug: 'logs/big', lines: { from: 100, count: 3 }, bytes: { offset: 0, length: 10 } });
expect([r.window.line_start, r.window_selector.applied]).toEqual([100, 'lines']);
});
+ test('a cursor that cannot read this page gives way to the next selector: another page, another view, an older revision', async () => {
+ await put('logs/sel-other', conversation(6000));
+ const foreign = (await get(ctx(), { slug: 'logs/big', body: 'window', max_bytes: 30_000 })).next_cursor;
+ const lines = { from: 7, count: 3 };
+ const a = await get(ctx(), { slug: 'logs/sel-other', cursor: foreign, lines, max_bytes: 30_000 });
+ expect([a.window.line_start, a.window_selector.applied, a.window_selector.ignored]).toEqual([7, 'lines', ['cursor']]);
+ expect(a.window_selector.note).toBe('the cursor is not a window cursor for this page, so this is the lines window. get_page reads one window: cursor, then around_chunk_id, then lines, then bytes.');
+ const readCursor = (await get(ctx(), { slug: 'logs/sel-other', body: 'window', max_bytes: 30_000 })).next_cursor;
+ const b = await get(ctx(), { slug: 'logs/sel-other', view: 'markdown', cursor: readCursor, lines, max_bytes: 30_000 });
+ expect([b.view, b.window.line_start, b.window_selector.applied]).toEqual(['markdown', 7, 'lines']);
+ expect(b.window_selector.note).toStartWith("the cursor pages view 'read', so this is the lines window.");
+ await put('logs/sel-other', conversation(6001));
+ const c = await get(ctx(), { slug: 'logs/sel-other', cursor: readCursor, bytes: { offset: 0, length: 2000 }, max_bytes: 30_000 });
+ expect([c.window.byte_start, c.window_selector.applied, c.window_selector.ignored]).toEqual([0, 'bytes', ['cursor']]);
+ expect(c.window_selector.note).toStartWith('the page changed since the cursor was issued, so this is the bytes window.');
+ await expectCode(get(ctx(), { slug: 'logs/sel-other', cursor: readCursor }), 'revision_changed');
+ });
+
+ test('a failed cursor and a stale around_chunk_id fall through to lines, and a stale around_chunk_id falls back to bytes', async () => {
+ const foreign = (await get(ctx(), { slug: 'logs/big', body: 'window', max_bytes: 30_000 })).next_cursor;
+ await put('logs/sel-chain', conversation(6000));
+ const r = await get(ctx(), { slug: 'logs/sel-chain', cursor: foreign, around_chunk_id: 999_999, lines: { from: 4, count: 2 }, body: 'full', max_bytes: 30_000 });
+ expect([r.window.line_start, r.window_selector.applied, r.window_selector.ignored]).toEqual([4, 'lines', ['cursor', 'around_chunk_id', 'body']]);
+ expect(r.window_selector.note).toBe('the cursor is not a window cursor for this page; around_chunk_id 999999 is not on this page at its current revision, so this is the lines window; ignored body. get_page reads one window: cursor, then around_chunk_id, then lines, then bytes.');
+ const b = await get(ctx(), { slug: 'logs/sel-chain', around_chunk_id: 999_999, bytes: { offset: 0, length: 2000 } });
+ expect([b.window.byte_start, b.window_selector.applied, b.window_selector.ignored]).toEqual([0, 'bytes', ['around_chunk_id']]);
+ });
+
+ test("view 'markdown' sets around_chunk_id aside when another selector came with it, and refuses it alone", async () => {
+ const chunkId = await chunk('logs/big');
+ const r = await get(ctx(), { slug: 'logs/big', view: 'markdown', around_chunk_id: chunkId, lines: { from: 100, count: 3 }, bytes: { offset: 0, length: 10 } });
+ expect([r.view, r.window.line_start, r.window_selector.applied, r.window_selector.ignored]).toEqual(['markdown', 100, 'lines', ['around_chunk_id', 'bytes']]);
+ await expectCode(get(ctx(), { slug: 'logs/big', view: 'markdown', around_chunk_id: chunkId }), 'invalid_params');
+ });
+
+ test("body 'auto' beside several selectors reads the first one's window", async () => {
+ const r = await get(ctx(), { slug: 'logs/big', body: 'auto', lines: { from: 100, count: 3 }, bytes: { offset: 0, length: 10 } });
+ expect([r.body, r.window.line_start, r.window_selector.applied]).toEqual(['window', 100, 'lines']);
+ });
+
+ test('a set-aside include_content or content_only says the window is not the page and how to edit it', async () => {
+ const r = await get(ctx(), { slug: 'logs/big', include_content: true, lines: { from: 100, count: 3 } });
+ expect(r.window_selector.note).toBe("Read the lines window; ignored include_content. This window is not the page's content: put_page with it would replace the whole page with this window, so edit through edit_page with edit_target, or read with include_content alone. get_page reads one window: cursor, then around_chunk_id, then lines, then bytes.");
+ const lines = await get(ctx(), { slug: 'logs/big', lines: { from: 100, count: 3 }, bytes: { offset: 0, length: 10 } });
+ expect(lines.window_selector.note).not.toContain('put_page');
+ });
+
});
describe('windows', () => {
diff --git a/test/tool-args-empty-optional-sol.test.ts b/test/tool-args-empty-optional-sol.test.ts
index 513c96a87e..404f9b66e4 100644
--- a/test/tool-args-empty-optional-sol.test.ts
+++ b/test/tool-args-empty-optional-sol.test.ts
@@ -294,7 +294,7 @@ describe("GST-927: GBEV-3's replayed Sol shapes", () => {
expect(r.compiled_truth).toBeUndefined();
expect(r.content).toBeUndefined();
expect(r.window_selector).toEqual({ applied: 'around_chunk_id', ignored: ['lines', 'bytes', 'body', 'include_content'],
- note: 'Read the around_chunk_id window; ignored lines, bytes, body and include_content. get_page reads one window: cursor, then around_chunk_id, then lines, then bytes.' });
+ note: "Read the around_chunk_id window; ignored lines, bytes, body and include_content. This window is not the page's content: put_page with it would replace the whole page with this window, so edit through edit_page with edit_target, or read with include_content alone. get_page reads one window: cursor, then around_chunk_id, then lines, then bytes." });
});
test('lines beside bytes reads the lines window; an around_chunk_id not on the page falls back to the next selector', async () => {