Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ops): agent-contract fixes for context, pages, search, code-intel, insights and facts ops (B2/B6/B7/B8)
garrytandb17f07948a0
diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.tsindex 287717c441..c866d5942b 100644--- a/src/core/ops/code-intel.ts+++ b/src/core/ops/code-intel.ts@@ -9,8 +9,10 @@*/import type { Operation, OperationContext } from './contract.ts';-import { OperationError } from './contract.ts';+import { opError, type OperationError } from './contract.ts';import { routeCodeIntelScope, readPolicyOpts } from './context.ts';+import { hostOnlyError } from './op-fix.ts';+import { isValidSourceId } from '../source-id.ts';import type { WalkResult } from '../code-intel/recursive-walk.ts';import {CODE_CALLERS_DESCRIPTION,@@ -53,7 +55,7 @@ const code_callers: Operation = {// Single trust+grant resolver + federated code-source re-route (see// routeCodeIntelScope): remote callers can't span sources outside their// grant, and `__all__` collapses to their grant (not the whole brain).- const { allSources, sourceId } = await routeCodeIntelScope(ctx, sourceIdParam, p.all_sources === true);+ const { allSources, sourceId } = await routeCodeIntelScope(ctx, sourceIdParam, p.all_sources === true, 'code_callers');const edges = await ctx.engine.getCallersOf(symbol, {limit,allSources,@@ -93,7 +95,7 @@ const code_callees: Operation = {const limit = (p.limit as number) ?? 100;const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;// Single trust+grant resolver + federated re-route (see code_callers).- const { allSources, sourceId } = await routeCodeIntelScope(ctx, sourceIdParam, p.all_sources === true);+ const { allSources, sourceId } = await routeCodeIntelScope(ctx, sourceIdParam, p.all_sources === true, 'code_callees');const edges = await ctx.engine.getCalleesOf(symbol, {limit,allSources,@@ -223,7 +225,7 @@ const code_blast: Operation = {// source outside its grant (pre-fix this scoped by bare ctx.sourceId only).// Falls back to ctx.sourceId (a required string) for the trusted-local case,// exactly preserving pre-fix local behavior.- const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);+ const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined, false, 'code_blast');const sourceId = scopedSourceId ?? ctx.sourceId;const walk = await runRecursiveWalk(ctx.engine, symbol, {direction: 'callers',@@ -258,7 +260,7 @@ const code_flow: Operation = {const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);const exact = (p.exact as boolean) ?? false;// Single trust+grant resolver (see code_blast).- const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);+ const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined, false, 'code_flow');const sourceId = scopedSourceId ?? ctx.sourceId;const walk = await runRecursiveWalk(ctx.engine, symbol, {direction: 'callees',@@ -305,6 +307,27 @@ const code_traversal_cache_clear: Operation = {cliHints: { name: 'code_traversal_cache_clear', hidden: true },};+const SYMBOL_ARG = /^[A-Za-z_$][\w$.:/-]{0,199}$/;++/**+ * B6: remote code reads are suspended; the same read runs through the+ * trusted local `gbrain call` lane on the brain host. The symbol and source+ * are interpolated only when they match strict id shapes.+ */+function codeReadRefusal(ctx: OperationContext, op: Operation, params: Record<string, unknown>): OperationError {+ const message = `${op.name} is temporarily unavailable to agent callers. Use the trusted local CLI for code reads.`;+ const key = 'entry_point' in op.params ? 'entry_point' : 'symbol';+ const symbol = params[key];+ if (typeof symbol !== 'string' || !SYMBOL_ARG.test(symbol)) {+ return opError('permission_denied', message,+ `Code reads over MCP are suspended; ask the user to run ${op.name} with the trusted local CLI on the brain host (gbrain call ${op.name}).`);+ }+ const source = typeof params.source_id === 'string' && isValidSourceId(params.source_id) ? ['--source', params.source_id] : [];+ return hostOnlyError(ctx, 'permission_denied', message,+ ['gbrain', 'call', ...source, op.name, JSON.stringify({ [key]: symbol })],+ 'Raw code fragments do not yet support the remote read policy, so code reads run only through the trusted local CLI on the brain host.');+}+const codeReadOperations: Operation[] = [code_callers, code_callees, code_def, code_refs,code_blast, code_flow,@@ -317,10 +340,7 @@ export const codeIntelOperations: Operation[] = [...op,description: `${op.description} Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.`,handler: async (ctx, params) => {- if (ctx.remote !== false) {- throw new OperationError('permission_denied',- `${op.name} is temporarily unavailable to agent callers. Use the trusted local CLI for code reads.`);- }+ if (ctx.remote !== false) throw codeReadRefusal(ctx, op, params);return op.handler(ctx, params);},})),diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex bb7e440b37..acf219f36f 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -12,8 +12,10 @@import { lstatSync, realpathSync } from 'fs';import { resolve, relative, sep } from 'path';-import { OperationError } from './contract.ts';+import { OperationError, opError } from './contract.ts';import type { AuthInfo, Operation, OperationContext } from './contract.ts';+import type { Action } from '../agent-output.ts';+import { hostFix, invalidParam, paramUse, readFix } from './op-fix.ts';import { CJK_SLUG_CHARS, SLUG_WORD_CHARS } from '../cjk.ts';import { ALL_SOURCES, NO_SOURCES, isValidSourceId } from '../source-id.ts';import { encodeDeepResearchId } from '../deep-research-id.ts';@@ -23,6 +25,103 @@ import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from 'import type { SearchResult, HybridSearchMeta, PageReadScope, PageReadPolicy } from '../types.ts';import { resolveExcludePrivatePages, isPrivatePage } from '../search/private-visibility.ts';+// --- Agent-contract fixes shared by the op error sites ---++/**+ * A slug safe to put in a fix's argv as a positional: the op CLI parser does+ * not honour `--`, so only slugs that cannot read as a flag (or carry shell+ * or Unicode surprises) are interpolated; anything else gets no slug fix.+ */+export function cliSafeSlug(slug: unknown): slug is string {+ return typeof slug === 'string' && /^[a-z0-9][a-z0-9._/:-]{0,254}$/i.test(slug);+}++/** Read-only: the sources this caller can read (MCP sources_list is grant-confined). */+export function sourcesListFix(why: string): Action {+ return readFix(why, { argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} } });+}++/** Read-only: one page by slug, scoped to a source when known. */+export function getPageFix(slug: string, why: string, opts: { sourceId?: string; includeDeleted?: boolean; fuzzy?: boolean } = {}): Action | undefined {+ if (!cliSafeSlug(slug)) return undefined;+ const source = opts.sourceId !== undefined && isValidSourceId(opts.sourceId) ? opts.sourceId : undefined;+ return readFix(why, {+ argv: ['gbrain', 'get', slug, ...(opts.includeDeleted ? ['--include-deleted'] : []), ...(opts.fuzzy ? ['--fuzzy'] : []), ...(source ? ['--source', source] : [])],+ mcp: { tool: 'get_page', arguments: { slug, ...(opts.includeDeleted ? { include_deleted: true } : {}), ...(opts.fuzzy ? { fuzzy: true } : {}), ...(source ? { source_id: source } : {}) } },+ });+}++/** opError options carrying a fix only when one could be built. */+export function withFix(fix: Action | undefined): { fix?: Action } {+ return fix ? { fix } : {};+}++/**+ * get_page's miss (#4516): where the slug lives when a trusted local probe+ * found it in another source, otherwise the soft-delete / fuzzy check, as+ * surface-correct prose plus the matching read.+ */+export function pageNotFoundError(+ ctx: Pick<OperationContext, 'remote' | 'transport'>,+ slug: string,+ opts: { includeDeleted: boolean; sourceIdParam?: string; elsewhereSource?: string },+): OperationError {+ const retry = opts.includeDeleted ? `Check the slug or use ${paramUse(ctx, 'fuzzy')}` : `Page may be soft-deleted; pass ${paramUse(ctx, 'include_deleted')} to verify`;+ const where = opts.elsewhereSource;+ const explicit = opts.sourceIdParam !== ALL_SOURCES ? opts.sourceIdParam : undefined;+ return opError('page_not_found', `Page not found: ${slug}`,+ where !== undefined ? `Page exists in source '${where}' — pass ${paramUse(ctx, 'source', where)}. ${retry}` : retry,+ withFix(where !== undefined+ ? getPageFix(slug, `Reads the page from source ${where}, where it exists.`, { sourceId: where })+ : getPageFix(slug, opts.includeDeleted ? 'Fuzzy-matches the slug.' : 'Shows the page if it is soft-deleted (deleted_at set).',+ { sourceId: explicit, ...(opts.includeDeleted ? { fuzzy: true } : { includeDeleted: true }) })));+}++const HTTP_HOST = { remote: true, transport: 'http' } as const;+const TOKEN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const CLIENT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;++/** The OAuth client id when it is safe to name in a command. */+function safeClientId(auth: Pick<AuthInfo, 'clientId' | 'principal'> | undefined): string | undefined {+ return auth?.principal?.kind === 'oauth_client' && CLIENT_ID_RE.test(auth.clientId) ? auth.clientId : undefined;+}++/**+ * B5/B6: the brain host operator's grant change for this connection (token+ * flags or client flags), or the grant listing when the principal cannot be+ * named. Credential-bearing callers reach the server over HTTP.+ */+function grantFix(+ auth: Pick<AuthInfo, 'clientId' | 'principal'> | undefined,+ change: { token: string[]; client: string[] },+ why: string,+ inputs?: Action['inputs'],+): Action {+ const principal = auth?.principal;+ const clientId = safeClientId(auth);+ const target = principal?.kind === 'legacy_token' && TOKEN_ID_RE.test(principal.id)+ ? ['rescope-token', '--id', principal.id, ...change.token]+ : clientId ? ['rescope-client', clientId, ...change.client] : null;+ if (!target) {+ return hostFix(HTTP_HOST, principal?.kind === 'oauth_client' ? ['gbrain', 'auth', 'clients', '--json'] : ['gbrain', 'auth', 'list'],+ 'Lists the grants so the operator can find and widen this connection.');+ }+ return { ...hostFix(HTTP_HOST, ['gbrain', 'auth', ...target], why, { consent: ['credentials'] }), ...(inputs ? { inputs } : {}) };+}++/** Grant at least one readable source to this connection (value supplied by the user). */+function sourceGrantFix(auth: Pick<AuthInfo, 'clientId' | 'principal'> | undefined): Action {+ return grantFix(auth, { token: ['--sources', '<sources>'], client: ['--federated-read', '<sources>'] },+ 'Grants this connection the sources it may read; only the brain host operator can change grants.',+ [{ name: 'sources', how: 'Ask the user which source ids this connection should read (comma-separated; `gbrain sources list` on the brain host shows them).' }]);+}++/** Pending schema migrations on the brain host restore a degraded grant/fence projection. */+function migrationsFix(ctx: Pick<OperationContext, 'remote' | 'transport'>): Action {+ return hostFix(ctx, ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'],+ 'The oauth_clients projection predates the grant columns; applying the pending migrations lets the fence be evaluated again.');+}+// --- Upload validators (Fix 1 / B5 / H5 / M4) ---/**@@ -48,14 +147,17 @@ export function validateUploadPath(filePath: string, root: string, strict = true} catch (e: unknown) {const msg = e instanceof Error ? e.message : String(e);if (msg.includes('ENOENT')) {- throw new OperationError('invalid_params', `File not found: ${filePath}`);+ throw opError('invalid_params', `File not found: ${filePath}`,+ 'Pass the path of an existing file; a relative path resolves against the working directory of the process running gbrain.');}- throw new OperationError('invalid_params', `Cannot resolve path: ${filePath}`);+ throw opError('invalid_params', `Cannot resolve path: ${filePath}`,+ 'Pass a readable regular file: the path or one of its parent directories could not be resolved (permissions or a broken link).');}// Always reject final-component symlinks (basic safety for both modes).try {if (lstatSync(resolve(filePath)).isSymbolicLink()) {- throw new OperationError('invalid_params', `Symlinks are not allowed for upload: ${filePath}`);+ throw opError('invalid_params', `Symlinks are not allowed for upload: ${filePath}`,+ "Pass the link's real target path instead of the symlink (`realpath` prints it).");}} catch (e) {if (e instanceof OperationError) throw e;@@ -69,11 +171,13 @@ export function validateUploadPath(filePath: string, root: string, strict = truetry {realRoot = realpathSync(root);} catch {- throw new OperationError('invalid_params', `Confinement root not accessible: ${root}`);+ throw opError('invalid_params', `Confinement root not accessible: ${root}`,+ "The upload root (the server's working directory) is unreadable on the brain host; tell the user so its operator can fix that directory.");}const rel = relative(realRoot, real);if (rel === '' || rel.startsWith('..') || rel.startsWith(`..${sep}`) || resolve(realRoot, rel) !== real) {- throw new OperationError('invalid_params', `Upload path must be within the working directory: ${filePath}`);+ throw opError('invalid_params', `Upload path must be within the working directory: ${filePath}`,+ "Copy the file under the server's working directory and pass that path; a symlinked parent that resolves outside it is refused too.");}return real;}@@ -109,16 +213,17 @@ const OP_PAGE_SLUG_SEG = `${OP_PAGE_SLUG_PART}(?::${OP_PAGE_SLUG_PART})*`;*/export function validatePageSlug(slug: string): void {if (typeof slug !== 'string' || slug.length === 0) {- throw new OperationError('invalid_params', 'page_slug must be a non-empty string');+ throw opError('invalid_params', 'page_slug must be a non-empty string', 'Pass a slug such as people/alice-example.');}if (slug.length > 255) {- throw new OperationError('invalid_params', 'page_slug exceeds 255 characters');+ throw opError('invalid_params', 'page_slug exceeds 255 characters', 'Shorten the slug to 255 characters or fewer.');}// #3417: letters/numbers from any script allowed in segments (u flag required// for the \p{...} classes in OP_PAGE_SLUG_SEG). Shape rules (word-char lead,// dot/underscore/hyphen continuation) preserved.if (!new RegExp(`^${OP_PAGE_SLUG_SEG}(\\/${OP_PAGE_SLUG_SEG})*$`, 'iu').test(slug)) {- throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, with '.', '_', '-' after the first character of a part, optional colon-separated namespace parts, and forward-slash separated segments)`);+ throw opError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, with '.', '_', '-' after the first character of a part, optional colon-separated namespace parts, and forward-slash separated segments)`,+ 'Use a slug shaped like people/alice-example or notes/v1.0.0: no spaces, backslashes, percent-encoding or dot-led segments.');}}@@ -162,15 +267,20 @@ export function matchesSlugAllowList(slug: string, prefixes: readonly string[]):export function enforceSubagentSlugFence(ctx: OperationContext, slug: string, opName: string): void {if (ctx.viaSubagent !== true) return;if (typeof ctx.subagentId !== 'number' || Number.isNaN(ctx.subagentId)) {- throw new OperationError('permission_denied', `${opName} via subagent requires ctx.subagentId`);+ throw opError('permission_denied', `${opName} via subagent requires ctx.subagentId`,+ 'This is a gbrain dispatch fault, not a caller mistake: report it to the user instead of resubmitting the write.');}if (slugUnderSubagentFence(ctx, slug)) return;const allowList = ctx.allowedSlugPrefixes;- throw new OperationError(+ const fenced = allowList && allowList.length > 0;+ throw opError('permission_denied',- allowList && allowList.length > 0+ fenced? `${opName} slug '${slug}' is not within the trusted-workspace allow-list (${allowList.join(', ')})`: `${opName} via subagent must write under 'wiki/agents/${ctx.subagentId}/...'`,+ fenced+ ? `Write to a slug matching one of: ${allowList.join(', ')}.`+ : `Write under wiki/agents/${ctx.subagentId}/ (for example wiki/agents/${ctx.subagentId}/notes).`,);}@@ -230,18 +340,20 @@ export function slugOutsideCallerFence(ctx: OperationContext, slug: string): boo*/export function enforceClientSlugFence(ctx: OperationContext, slug: string, opName: string): void {if (ctx.auth?.fenceProjectionDegraded) {- throw new OperationError(+ throw opError('permission_denied',`${opName}: this brain's oauth_clients projection is missing bound_slug_prefixes, so the write fence cannot be evaluated. Refusing the write rather than running unfenced.`,- 'Run `gbrain apply-migrations --yes` on the brain host.',+ "The brain host's operator applies the pending migrations (command in fix); then repeat the write.",+ { fix: migrationsFix(ctx) },);}const prefixes = ctx.auth?.boundSlugPrefixes;if (!prefixes) return;if (!slugUnderBoundPrefixes(prefixes, slug)) {- throw new OperationError(+ throw opError('permission_denied',`${opName}: slug '${slug}' is not under any of client ${ctx.auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${prefixes.join(', ')})`,+ `Write to a slug under ${prefixes.join(', ') || 'a granted prefix'}; only the brain host's operator can change this client's binding.`,);}}@@ -381,11 +493,11 @@ export function opAllowedForBoundClient(* `gbrain auth rescope-token <name> --sources none`) refuses every operation:* it never falls back to the `default` floor for reads or writes.*/-export function noSourceGrantError(operation?: string): OperationError {- const err = new OperationError('permission_denied',+export function noSourceGrantError(operation?: string, auth?: Pick<AuthInfo, 'clientId' | 'principal'>): OperationError {+ const err = opError('permission_denied',`${operation ? `${operation}: ` : ''}this token is granted no sources (its source grant is an explicit empty list).`,- 'On the brain host, grant sources with: gbrain auth rescope-token <name> --sources <id,...>',- 'docs/mcp/ADMIN.md#legacy-token-grants');+ "Ask the brain host's operator to grant this token at least one source (command in fix), then reconnect.",+ { docs: 'docs/mcp/ADMIN.md#legacy-token-grants', fix: sourceGrantFix(auth) });err.detail = 'fence=no_source_grant';return err;}@@ -401,20 +513,25 @@ export function enforceBoundClientOpAllowList(auth: AuthInfo | undefined,op: Pick<Operation, 'name' | 'scope' | 'mutating'>,): void {- if (auth?.sourceId === NO_SOURCES) throw noSourceGrantError(op.name);+ if (auth?.sourceId === NO_SOURCES) throw noSourceGrantError(op.name, auth);if (opAllowedForBoundClient(auth, op)) return;if (auth?.grantProjectionDegraded || (Array.isArray(auth?.allowedOperations) && !auth.allowedOperations.includes(op.name))) {- const err = new OperationError('permission_denied', `${op.name} is outside this client's approved operation snapshot.`,- 'Ask the operator to explicitly regrant the required operation; upgrading the server does not expand client grants.');+ const err = opError('permission_denied', `${op.name} is outside this client's approved operation snapshot.`,+ "Ask the brain host's operator to explicitly regrant the required operation (command in fix); upgrading the server does not expand client grants.",+ { fix: auth?.grantProjectionDegraded ? migrationsFix(HTTP_HOST) : grantFix(auth, {+ token: ['--refresh-operations', '--add', op.name],+ client: ['--allowed-operations', [...new Set([...(auth?.allowedOperations ?? []), op.name])].join(',')],+ }, `Adds ${op.name} to this connection's approved operations; only the brain host operator can change grants.`) });err.detail = 'fence=operation_grant';throw err;}const degraded = auth?.fenceProjectionDegraded === true;if (degraded) {- const err = new OperationError(+ const err = opError('permission_denied',`${op.name}: this brain's oauth_clients projection is missing bound_slug_prefixes, so client write bindings cannot be evaluated. Refusing every non-read operation rather than running unfenced.`,- 'Run `gbrain apply-migrations --yes` on the brain host.',+ "The brain host's operator applies the pending migrations (command in fix); then repeat the call.",+ { fix: migrationsFix(HTTP_HOST) },);// Amendment 33 / D10: OP-level fence denial — the tools/list filter// (opAllowedForBoundClient, the same predicate) should have hidden this@@ -423,10 +540,11 @@ export function enforceBoundClientOpAllowList(err.detail = 'fence=op';throw err;}- const err = new OperationError(+ const clientId = safeClientId(auth);+ const err = opError('permission_denied',`${op.name} is not available to slug-bound clients: it can write outside client ${auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${(auth?.boundSlugPrefixes ?? []).join(', ')}).`,- 'Use put_page / add_timeline_entry / add_link under your own prefixes, or ask an operator to clear the binding with `gbrain auth rescope-client <id> --bound-slug-prefixes none`.',+ `Use put_page / add_timeline_entry / add_link under your own prefixes, or ask the brain host's operator to clear the binding${clientId ? ` (gbrain auth rescope-client ${clientId} --bound-slug-prefixes none)` : ''}.`,);// Amendment 33 / D10: op-level, not argument-level — see above. The// slug-prefix ARGUMENT denials (enforceClientSlugFence) deliberately do@@ -443,16 +561,17 @@ export function enforceBoundClientOpAllowList(*/export function validateFilename(name: string): void {if (typeof name !== 'string' || name.length === 0) {- throw new OperationError('invalid_params', 'Filename must be a non-empty string');+ throw opError('invalid_params', 'Filename must be a non-empty string', 'Pass a file name such as report-2026.pdf.');}if (name.length > 255) {- throw new OperationError('invalid_params', 'Filename exceeds 255 characters');+ throw opError('invalid_params', 'Filename exceeds 255 characters', 'Shorten the file name to 255 characters or fewer.');}// v0.32.7: CJK ranges (Han / Hiragana / Katakana / Hangul) allowed in filenames.// Leading-dot / leading-dash rejection preserved.const FILENAME_RE = new RegExp(`^[a-zA-Z0-9${CJK_SLUG_CHARS}][a-zA-Z0-9${CJK_SLUG_CHARS}._\\-]*$`);if (!FILENAME_RE.test(name)) {- throw new OperationError('invalid_params', `Invalid filename: ${name} (allowed: alphanumeric, CJK, dot, underscore, hyphen — no leading dot/dash, no control chars or backslash)`);+ throw opError('invalid_params', `Invalid filename: ${name} (allowed: alphanumeric, CJK, dot, underscore, hyphen — no leading dot/dash, no control chars or backslash)`,+ 'Rename the file to letters, digits, CJK, dots, underscores and hyphens, starting with a letter or digit (e.g. report-2026.pdf).');}}@@ -478,7 +597,7 @@ export function validateFilename(name: string): void {* same precedence ladder — drift between sites is the bug class.*/export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {- if (ctx.sourceId === NO_SOURCES || ctx.auth?.sourceId === NO_SOURCES) throw noSourceGrantError();+ if (ctx.sourceId === NO_SOURCES || ctx.auth?.sourceId === NO_SOURCES) throw noSourceGrantError(undefined, ctx.auth);const allowed = ctx.auth?.allowedSources;// Treat an empty `allowedSources: []` as "no federated read scope" — the// op-handler defers to scalar `ctx.sourceId` below. An attacker-controlled@@ -495,7 +614,9 @@ export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sou}if (ctx.sourceId) return { sourceId: ctx.sourceId };if (ctx.remote !== false && allowed !== undefined) {- throw new OperationError('permission_denied', 'No readable source is granted for this request.');+ throw opError('permission_denied', 'No readable source is granted for this request.',+ "This connection's grant names no readable source; ask the brain host's operator to grant one (command in fix).",+ { fix: sourceGrantFix(ctx.auth) });}return {};}@@ -515,7 +636,8 @@ export function assertSourceInCallerScope(ctx: OperationContext, id: string): voconst scope = sourceScopeOpts(ctx);const allowed = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);if (allowed && !allowed.includes(id)) {- throw new OperationError('not_found', `Unknown source: ${id}`);+ throw opError('not_found', `Unknown source: ${id}`, 'Pass a source id from sources_list, which lists the sources this connection can read.',+ { fix: sourcesListFix('Lists the sources this connection can read.') });}}@@ -546,7 +668,8 @@ export function assertSourceInCallerWriteScope(ctx: OperationContext, id: stringconst bound = writeSource !== undefined || ctx.auth?.allowedSources !== undefined;if (!bound) return;if (writeSource === undefined || writeSource === ALL_SOURCES || id !== writeSource) {- throw new OperationError('not_found', `Unknown source: ${id}`);+ throw opError('not_found', `Unknown source: ${id}`, "Name this connection's own write source; sources_list shows the sources it can read.",+ { fix: sourcesListFix('Lists the sources this connection can read.') });}}@@ -652,13 +775,15 @@ export function resolveRequestedScope(? scope.sourceIds.includes(sourceIdParam): scope.sourceId === sourceIdParam;if (ctx.remote !== false && !granted && !explicitReads?.includes(sourceIdParam)) {- throw new OperationError(+ throw opError('permission_denied','Requested source is outside your granted sources',explicitReads === undefined? 'Request access to this source, or omit source_id to search within your grant.': explicitReadDeniedHint(ctx, sourceIdParam),- explicitReads === undefined ? undefined : EXPLICIT_READ_DOCS,+ explicitReads === undefined+ ? { fix: sourcesListFix('Lists the sources this connection can read; pass one of them as source_id, or omit it.') }+ : { docs: EXPLICIT_READ_DOCS, fix: explicitReadDeniedFix(ctx, sourceIdParam) },);}return { sourceId: sourceIdParam };@@ -701,6 +826,25 @@ function explicitReadDeniedHint(ctx: OperationContext, id: string): string {return `${bound} ${id} ${reason}; the brain owner can run \`gbrain sources federate ${id}\` on the brain host, or ${unbind}.`;}+/**+ * The command behind explicitReadDeniedHint: widen the token's grant, or+ * federate the source this connection's reads stop at (host-only either way).+ */+function explicitReadDeniedFix(ctx: OperationContext, id: string): Action | undefined {+ const auth = ctx.auth;+ if (auth !== undefined && (auth.allowedSources !== undefined || auth.hasSourceGrant !== false)) {+ const granted = auth.allowedSources ?? (auth.sourceId !== undefined ? [auth.sourceId] : []);+ const wanted = [...new Set([...granted, id])].join(',');+ return grantFix(auth, { token: ['--sources', wanted], client: ['--federated-read', wanted] },+ `Adds ${id} to this connection's readable sources; only the brain host operator can change grants.`);+ }+ const binding = ctx.explicitReadBinding;+ const target = binding?.optedOut.includes(binding.sourceId) ? binding.sourceId : id;+ if (!isValidSourceId(target)) return undefined;+ return hostFix(ctx, ['gbrain', 'sources', 'federate', target],+ `Lets unqualified and explicit reads from other connections include ${target}; only the trusted CLI on the brain host changes federation.`);+}+/*** #5081: the sources an explicit `source_id` read may name beyond the scope.* A grant (`ctx.auth.allowedSources`) governs alone. Otherwise a bound stdio@@ -732,18 +876,20 @@ export function parseSourceIdParam(if (typeof raw === 'string') {if (raw === ALL_SOURCES) {if (opts?.allowAll === true) return raw;- throw new OperationError(+ throw opError('invalid_params',`${opName}: source_id '${ALL_SOURCES}' is not a valid target — this op acts on exactly one source.`,'Pass the single source_id of the row to target, or omit source_id to use the ambient source scope.',+ { fix: sourcesListFix('Lists the source ids this caller can name.') },);}if (isValidSourceId(raw)) return raw;}- throw new OperationError(+ throw opError('invalid_params',`${opName}: invalid source_id ${JSON.stringify(raw)} — must be 1-32 lowercase alnum chars with optional interior hyphens.`,- 'Pass a registered source id (see list_sources), or omit source_id to use the ambient source scope.',+ 'Pass a registered source id (sources_list shows them), or omit source_id to use the ambient source scope.',+ { fix: sourcesListFix('Lists the source ids this caller can name.') },);}@@ -821,12 +967,14 @@ export async function assertExplicitSourceLive([sourceIdParam],);if (live.length > 0) return;- throw new OperationError(+ const clientId = safeClientId(ctx.auth);+ throw opError('unknown_source',`source '${sourceIdParam}' does not exist (removed or archived)`,'Omit source_id to read within your grant, or pick an id from sources_list. ' +'If a .gbrain-source dotfile or a federated_read grant still names it, update them ' +- '(gbrain auth rescope-client <client_id>; gbrain doctor lists dangling grants).',+ `(the brain host operator rescopes ${clientId ? `client ${clientId}'s` : 'the'} federated_read grant; gbrain doctor lists dangling grants).`,+ { fix: sourcesListFix('Lists the live sources this caller can read.') },);}@@ -866,7 +1014,8 @@ export async function requireWritablePage(if (writable) {if (ctx.viaSubagent === true && ctx.auth && isPrivatePage(writable)&& await resolveExcludePrivatePages(ctx.engine, ctx.remote)) {- throw new OperationError('permission_denied', `${operation}: this page is outside your write visibility.`);+ throw opError('permission_denied', `${operation}: this page is outside your write visibility.`,+ 'The page is private and this delegated write cannot see it; choose a different slug, or report the refusal to the user.');}return;}@@ -879,17 +1028,20 @@ export async function requireWritablePage(if (spansAnotherSource) {const visible = await ctx.engine.getPage(slug, visibleScope);if (visible && visible.source_id !== writeSource) {- throw new OperationError(+ throw opError('permission_denied',`${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" is readable from source "${visible.source_id}" but this client writes to source "${writeSource}".`,'Graph mutations are same-source by design. Use a client whose write source owns the page, or import the page into your write source first.',+ { why: `The page lives in source "${visible.source_id}"; this connection writes only to "${writeSource}".` },);}}- throw new OperationError(+ throw opError('page_not_found',`${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" was not found in writable source "${writeSource}".`,+ `Check the slug (fuzzy lookup in fix), or create the page in source "${writeSource}" with put_page first.`,+ withFix(getPageFix(slug, `Looks the slug up in source ${writeSource} with fuzzy matching.`, { sourceId: writeSource, fuzzy: true })),);}@@ -909,9 +1061,12 @@ export async function reclassifyMutationTimePageMiss(endpoint: 'from' | 'to' | 'page',): Promise<never> {await requireWritablePage(ctx, slug, operation, endpoint);- throw new OperationError(+ const writeSource = ctx.sourceId || 'default';+ throw opError('page_not_found',- `${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" was unavailable in writable source "${ctx.sourceId || 'default'}" during the mutation.`,+ `${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" was unavailable in writable source "${writeSource}" during the mutation.`,+ 'The page was deleted or restored while the write ran; read its current state (fix) before deciding whether to repeat the write.',+ withFix(getPageFix(slug, 'Shows whether the page exists now, including a soft-deleted row.', { sourceId: writeSource, includeDeleted: true })),);}@@ -932,6 +1087,7 @@ export function resolveCodeIntelScope(ctx: OperationContext,sourceIdParam: string | undefined,allSourcesParam = false,+ opName = 'code_callers',): { allSources: boolean; sourceId?: string } {const scope = resolveRequestedScope(ctx, sourceIdParam, allSourcesParam);if (scope.sourceId) return { allSources: false, sourceId: scope.sourceId };@@ -939,19 +1095,18 @@ export function resolveCodeIntelScope(return { allSources: false, sourceId: scope.sourceIds[0] };}if (scope.sourceIds && scope.sourceIds.length > 1) {- throw new OperationError(- 'invalid_params',+ throw invalidParam(ctx, opName, 'source_id','Code traversal runs against a single source. Specify source_id (one of your granted sources).',- 'Pass source_id=<one of your sources>.',- );+ { choices: scope.sourceIds });}// Empty scope: span everything only for trusted local callers; a remote caller// that reached here has no source in scope and must NOT get cross-source results.if (ctx.remote === false) return { allSources: true, sourceId: undefined };- throw new OperationError(+ throw opError('permission_denied','No source in scope for this request.',- 'Specify source_id, or check your granted sources.',+ 'Pass source_id naming one of your granted sources (sources_list shows them).',+ { fix: sourcesListFix('Lists the sources this connection can read.') },);}@@ -979,8 +1134,9 @@ export async function routeCodeIntelScope(ctx: OperationContext,sourceIdParam: string | undefined,allSourcesParam = false,+ opName = 'code_callers',): Promise<{ allSources: boolean; sourceId?: string }> {- const scope = resolveCodeIntelScope(ctx, sourceIdParam, allSourcesParam);+ const scope = resolveCodeIntelScope(ctx, sourceIdParam, allSourcesParam, opName);if (sourceIdParam !== undefined || allSourcesParam ||scope.allSources || scope.sourceId === undefined ||@@ -1009,15 +1165,12 @@ export async function routeCodeIntelScope(* mode → silently ignored (server-configured mode wins). Returns undefined to* mean "use the configured mode".*/-export function resolvePerCallMode(ctx: OperationContext, raw: unknown): string | undefined {+export function resolvePerCallMode(ctx: OperationContext, raw: unknown, opName = 'query'): string | undefined {if (typeof raw !== 'string' || raw.length === 0) return undefined;if (ctx.remote !== false) return undefined; // remote can't select modeif (!isSearchMode(raw)) {- throw new OperationError(- 'invalid_params',- `Unknown search mode '${raw}'. Valid: conservative, balanced, tokenmax.`,- `gbrain search "<query>" --mode balanced`,- );+ throw invalidParam(ctx, opName, 'mode', `Unknown search mode '${raw}'. Valid: conservative, balanced, tokenmax.`,+ { choices: ['conservative', 'balanced', 'tokenmax'], example: 'balanced' });}return raw;}diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.tsindex dd46a289bf..ac56a177a7 100644--- a/src/core/ops/embedding-migration.ts+++ b/src/core/ops/embedding-migration.ts@@ -39,8 +39,9 @@ const migrate_embeddings: Operation = {// forgets the localOnly filter.if (ctx.remote !== false) {const to = typeof p.to === 'string' && /^[a-z0-9_-]+:[A-Za-z0-9._/-]+$/.test(p.to) ? ['--to', p.to] : [];+ const brain = ctx.brainId && ctx.brainId !== 'host' && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(ctx.brainId) ? ['--brain', ctx.brainId] : [];throw hostOnlyError(ctx, 'permission_denied', 'migrate_embeddings is local-only. Run `gbrain migrate embeddings` on the host.',- ['gbrain', 'migrate', 'embeddings', ...to, '--dry-run'],+ ['gbrain', ...brain, 'migrate', 'embeddings', ...to, '--dry-run'],'Re-embedding rebuilds the vector schema and spends provider money, so only the trusted CLI on the brain host runs it; the dry run prints the plan and cost first.',{ consent: [] });}diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex fe06efe505..67e460935c 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -18,6 +18,7 @@ import { readHolders } from './context.ts';import type { Operation, OperationContext } from './contract.ts';import { OperationError, verbError } from './contract.ts';+import { invalidParam, paramUse } from './op-fix.ts';import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam, sourceScopeOpts, stampEvidenceSafe } from './context.ts';import { markKeywordHits } from '../search/evidence.ts';import { hybridSearchCached, stampContentFlags } from '../search/hybrid.ts';@@ -101,10 +102,9 @@ const extract_facts: Operation = {if (p.valid_from !== undefined && p.valid_from !== null) {const d = new Date(p.valid_from as string);if (!Number.isFinite(d.getTime())) {- throw new OperationError(- 'invalid_params',+ throw invalidParam(ctx, 'extract_facts', 'valid_from',`invalid valid_from: "${String(p.valid_from)}" — expected a parseable ISO 8601 datetime`,- );+ { def: extract_facts.params.valid_from, example: '2026-08-11T00:00:00Z' });}validFrom = d;}@@ -253,9 +253,9 @@ const recall: Operation = {: error.code === 'unknown_source' ? 'not_found': error.code === 'invalid_params' ? 'invalid_params' : null;if (code === null) throw error;- throw verbError(code, error.message,+ throw Object.assign(verbError(code, error.message,error.suggestion ?? 'Choose a permitted active source, or omit source_id to use your existing scope.',- error.detail ?? error.code);+ error.detail ?? error.code), error.fix ? { fix: error.fix } : {});}// Set-dedupe: a grant carrying a repeated id (or the scalar source again)// must not fan out the same source twice into the merge.@@ -635,7 +635,7 @@ const context_pack: Operation = {throw verbError('invalid_params',`context_pack: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,- 'Pass an ISO 8601 datetime, e.g. since: "2026-08-11T00:00:00Z".',+ `Pass an ISO 8601 datetime, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,);}// Normalize to ISO (red-team F4): the filter + rendered text use it.@@ -754,7 +754,7 @@ const delta: Operation = {throw verbError('invalid_params',`delta: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,- 'Pass an ISO 8601 datetime, e.g. since: "2026-08-11T00:00:00Z".',+ `Pass an ISO 8601 datetime, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,);}// NORMALIZE to ISO immediately (red-team F4): the raw string is echoed@@ -774,7 +774,7 @@ const delta: Operation = {throw verbError('invalid_params',`delta: since is not a valid ISO 8601 calendar timestamp: "${rawSince.slice(0, 60)}"`,- 'Pass a real calendar datetime, e.g. since: "2026-08-11T00:00:00Z".',+ `Pass a real calendar datetime, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,);}const explicitSince =@@ -804,7 +804,7 @@ const delta: Operation = {throw verbError('invalid_params','delta requires `since` (ISO 8601) or a `session_id` with an established cursor.',- 'Pass since ("2026-08-11T00:00:00Z") for a stateless delta, or a stable session_id — the first call establishes the cursor and later calls return only newer changes.',+ `Pass ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')} for a stateless delta, or a stable ${paramUse(ctx, 'session_id', 'agent-main')} — the first call establishes the cursor and later calls return only newer changes.`,);}// First wake for this session: establish the cursor at now and report andiff --git a/src/core/ops/image.ts b/src/core/ops/image.tsindex 9e8c74f41b..8f0a54e417 100644--- a/src/core/ops/image.ts+++ b/src/core/ops/image.ts@@ -11,6 +11,7 @@ import { readPolicyOpts } from './context.ts';import type { BrainEngine } from '../engine.ts';import { opError, type Operation } from './contract.ts';+import { paramUse } from './op-fix.ts';import { resolveRequestedScope } from './context.ts';// --- v0.36 Phase 2: search_by_image (image-as-query) ---@@ -58,7 +59,7 @@ const search_by_image: Operation = {if (!imagePath && !imageUrl && !imageData) {throw opError('invalid_params', 'search_by_image requires one of: image_path, image_url, image_data',ctx.remote === false- ? 'Pass one image input: --image-path <file>, --image-url <http(s) URL> or --image-data <base64>.'+ ? `Pass one image input: ${paramUse(ctx, 'image_path', 'photo.png')}, ${paramUse(ctx, 'image_url', 'https://example.com/photo.png')} or ${paramUse(ctx, 'image_data')} with base64 bytes.`: 'Pass one image input: `image_data` (base64 PNG/JPEG/WebP) or `image_url` (http(s) URL).');}if ([imagePath, imageUrl, imageData].filter(Boolean).length > 1) {diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex bccb5bc41b..7120307f22 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -10,8 +10,8 @@*/import type { Operation } from './contract.ts';-import { OperationError } from './contract.ts';-import { invalidParam } from './op-fix.ts';+import { opError } from './contract.ts';+import { invalidParam, paramUse } from './op-fix.ts';import { sourceScopeOpts, readPolicyOpts } from './context.ts';import {FIND_EXPERTS_DESCRIPTION,@@ -74,10 +74,10 @@ const volunteer_context: Operation = {}if (typeof p.window !== 'string' || !p.window.trim()) {- throw new OperationError(+ throw opError('invalid_params',- 'window is required unless stats: true',- 'Pass the recent turns as a string (CLI: pipe them on stdin), or use --stats.',+ `window is required unless ${paramUse(ctx, 'stats')}`,+ `${ctx.remote === false ? 'Pipe the recent turns on stdin' : 'Pass `window` with the recent turns as a string'}, or pass ${paramUse(ctx, 'stats')} for the volunteered-vs-used summary.`,);}const turns = parseWindow(p.window);@@ -149,7 +149,8 @@ const find_experts: Operation = {const { findExperts } = await import('../../commands/whoknows.ts');const topic = typeof p.topic === 'string' ? p.topic : '';if (!topic.trim()) {- throw new OperationError('invalid_params', '`topic` is required and must be a non-empty string.');+ throw invalidParam(ctx, 'find_experts', 'topic', '`topic` is required and must be a non-empty string.',+ { def: find_experts.params.topic, example: 'vector search' });}// v0.34.1 (#861, D3 — 5th leak surface): find_experts (whoknows) was// authored against v0.33 after PR #861 was drafted, so the source-scopediff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex d552f795e6..fc296e2cde 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -8,7 +8,8 @@ import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';* '../operations.ts' here (cycle).*/-import { OperationError, opError, type Operation } from './contract.ts';+import { opError, type Operation } from './contract.ts';+import { paramUse } from './op-fix.ts';import {assertExplicitSourceLive,enforceClientSlugFence,@@ -76,7 +77,7 @@ const add_link: Operation = {if (linkType.length > 0) {const activePack = await loadActivePackForWriteVocabulary(ctx);if (activePack && !packDeclaresLinkType(activePack, linkType)) {- throw new OperationError(+ throw opError('invalid_params',undeclaredLinkTypeMessage(linkType, activePack, 'add_link'),undeclaredLinkTypeSuggestion(activePack),@@ -192,10 +193,10 @@ async function resolveLinkReadScope(): Promise<{ requested: string | undefined; policy: PageReadPolicy }> {const sourceIdParam = parseSourceIdParam(p.source_id, opName, { allowAll: true });if (p.all_sources === true && sourceIdParam !== undefined && sourceIdParam !== ALL_SOURCES) {- throw new OperationError(+ throw opError('invalid_params',`${opName}: pass either source_id or all_sources, not both.`,- 'Drop all_sources to read one source, or drop source_id to span sources.',+ `Drop ${paramUse(ctx, 'all_sources')} to read source ${sourceIdParam}, or drop source_id to span sources.`,);}const requested = p.all_sources === true ? ALL_SOURCES : sourceIdParam;diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex 9b09178475..1d2c8becc2 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -6,7 +6,7 @@*/import { assertSourceInCallerScope, readPolicyOpts } from './context.ts';-import { OperationError, type Operation } from './contract.ts';+import type { Operation } from './contract.ts';import { invalidParam } from './op-fix.ts';// --- Orphans ---@@ -61,8 +61,11 @@ const find_orphans: Operation = {const scope = named !== undefined ? await readPolicyOpts(ctx, { sourceId: named }) : await readPolicyOpts(ctx);const limit = p.limit === undefined ? ORPHANS_DEFAULT_LIMIT : Number(p.limit);const offset = p.offset === undefined ? 0 : Number(p.offset);- if (!Number.isInteger(limit) || limit < 1 || limit > ORPHANS_MAX_LIMIT || !Number.isInteger(offset) || offset < 0) {- throw new OperationError('invalid_params', `find_orphans: limit must be 1-${ORPHANS_MAX_LIMIT} and offset a non-negative integer`);+ const limitOk = Number.isInteger(limit) && limit >= 1 && limit <= ORPHANS_MAX_LIMIT;+ if (!limitOk || !Number.isInteger(offset) || offset < 0) {+ throw invalidParam(ctx, 'find_orphans', limitOk ? 'offset' : 'limit',+ `find_orphans: limit must be 1-${ORPHANS_MAX_LIMIT} and offset a non-negative integer`,+ limitOk ? { def: find_orphans.params.offset, example: 0 } : { def: find_orphans.params.limit, example: ORPHANS_DEFAULT_LIMIT });}const result = await findOrphans(ctx.engine, {includePseudo: (p.include_pseudo as boolean) || false,diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 423666d7b5..4dc6bfaba7 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -21,8 +21,8 @@ import { getContentFlag } from '../quarantine.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';-import { OperationError } from './contract.ts';-import type { Operation, OperationContext } from './contract.ts';+import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';+import { invalidParam } from './op-fix.ts';import {assertExplicitSourceLive,enforceSubagentSlugFence,@@ -32,7 +32,7 @@ import {normalizeSlugPrefix,parseSourceIdParam,readPolicyOpts,- validatePageSlug,+ validatePageSlug, pageNotFoundError,} from './context.ts';// --- Page CRUD ---@@ -139,7 +139,7 @@ const get_page: Operation = {}if (!page) {- let hint = includeDeleted ? 'Check the slug or use fuzzy: true' : 'Page may be soft-deleted; pass include_deleted: true to verify';+ let elsewhereSource: string | undefined;// #4516: source scoping is by-design isolation, but the miss diagnostic// should say WHERE the slug actually lives. Trusted local callers only// (`ctx.remote === false`) — for a remote caller the probe would be a@@ -151,13 +151,13 @@ const get_page: Operation = {// deliberately spans all sources to name where the slug lives.const elsewhere = await ctx.engine.getPage(slug, { includeDeleted });if (elsewhere && !(excludePrivate && isPrivatePage(elsewhere))) {- hint = `Page exists in source '${elsewhere.source_id}' — pass --source ${elsewhere.source_id} (source_id: '${elsewhere.source_id}' over MCP). ${hint}`;+ elsewhereSource = elsewhere.source_id;}} catch {// Diagnostic only — a probe failure must never mask the real error.}}- throw new OperationError('page_not_found', `Page not found: ${slug}`, hint);+ throw pageNotFoundError(ctx, slug, { includeDeleted, sourceIdParam, elsewhereSource });}// v0.37.0 (D11): op-layer write-back for the `last_retrieved_at` stale@@ -220,13 +220,13 @@ const fetch_page: Operation = {handler: async (ctx, p) => {const id = p.id as string;if (typeof id !== 'string' || !id.trim()) {- throw new OperationError('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.');}let identity: ReturnType<typeof decodeDeepResearchId>;try { identity = decodeDeepResearchId(id); }- catch { throw new OperationError('invalid_params', 'Invalid fetch result id', 'Pass the unchanged `id` field from a `search` result.'); }+ catch { throw opError('invalid_params', 'Invalid fetch result id', 'Pass the unchanged `id` field from a `search` result.'); }const slug = identity?.slug ?? id.trim();- const missing = () => new OperationError('page_not_found', 'Page not found', 'Pass an id returned by a current `search` call.');+ const missing = () => opError('page_not_found', 'Page not found', 'Pass an id returned by a current `search` call.');let sourceOpts: ReturnType<typeof federatedSearchScope>;try { sourceOpts = federatedSearchScope(ctx, identity?.sourceId); }catch (error) {@@ -248,7 +248,7 @@ const fetch_page: Operation = {});} catch (error) {if (error instanceof PageSnapshotAmbiguousError) {- throw new OperationError('ambiguous_id', 'The legacy id matches multiple readable pages', 'Search again and pass the source-qualified result id.');+ throw opError('ambiguous_id', 'The legacy id matches multiple readable pages', 'Search again and pass the source-qualified result id.');}throw error;}@@ -491,7 +491,7 @@ const list_pages: Operation = {const updatedAfter = typeof p.updated_after === 'string' ? p.updated_after : undefined;const updatedAfterSlug = typeof p.updated_after_slug === 'string' ? p.updated_after_slug : undefined;if (updatedAfterSlug !== undefined && updatedAfter === undefined) {- throw new OperationError('invalid_params', "list_pages: updated_after_slug requires updated_after (the cursor row's updated_at_iso).");+ throw invalidParam(ctx, 'list_pages', 'updated_after', "list_pages: updated_after_slug requires updated_after (the cursor row's updated_at_iso).", { def: list_pages.params.updated_after, example: '2026-08-11T00:00:00.000000Z' });}const updatedAfterKeyset = updatedAfter !== undefined && updatedAfterSlug !== undefined? { updatedAt: updatedAfter, slug: updatedAfterSlug }diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex f9d9d99b00..4abe40b092 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -33,8 +33,9 @@ import { probeProjectionReadiness } from '../search/projection-readiness.ts';import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';import { pageReadFilter } from '../search/read-policy-sql.ts';import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';-import { OperationError } from './contract.ts';+import { opError } from './contract.ts';import type { Operation, OperationContext } from './contract.ts';+import { invalidParam, paramUse } from './op-fix.ts';import {assertExplicitSourceLive,federatedSearchScope,@@ -258,7 +259,7 @@ async function buildRetrievalResponseMeta(* → both engines' keyword/title/vector legs) has existed since v0.33* (whoknows); this just exposes it on the public search/query ops.*/-function normalizeTypesParam(raw: unknown): string[] | undefined {+function normalizeTypesParam(ctx: OperationContext, tool: 'search' | 'query', raw: unknown): string[] | undefined {if (raw === undefined || raw === null) return undefined;// #5390: a structurally empty array, an empty string or a whitespace-only// string is treated as absent, not as a request for an impossible filter.@@ -270,18 +271,14 @@ function normalizeTypesParam(raw: unknown): string[] | undefined {: typeof raw === 'string'? raw.split(','): null;+ const example = ctx.remote === false ? 'person,company' : ['person', 'company'];if (arr === null || arr.some((t) => typeof t !== 'string')) {- throw new OperationError(- 'invalid_params',- '`types` must be an array of page-type strings (CLI: --types person,company).',- );+ throw invalidParam(ctx, tool, 'types', `\`types\` must be an array of page-type strings (e.g. ${paramUse(ctx, 'types', example)}).`, { example });}const types = [...new Set((arr as string[]).map((t) => t.trim()).filter(Boolean))];if (types.length === 0) {- throw new OperationError(- 'invalid_params',- '`types` was provided but contained no usable page-type strings (CLI: --types person,company).',- );+ throw invalidParam(ctx, tool, 'types',+ `\`types\` was provided but contained no usable page-type strings (e.g. ${paramUse(ctx, 'types', example)}).`, { example });}return types;}@@ -368,7 +365,7 @@ const search: Operation = {const limit = (p.limit as number) || 20;const offset = (p.offset as number) || 0;// #3985: validated multi-type filter, threaded into both branches below.- let types = normalizeTypesParam(p.types);+ let types = normalizeTypesParam(ctx, 'search', p.types);// #3800: snippet cap (param > subagent config default > full text).const snippetCap = await resolveSnippetCap(ctx, p);const plan = await evidencePlanFor(ctx, p, snippetCap, 'search');@@ -388,7 +385,7 @@ const search: Operation = {// T4/D5 — per-call mode honored ONLY for trusted/local callers so a remote// OAuth client can't escalate to the costly tokenmax bundle. Local + unknown// mode → loud reject; remote + mode set → silently ignored (uses config).- const perCallMode = resolvePerCallMode(ctx, p.mode);+ const perCallMode = resolvePerCallMode(ctx, p.mode, 'search');// T4/D17 — escape hatch: keyword-only when the operator opts out of the// hybrid `search` contract (privacy/cost: no query text to an embedding@@ -585,7 +582,7 @@ const query: Operation = {const queryText = p.query as string | undefined;// #3985: validated multi-type filter (text path; the image-similarity// branch below also honors it — searchVector filters types at SQL level).- let types = normalizeTypesParam(p.types);+ let types = normalizeTypesParam(ctx, 'query', p.types);// #3800: snippet cap (param > subagent config default > full text).const snippetCap = await resolveSnippetCap(ctx, p);const plan = await evidencePlanFor(ctx, p, snippetCap, 'query');@@ -664,10 +661,12 @@ const query: Operation = {if (!queryText) {// WP3: typed envelope — a caller mistake must classify as invalid_params// over MCP, not the internal_error a plain throw produced.- throw new OperationError(+ throw opError('invalid_params','query requires either `query` (text) or `image` (base64 bytes).',- 'Pass `query` with your search text (e.g. {"query": "acme-example roadmap"}), or `image` with base64 image bytes.',+ ctx.remote === false+ ? `Pass the search text as the positional argument (e.g. gbrain query "acme-example roadmap"), or ${paramUse(ctx, 'image', 'photo.png')}.`+ : 'Pass `query` with your search text (e.g. {"query": "acme-example roadmap"}), or `image` with base64 image bytes.',);}@@ -935,8 +934,8 @@ const assemble_evidence: Operation = {if (!Array.isArray(hits) || hits.some(h => typeof h !== 'object' || h === null|| typeof (h as Record<string, unknown>).source_id !== 'string' || typeof (h as Record<string, unknown>).slug !== 'string'|| !Number.isInteger((h as Record<string, unknown>).chunk_id))) {- throw new OperationError('invalid_params', 'hits must be an array of { source_id: string, slug: string, chunk_id: integer }.',- 'Example: {"hits": [{"source_id": "default", "slug": "chat/session-0412", "chunk_id": 8812}], "return_unit": "page"}');+ throw opError('invalid_params', 'hits must be an array of { source_id: string, slug: string, chunk_id: integer }.',+ 'Pass the source_id, slug and chunk_id of each search hit. Example: {"hits": [{"source_id": "default", "slug": "chat/session-0412", "chunk_id": 8812}], "return_unit": "page"}');}const scope = federatedSearchScope(ctx);const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);diff --git a/test/explicit-read-admission-5081.test.ts b/test/explicit-read-admission-5081.test.tsindex 09a7a32b6a..ac3f868f12 100644--- a/test/explicit-read-admission-5081.test.ts+++ b/test/explicit-read-admission-5081.test.ts@@ -222,14 +222,14 @@ describe('#5081 — callers that pass no admission set keep denying (ENG-O6 pinsconst { isError, body } = await call(await bound(), 'search_by_image', { image_data: png, source_id: 'notes' });expect(isError).toBe(true);expect(body.error).toBe('permission_denied');- expect(body.suggestion).toBe(ORIGINAL_HINT);+ expect(body.suggestion).toContain(ORIGINAL_HINT);});test('open_loops still denies an explicit federated source', async () => {const { isError, body } = await call(await bound(), 'open_loops', { source_id: 'notes' });expect(isError).toBe(true);expect(body.error).toBe('permission_denied');- expect(body.suggestion).toBe(ORIGINAL_HINT);+ expect(body.suggestion).toContain(ORIGINAL_HINT);});test('code-intel scope resolution still denies an explicit federated source', async () => {@@ -305,6 +305,6 @@ describe('#5081 — HTTP tokens and unbound stdio keep the no-widening rule', ()const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'work', hasSourceGrant: true } as AuthInfo;const { body } = await call({ remote: true, transport: 'http', sourceId: 'work', auth }, 'search', { query: MARKER, source_id: 'notes' });expect(body.error).toBe('permission_denied');- expect(body.suggestion).toBe('Your token is not granted notes; ask the brain owner to grant it.');+ expect(body.suggestion).toContain('Your token is not granted notes; ask the brain owner to grant it.');});});diff --git a/test/ops-error-fixes-g1.test.ts b/test/ops-error-fixes-g1.test.tsnew file mode 100644index 0000000000..2eb5121f95--- /dev/null+++ b/test/ops-error-fixes-g1.test.ts@@ -0,0 +1,166 @@+/**+ * Agent contract v1, Lane B (B2/B6/B7/B8) — representative op error sites in+ * the context / pages / search / code-intel / insights / embedding-migration+ * group carry a filled suggestion and, where a next step exists, a fix that+ * names real ids and renders for the caller's surface.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, OperationError, type AuthInfo, type OperationContext } from '../src/core/operations.ts';+import {+ enforceBoundClientOpAllowList,+ noSourceGrantError,+ parseSourceIdParam,+ requireWritablePage,+ resolveCodeIntelScope,+ resolvePerCallMode,+ resolveRequestedScope,+ validatePageSlug,+} from '../src/core/ops/context.ts';+import { toAgentError } from '../src/core/agent-output.ts';++const TOKEN_ID = '0b9a1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d';+const oauth = (over: Partial<AuthInfo> = {}): AuthInfo => ({+ token: 't', clientId: 'cli-alpha', scopes: ['read', 'write'], principal: { kind: 'oauth_client', id: 'cli-alpha' }, ...over,+});+const ctxOf = (over: Partial<OperationContext> = {}): OperationContext =>+ ({ engine: {} as OperationContext['engine'], config: {} as OperationContext['config'], remote: true, transport: 'http', ...over }) as OperationContext;+const opNamed = (name: string) => {+ const op = operations.find(o => o.name === name);+ if (!op) throw new Error(`no op ${name}`);+ return op;+};+const caught = async (fn: () => unknown): Promise<OperationError> => {+ try { await fn(); } catch (e) { expect(e).toBeInstanceOf(OperationError); return e as OperationError; }+ throw new Error('expected a throw');+};+const render = (transport: 'stdio' | 'http', callable: string[] = []) => ({+ transport, isCallable: (t: string) => callable.includes(t), preapproved: () => false,+});++describe('context.ts grant and fence refusals (B6/B7)', () => {+ test('no-source grant names the token and asks for the sources as an input', () => {+ const e = noSourceGrantError('put_page', oauth({ clientId: 'tok', principal: { kind: 'legacy_token', id: TOKEN_ID } }));+ expect(e.code).toBe('permission_denied');+ expect(e.suggestion).not.toContain('<name>');+ expect(e.fix).toMatchObject({+ argv: ['gbrain', 'auth', 'rescope-token', '--id', TOKEN_ID, '--sources', '<sources>'],+ actor: 'host_admin', consent: ['credentials'], inputs: [{ name: 'sources' }],+ });+ const env = toAgentError(e, { transport: 'http', op: 'put_page', render: render('http') });+ expect(env.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'host_admin' });+ });++ test('operation-snapshot refusal regrants the exact op for an OAuth client', async () => {+ const e = await caught(() => enforceBoundClientOpAllowList(oauth({ allowedOperations: ['get_page'] }), { name: 'put_page', scope: 'write', mutating: true }));+ expect(e.detail).toBe('fence=operation_grant');+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'auth', 'rescope-client', 'cli-alpha', '--allowed-operations', 'get_page,put_page'], actor: 'host_admin' });+ });++ test('slug-bound refusal fills the client id instead of <id>', async () => {+ const e = await caught(() => enforceBoundClientOpAllowList(oauth({ boundSlugPrefixes: ['wiki/agents/alpha/'] }), { name: 'sources_remove', scope: 'admin', mutating: true }));+ expect(e.suggestion).toContain('gbrain auth rescope-client cli-alpha --bound-slug-prefixes none');+ expect(e.suggestion).not.toContain('<id>');+ });++ test('degraded fence projection points the host at the migrations', async () => {+ const e = await caught(() => enforceBoundClientOpAllowList(oauth({ fenceProjectionDegraded: true }), { name: 'delete_page', scope: 'write', mutating: true }));+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'], actor: 'host_admin' });+ });+});++describe('context.ts source scope (B2)', () => {+ test('out-of-grant source keeps its hint and lists the readable sources', async () => {+ const e = await caught(() => resolveRequestedScope(ctxOf({ auth: oauth({ allowedSources: ['work'] }) }), 'notes'));+ expect(e.suggestion).toBe('Request access to this source, or omit source_id to search within your grant.');+ expect(e.fix).toMatchObject({ mcp: { tool: 'sources_list', arguments: {} }, argv: ['gbrain', 'sources', 'list', '--json'] });+ });++ test('explicit-read denial on a bound connection names the federate command for that source', async () => {+ const ctx = ctxOf({ transport: 'stdio', explicitReadBinding: { sourceId: 'work', via: 'GBRAIN_SOURCE', sourceIds: ['work'], optedOut: [] } } as Partial<OperationContext>);+ const e = await caught(() => resolveRequestedScope(ctx, 'notes', false, ['work']));+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'sources', 'federate', 'notes'], actor: 'user' });+ });++ test('an invalid source_id points at sources_list (not the nonexistent list_sources)', async () => {+ const e = await caught(() => parseSourceIdParam('Bad Id', 'get_page'));+ expect(e.code).toBe('invalid_params');+ expect(e.suggestion).not.toContain('list_sources');+ expect(e.fix?.mcp).toEqual({ tool: 'sources_list', arguments: {} });+ });++ test('code traversal over several granted sources lists them as choices', async () => {+ const e = await caught(() => resolveCodeIntelScope(ctxOf({ auth: oauth({ allowedSources: ['work', 'notes'] }) }), undefined, false, 'code_blast'));+ expect(e.code).toBe('invalid_params');+ expect(e.suggestion).toBe('Pass `source_id` as one of: work, notes. Example: code_blast {"source_id": "work"}.');+ });++ test('an unknown search mode renders the CLI flag on the CLI (B8)', async () => {+ const e = await caught(() => resolvePerCallMode(ctxOf({ remote: false }), 'NUKE', 'search'));+ expect(e.suggestion).toBe('Pass --mode as one of: conservative, balanced, tokenmax. Example: --mode balanced.');+ });++ test('slug validation explains the accepted shape', async () => {+ const e = await caught(() => validatePageSlug('../etc'));+ expect(e.code).toBe('invalid_params');+ expect(e.suggestion).toContain('people/alice-example');+ expect(e.contractVersion).toBe(1);+ });+});++describe('op handlers (B2/B6/B8)', () => {+ test('volunteer_context names stats on the caller surface', async () => {+ const op = opNamed('volunteer_context');+ const mcp = await caught(() => op.handler(ctxOf({ transport: 'stdio' }), {}));+ expect(mcp.message).toBe('window is required unless stats: true');+ expect(mcp.suggestion).not.toContain('--stats');+ const cli = await caught(() => op.handler(ctxOf({ remote: false }), {}));+ expect(cli.message).toBe('window is required unless --stats');+ expect(cli.suggestion).toContain('--stats');+ });++ test('remote code reads name the trusted local call with the symbol and source', async () => {+ const e = await caught(() => opNamed('code_callers').handler(ctxOf(), { symbol: 'parseMarkdown', source_id: 'work' }));+ expect(e.code).toBe('permission_denied');+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'call', '--source', 'work', 'code_callers', '{"symbol":"parseMarkdown"}'], actor: 'host_admin' });+ const odd = await caught(() => opNamed('code_flow').handler(ctxOf(), { entry_point: '$(rm -rf)' }));+ expect(odd.fix).toBeUndefined();+ });++ test('migrate_embeddings refusal routes to the caller brain explicitly', async () => {+ const e = await caught(() => opNamed('migrate_embeddings').handler(ctxOf({ transport: 'stdio', brainId: 'work-brain' }), { to: 'openai:text-embedding-3-small' }));+ expect(e.fix).toMatchObject({+ argv: ['gbrain', '--brain', 'work-brain', 'migrate', 'embeddings', '--to', 'openai:text-embedding-3-small', '--dry-run'],+ actor: 'user',+ });+ });++ test('find_experts without a topic lists the param on each surface', async () => {+ const op = opNamed('find_experts');+ expect((await caught(() => op.handler(ctxOf({ transport: 'stdio' }), {}))).suggestion).toContain('find_experts {"topic": "vector search"}');+ expect((await caught(() => op.handler(ctxOf({ remote: false }), {}))).suggestion).toContain('--topic vector search');+ });+});++describe('page misses carry a read-only lookup (B2)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });+ afterAll(async () => { await engine.disconnect(); });++ test('get_page miss on the CLI suggests the soft-delete check as a flag', async () => {+ const e = await caught(() => opNamed('get_page').handler(ctxOf({ engine, remote: false }), { slug: 'people/nobody-example' }));+ expect(e.code).toBe('page_not_found');+ expect(e.suggestion).toContain('--include-deleted');+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'get', 'people/nobody-example', '--include-deleted'], mcp: { tool: 'get_page', arguments: { slug: 'people/nobody-example', include_deleted: true } } });+ });++ test('graph-write endpoint miss looks the slug up in the write source', async () => {+ const e = await caught(() => requireWritablePage(ctxOf({ engine, remote: false, sourceId: 'default' }), 'people/nobody-example', 'add_link', 'to'));+ expect(e.code).toBe('page_not_found');+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'get', 'people/nobody-example', '--fuzzy', '--source', 'default'] });+ });+});