Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ops): agent-contract fixes for loops, think, timeline, transcripts, extraction and attribution ops (B1/B2/B6/B7/B8)

garrytan41d03e777c15
diff --git a/src/core/ops/attribution.ts b/src/core/ops/attribution.ts
index 9b72fcc619..c2ab1e6db7 100644
--- a/src/core/ops/attribution.ts
+++ b/src/core/ops/attribution.ts
@@ -12,7 +12,9 @@
import type { BrainEngine } from '../engine.ts';
import type { AttributedPageVersion, PageVersion, WriteAttributionView } from '../types.ts';
import { hasScope } from '../scope.ts';
-import { OperationError, type Operation, type OperationContext } from './contract.ts';
+import { opError, type Operation, type OperationContext } from './contract.ts';
+import type { McpCall } from '../agent-output.ts';
+import { opTransport, paramUse, readFix } from './op-fix.ts';
import { readHolders, readPolicyOpts } from './context.ts';
const DOCS = 'docs/mcp/ADMIN.md#write-attribution';
@@ -88,14 +90,30 @@ export async function attributeVersions(engine: BrainEngine, versions: PageVersi
return versions.map((v, i) => ({ ...v, written_by: views[2 * i], archived_by: views[2 * i + 1] }));
}
-function positiveInt(value: unknown, flag: string): number | undefined {
+const SLUG = /^[a-z0-9][a-z0-9/_.-]{0,254}$/i;
+
+const paramName = (ctx: OperationContext, param: string) => (opTransport(ctx) === 'cli' ? paramUse(ctx, param) : param);
+
+function positiveInt(ctx: OperationContext, value: unknown, param: 'fact' | 'take' | 'timeline'): number | undefined {
if (value === undefined || value === null) return undefined;
const n = Number(value);
- if (!Number.isSafeInteger(n) || n < 1) throw new OperationError('invalid_params', `${flag} must be a positive integer, got '${String(value)}'.`, undefined, DOCS);
+ if (!Number.isSafeInteger(n) || n < 1) {
+ const name = paramName(ctx, param);
+ throw opError('invalid_params', `${name} must be a positive integer, got '${String(value)}'.`,
+ `Pass ${name} as a row id from the page, for example ${paramUse(ctx, param, 1)}.`, { docs: DOCS });
+ }
return n;
}
-type RowTarget = { kind: 'fact' | 'take' | 'timeline_entry'; label: string; sql: string; params: unknown[]; list: string };
+function attributionCall(slug: string, row: { fact?: number; take?: number; timeline?: number }) {
+ const [key, id] = Object.entries(row).find(([, v]) => v !== undefined) as ['fact' | 'take' | 'timeline', number];
+ return readFix(`Attributes the ${key} you named on its own.`, {
+ argv: ['gbrain', 'attribution', slug, `--${key}`, String(id)],
+ mcp: { tool: 'get_write_attribution', arguments: { slug, [key]: id } },
+ });
+}
+
+type RowTarget = { kind: 'fact' | 'take' | 'timeline_entry'; label: string; sql: string; params: unknown[]; list: McpCall };
const get_write_attribution: Operation = {
name: 'get_write_attribution',
@@ -117,18 +135,20 @@ const get_write_attribution: Operation = {
cliHints: { name: 'attribution', positional: ['slug'] },
handler: async (ctx, p) => {
const slug = p.slug as string;
- const fact = positiveInt(p.fact, '--fact');
- const take = positiveInt(p.take, '--take');
- const timeline = positiveInt(p.timeline, '--timeline');
+ const fact = positiveInt(ctx, p.fact, 'fact');
+ const take = positiveInt(ctx, p.take, 'take');
+ const timeline = positiveInt(ctx, p.timeline, 'timeline');
if ([fact, take, timeline].filter(v => v !== undefined).length > 1) {
- throw new OperationError('invalid_params', 'Pass at most one of --fact, --take or --timeline.',
- `Run one call per row, for example: gbrain attribution ${slug} --fact ${fact ?? take ?? timeline}`, DOCS);
+ throw opError('invalid_params', `Pass at most one of ${paramName(ctx, 'fact')}, ${paramName(ctx, 'take')} or ${paramName(ctx, 'timeline')}.`,
+ 'Make one call per row; fix attributes the first row you named.',
+ { docs: DOCS, ...(SLUG.test(slug) ? { fix: attributionCall(slug, { fact, take, timeline }) } : {}) });
}
const policy = await readPolicyOpts(ctx);
const page = await ctx.engine.getPage(slug, policy);
if (!page?.id) {
- throw new OperationError('page_not_found', `No page '${slug}' is visible to this caller.`,
- 'Find the exact slug with `gbrain search "<words>"` (remote: the search tool), then retry. Pages outside your source grant read as missing.', DOCS);
+ throw opError('page_not_found', `No page '${slug}' is visible to this caller.`,
+ 'Find the exact slug by searching (fix), then call again with it. Pages outside your source grant read as missing.',
+ { docs: DOCS, ...(SLUG.test(slug) ? { fix: readFix('Searches for pages near the slug you passed.', { argv: ['gbrain', 'search', slug], mcp: { tool: 'search', arguments: { query: slug } } }) } : {}) });
}
const sourceId = page.source_id ?? 'default';
const [live] = await ctx.engine.executeRaw<{ revision: string; req: string | null; kind: string | null; pid: string | null }>(
@@ -144,8 +164,12 @@ const get_write_attribution: Operation = {
const [found] = await ctx.engine.executeRaw<{ id: number; w_req: string | null; w_kind: string | null; w_id: string | null; created_at: Date | string | null;
l_req: string | null; l_kind: string | null; l_id: string | null; last_written_at: Date | string | null }>(row.sql, row.params);
if (!found) {
- throw new OperationError(row.kind === 'fact' ? 'fact_not_found' : 'not_found', `No ${row.label} is visible on page '${page.slug}'.`,
- `List the page's rows with \`${row.list}\`, then retry with an id from that list.`, DOCS);
+ throw opError(row.kind === 'fact' ? 'fact_not_found' : 'not_found', `No ${row.label} is visible on page '${page.slug}'.`,
+ 'List the page\'s rows (fix), then call again with an id from that list.', {
+ docs: DOCS,
+ fix: readFix(`Lists the ${row.kind === 'timeline_entry' ? 'timeline entries' : `${row.kind}s`} on page '${page.slug}' with their ids.`,
+ { argv: ['gbrain', 'call', '--source', sourceId, row.list.tool, JSON.stringify(row.list.arguments)], mcp: row.list }),
+ });
}
target = { kind: row.kind, id: Number(found.id), ...(row.kind === 'take' ? { row_num: take } : {}), slug: page.slug, source_id: sourceId, page_id: page.id };
created = { request_id: found.w_req, principal_kind: found.w_kind, principal_id: found.w_id, at: found.created_at };
@@ -175,18 +199,18 @@ function rowTarget(ctx: OperationContext, pageId: number, slug: string, sourceId
const cols = `write_request_id::text AS w_req, write_principal_kind AS w_kind, write_principal_id AS w_id, created_at,
last_write_request_id::text AS l_req, last_write_principal_kind AS l_kind, last_write_principal_id AS l_id, last_written_at`;
if (ids.fact !== undefined) {
- return { kind: 'fact', label: `fact #${ids.fact}`, list: `gbrain call recall '{"entity":"${slug}"}'`,
+ return { kind: 'fact', label: `fact #${ids.fact}`, list: { tool: 'recall', arguments: { entity: slug } },
sql: `SELECT id, ${cols} FROM facts WHERE id = $1 AND source_id = $2 AND (entity_slug = $3 OR source_markdown_slug = $3)
${ctx.remote === false ? '' : "AND visibility = 'world'"}`, params: [ids.fact, sourceId, slug] };
}
if (ids.take !== undefined) {
const holders = readHolders(ctx);
- return { kind: 'take', label: `take at row ${ids.take}`, list: `gbrain call takes_list '{"page_slug":"${slug}"}'`,
+ return { kind: 'take', label: `take at row ${ids.take}`, list: { tool: 'takes_list', arguments: { page_slug: slug } },
sql: `SELECT id, ${cols} FROM takes WHERE page_id = $1 AND row_num = $2 ${holders ? 'AND holder = ANY($3::text[])' : ''}`,
params: holders ? [pageId, ids.take, holders] : [pageId, ids.take] };
}
if (ids.timeline !== undefined) {
- return { kind: 'timeline_entry', label: `timeline entry #${ids.timeline}`, list: `gbrain call get_timeline '{"slug":"${slug}"}'`,
+ return { kind: 'timeline_entry', label: `timeline entry #${ids.timeline}`, list: { tool: 'get_timeline', arguments: { slug } },
sql: `SELECT id, ${cols} FROM timeline_entries WHERE id = $1 AND page_id = $2`, params: [ids.timeline, pageId] };
}
return undefined;
diff --git a/src/core/ops/extraction.ts b/src/core/ops/extraction.ts
index d0b14cc401..1dd5143b22 100644
--- a/src/core/ops/extraction.ts
+++ b/src/core/ops/extraction.ts
@@ -9,7 +9,9 @@
*/
import type { Operation } from './contract.ts';
-import { OperationError } from './contract.ts';
+import { opError, type OperationContext } from './contract.ts';
+import type { Action } from '../agent-output.ts';
+import { hostOnlyError, paramUse, readFix } from './op-fix.ts';
import { sourceScopeOpts } from './context.ts';
import { unverifiedExtractionFragment, isUnverifiedExtraction, EXTRACTION_STATUS_KEY, STATUS_VERIFIED } from '../extraction-review.ts';
import { buildVisibilityClause } from '../search/sql-ranking.ts';
@@ -48,7 +50,7 @@ const extract_entities: Operation = {
name: 'extract_entities',
idempotent: false,
outputRedaction: 'retrieval',
- description: 'Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI AND --trusted-extraction.',
+ description: 'Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI with trusted_extraction set.',
params: {
text: { type: 'string', required: true, description: 'The text to extract entities from (email, transcript, pasted content, …). Max 200k characters — split larger inputs.' },
source_slug: { type: 'string', required: true, description: 'Slug of the source page the text came from (used for backlinks + timeline attribution).' },
@@ -67,10 +69,10 @@ const extract_entities: Operation = {
// of thousands of "entities", each costing several DB round-trips. Cap
// input size loudly and entity count softly (surfaced as `truncated`).
if (text.length > MAX_EXTRACT_TEXT_CHARS) {
- throw new OperationError(
+ throw opError(
'invalid_params',
`extract_entities: text is ${text.length} chars (max ${MAX_EXTRACT_TEXT_CHARS}).`,
- 'Split the input and call extract_entities per section.',
+ `Nothing was written. Split the input into pieces of at most ${MAX_EXTRACT_TEXT_CHARS} characters and call extract_entities once per piece.`,
);
}
if (ctx.dryRun) return { dry_run: true, action: 'extract_entities', trusted };
@@ -149,6 +151,26 @@ const extraction_pending: Operation = {
cliHints: { name: 'extraction-pending' },
};
+const REVIEW_SLUG = /^[a-z0-9][a-z0-9/_.-]{0,254}$/i;
+
+function pendingFix(): Action {
+ return readFix('Lists the unverified auto-extracted stubs awaiting review, with their slugs.',
+ { argv: ['gbrain', 'extraction-pending'], mcp: { tool: 'extraction_pending', arguments: {} } });
+}
+
+function reviewOwnerOnly(ctx: OperationContext, p: Record<string, unknown>) {
+ const message = 'extraction_review is owner-only: promote/reject decisions must come from the trusted local CLI.';
+ const action = p.action === 'promote' || p.action === 'reject' ? p.action : undefined;
+ const slugs = Array.isArray(p.slugs) ? p.slugs : [];
+ const exact = action && slugs.length > 0 && slugs.every(s => typeof s === 'string' && REVIEW_SLUG.test(s));
+ return exact
+ ? hostOnlyError(ctx, 'permission_denied', message, ['gbrain', 'extraction-review', action, '--slugs', slugs.join(',')],
+ 'The review decision is the quarantine trust gate, so only the brain owner\'s CLI may make it.',
+ { consent: action === 'reject' ? ['destructive'] : [] })
+ : hostOnlyError(ctx, 'permission_denied', message, ['gbrain', 'extraction-pending'],
+ 'The review decision is the quarantine trust gate; the owner reviews the pending stubs and decides on the host.');
+}
+
const extraction_review: Operation = {
name: 'extraction_review',
idempotent: false,
@@ -166,15 +188,12 @@ const extraction_review: Operation = {
// promote, injected content could self-promote and the quarantine lane
// would be decorative. Fail-closed: only strictly-local callers pass.
if (ctx.remote !== false) {
- throw new OperationError(
- 'permission_denied',
- 'extraction_review is owner-only: promote/reject decisions must come from the trusted local CLI.',
- 'Run `gbrain extraction-review <promote|reject> --slugs ...` on the host machine.',
- );
+ throw reviewOwnerOnly(ctx, p);
}
const action = p.action as string;
if (action !== 'promote' && action !== 'reject') {
- throw new OperationError('invalid_params', `extraction_review: action must be 'promote' or 'reject'; got '${action}'.`);
+ throw opError('invalid_params', `extraction_review: action must be 'promote' or 'reject'; got '${action}'.`,
+ "Nothing changed. Pass 'promote' or 'reject' as the action; fix lists the stubs awaiting review.", { fix: pendingFix() });
}
// CLI passes `--slugs a,b,c` as one string; MCP passes a real array.
const slugs = Array.isArray(p.slugs)
@@ -183,7 +202,9 @@ const extraction_review: Operation = {
? p.slugs.split(',').map((s) => s.trim()).filter(Boolean)
: [];
if (slugs.length === 0) {
- throw new OperationError('invalid_params', 'extraction_review: slugs must be a non-empty array (CLI: --slugs slug1,slug2).');
+ throw opError('invalid_params', 'extraction_review: slugs must be a non-empty array.',
+ `Nothing changed. Pass the stub slugs to act on, for example ${paramUse(ctx, 'slugs', ctx.remote === false ? 'slug1,slug2' : ['slug1', 'slug2'])}; fix lists the stubs awaiting review.`,
+ { fix: pendingFix() });
}
if (ctx.dryRun) return { dry_run: true, action: `extraction_review:${action}`, slugs };
const results: Array<{ slug: string; status: string }> = [];
diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.ts
index 18a9d6523b..0901a28cf8 100644
--- a/src/core/ops/loops.ts
+++ b/src/core/ops/loops.ts
@@ -19,7 +19,9 @@
* stale unless --stale-ok.
*/
-import { OperationError, type Operation, type OperationContext } from './contract.ts';
+import { opError, type Operation, type OperationContext, type OperationError } from './contract.ts';
+import type { Action } from '../agent-output.ts';
+import { hostFix, invalidParam, opTransport, paramUse, readFix } from './op-fix.ts';
import { resolveRequestedScope, sourceScopeOpts } from './context.ts';
import { validateSourceId } from '../utils.ts';
import { closedLoopWithActiveFact, retireLoopFact } from '../persistence/loop-fact-retirement.ts';
@@ -325,7 +327,8 @@ const open_loops: Operation = {
const trusted = ctx.remote === false;
const nowMs = p.as_of === undefined ? Date.now() : Date.parse(String(p.as_of));
if (!Number.isFinite(nowMs)) {
- throw new OperationError('invalid_params', `open_loops: as_of must be an ISO 8601 timestamp, got ${JSON.stringify(p.as_of)}`);
+ throw invalidParam(ctx, 'open_loops', 'as_of', `open_loops: as_of must be an ISO 8601 timestamp, got ${JSON.stringify(p.as_of)}`,
+ { def: open_loops.params.as_of, example: '2026-04-03T09:00:00Z' });
}
const groupBy = (p.group_by as string | undefined) ?? 'counterparty';
const status = ((p.status as string | undefined) ?? 'open') as LoopStatus;
@@ -351,9 +354,11 @@ const open_loops: Operation = {
(allowed && allowed.length > 0 && allowed.includes(p.source_id)) ||
(!(allowed && allowed.length > 0) && ctx.sourceId === p.source_id);
if (!inGrant) {
- throw new OperationError(
+ throw opError(
'permission_denied',
`open_loops: source '${p.source_id}' is outside your granted sources`,
+ `Pass source_id as one of your granted sources (${grantedSources(ctx).join(', ') || 'none'}), or omit it to read your default scope.`,
+ { fix: sourcesFix('Lists the sources this connection can read.') },
);
}
}
@@ -362,9 +367,11 @@ const open_loops: Operation = {
// the op must not rely on them — an unscoped remote read here would span
// every source (the cross-source leak class).
if (!trusted && !scope.sourceId && !scope.sourceIds) {
- throw new OperationError(
+ throw opError(
'permission_denied',
'open_loops: remote callers need a resolved source scope',
+ 'Pass source_id naming one of your granted sources (fix lists them).',
+ { fix: sourcesFix('Lists the sources this connection can read.') },
);
}
const loops = await listOpenLoops(ctx.engine, {
@@ -480,6 +487,43 @@ const open_loops: Operation = {
},
};
+function grantedSources(ctx: OperationContext): string[] {
+ const allowed = ctx.auth?.allowedSources;
+ if (allowed && allowed.length > 0) return [...allowed];
+ return ctx.sourceId ? [ctx.sourceId] : [];
+}
+
+function sourcesFix(why: string): Action {
+ return readFix(why, { argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} } });
+}
+
+function closeFix(ctx: OperationContext, p: Record<string, unknown>): { fix?: Action } {
+ if (typeof p.id !== 'number' || !Number.isSafeInteger(p.id)) return {};
+ return { fix: hostFix(ctx, ['gbrain', 'loops', p.status === 'dropped' ? 'drop' : 'done', String(p.id)],
+ 'The trusted local CLI closes loops in any source; a remote caller closes only inside its bound write source.') };
+}
+
+const MUTE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._%+@-]{0,253}$/;
+
+function muteScopeError(ctx: OperationContext, verb: 'mute' | 'unmute', p: Record<string, unknown>,
+ sourceId: string, writeSource: string | undefined): OperationError {
+ const kind = p.kind === 'sender' || p.kind === 'thread' ? p.kind : undefined;
+ const value = typeof p.value === 'string' && MUTE_VALUE.test(p.value) ? p.value : undefined;
+ return opError('permission_denied', `loops_${verb}: source "${sourceId}" is outside the caller's write scope`,
+ writeSource
+ ? `Nothing changed. This connection writes only to source '${writeSource}': pass source_id '${writeSource}', or have the user run the ${verb} from the trusted local CLI (command in fix).`
+ : `Nothing changed. This connection has no bound write source; the user can run the ${verb} from the trusted local CLI (command in fix).`,
+ kind && value ? { fix: hostFix(ctx, ['gbrain', 'loops', verb, kind, value, '--source', sourceId],
+ 'A suppression is a write; remote callers write only inside their bound source.') } : {});
+}
+
+function noGoogleContent(ctx: OperationContext, message: string): OperationError {
+ const param = opTransport(ctx) === 'cli' ? paramUse(ctx, 'source') : '`source_id`';
+ return opError('invalid_params', message,
+ `Nothing changed. Pass ${param} naming the google source (fix lists sources with their kind).`,
+ { fix: sourcesFix('Lists sources with their kind, so you can pick the google one.') });
+}
+
const loops_close: Operation = {
name: 'loops_close',
idempotent: true,
@@ -516,15 +560,19 @@ const loops_close: Operation = {
if (!writeSource) {
// Enumerated error envelope (dispatch classifies + request-logs it),
// never a success-shaped { closed:false } payload.
- throw new OperationError(
+ throw opError(
'permission_denied',
'loops_close: remote callers need a bound write source',
+ 'Nothing was closed. This connection has no bound write source; the user can close the loop from the trusted local CLI (command in fix).',
+ closeFix(ctx, p),
);
}
if (requested && requested !== writeSource) {
- throw new OperationError(
+ throw opError(
'permission_denied',
`loops_close: source "${requested}" is outside the caller's write scope`,
+ `Nothing was closed. This connection writes only to source '${writeSource}': omit source_id to close there, or have the user close it from the trusted local CLI (command in fix).`,
+ closeFix(ctx, p),
);
}
// No cross-source SELECT: the close runs scoped to the write source,
@@ -579,10 +627,7 @@ const loops_mute: Operation = {
if (ctx.remote !== false) {
const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
if (!writeSource || sourceId !== writeSource) {
- throw new OperationError(
- 'permission_denied',
- `loops_mute: source "${sourceId}" is outside the caller's write scope`,
- );
+ throw muteScopeError(ctx, 'mute', p, sourceId, writeSource);
}
}
// A suppression is only consulted inside a google source — when the
@@ -590,10 +635,7 @@ const loops_mute: Operation = {
// content, the row can never match. Refuse instead of planting a dead
// mute (remote callers bound to a non-google source hit exactly this).
if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {
- throw new OperationError(
- 'invalid_params',
- `loops_mute: source "${sourceId}" holds no Google content — a suppression there can never match; pass source_id naming the google source`,
- );
+ throw noGoogleContent(ctx, `loops_mute: source "${sourceId}" holds no Google content — a suppression there can never match; pass source_id naming the google source`);
}
if (ctx.dryRun) return { dry_run: true, action: 'loops_mute', kind: p.kind, value: p.value };
await addSuppression(ctx.engine, sourceId, p.kind as 'sender' | 'thread', p.value as string);
@@ -625,20 +667,14 @@ const loops_unmute: Operation = {
if (ctx.remote !== false) {
const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
if (!writeSource || sourceId !== writeSource) {
- throw new OperationError(
- 'permission_denied',
- `loops_unmute: source "${sourceId}" is outside the caller's write scope`,
- );
+ throw muteScopeError(ctx, 'unmute', p, sourceId, writeSource);
}
}
// Mirrors loops_mute: an omitted source_id resolving to a source with no
// Google content can never hold a live suppression — refuse rather than
// answer removed:false on a row that should never have existed.
if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {
- throw new OperationError(
- 'invalid_params',
- `loops_unmute: source "${sourceId}" holds no Google content — pass source_id naming the google source`,
- );
+ throw noGoogleContent(ctx, `loops_unmute: source "${sourceId}" holds no Google content — pass source_id naming the google source`);
}
if (ctx.dryRun) return { dry_run: true, action: 'loops_unmute', kind: p.kind, value: p.value };
const removed = await removeSuppression(
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 4c74d173e9..2017b5626b 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -7,7 +7,8 @@ import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
* in ../operations.ts. Never import from '../operations.ts' here (cycle).
*/
-import { OperationError, type Operation, type OperationContext } from './contract.ts';
+import { opError, type Operation, type OperationContext } from './contract.ts';
+import { opTransport, paramUse } from './op-fix.ts';
import {
readPolicyOpts,
readHolders,
@@ -15,14 +16,6 @@ import {
enforceClientSlugFence,
validatePageSlug,
} from './context.ts';
-import {
- addTakeToPage,
- updateTakeOnPage,
- supersedeTakeOnPage,
- resolveTakeOnPage,
- resolveTakesRepoDir,
- TakesWriteError,
-} from '../takes-write.ts';
import { embedQuery } from '../embedding.ts';
import { ALL_SOURCES } from '../source-id.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
@@ -196,6 +189,15 @@ async function countMcpResolved(ctx: OperationContext): Promise<number> {
}
}
+/** runThink names the CLI flag; op callers get the param on their own surface and a caller-class code. */
+function thinkModelError(ctx: OperationContext, e: unknown): unknown {
+ if (!(e instanceof Error) || !e.message.startsWith('think: --model ')) return e;
+ const name = opTransport(ctx) === 'cli' ? paramUse(ctx, 'model') : '`model`';
+ return opError('invalid_params',
+ e.message.replace('think: --model ', 'think: model ').replace(' or omit --model.', ' or omit it.'),
+ `Nothing was synthesized. Omit ${name} to use the configured think model (models.think, then models.default), or pass a model id this brain can reach.`);
+}
+
const think: Operation = {
name: 'think',
idempotent: false,
@@ -247,7 +249,8 @@ const think: Operation = {
...thinkScope,
excludePrivate: (await readPolicyOpts(ctx)).excludePrivate,
remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
- });
+ }).catch((e: unknown) => { throw thinkModelError(ctx, e); });
+ result.answer = result.answer.replace(' or pass `client`', ' on the brain host');
// Persist if --save was passed locally
let savedSlug: string | undefined;
@@ -332,76 +335,6 @@ const think: Operation = {
// ---------------------------------------------------------------------------
const TAKE_KINDS = ['fact', 'take', 'bet', 'hunch'] as const;
-/** Ops hold the MCP request at most this long waiting for the page lock. */
-const OP_LOCK_TIMEOUT_MS = 2000;
-
-/** Remote callers get the read allow-list as the WRITE fence; local CLI is unfenced. */
-function takesWriteAllowList(ctx: OperationContext): readonly string[] | null {
- return ctx.remote !== false ? (ctx.takesHoldersAllowList ?? ['world']) : null;
-}
-
-async function opBrainDir(ctx: OperationContext): Promise<string> {
- const dir = await resolveTakesRepoDir(ctx.engine);
- if (!dir) {
- const err = new OperationError(
- 'unavailable',
- 'Takes are markdown-canonical and this brain has no writable markdown repo configured.',
- 'Configure sync.repo_path on the brain host, then retry.',
- );
- err.detail = 'takes_mirror_unavailable';
- throw err;
- }
- return dir;
-}
-
-function mapTakesWriteError(err: unknown): never {
- if (err instanceof TakesWriteError) {
- switch (err.code) {
- case 'page_not_found':
- throw new OperationError('page_not_found', err.message, 'Sync the brain first, or check the slug/source.');
- case 'row_not_found':
- // Fenced rows deliberately share this shape (no-existence-leak of
- // content/holder — see the trust-model comment above).
- throw new OperationError('not_found', err.message);
- case 'holder_denied': {
- const e = new OperationError('permission_denied', err.message,
- "Ask the brain owner to widen this caller's takes-holder allow-list.");
- e.detail = 'holder_not_in_allowlist';
- throw e;
- }
- case 'mirror_unavailable': {
- const e = new OperationError('unavailable', err.message,
- 'Configure sync.repo_path on the brain host, then retry.');
- e.detail = 'takes_mirror_unavailable';
- throw e;
- }
- case 'page_locked': {
- const e = new OperationError('unavailable', err.message, 'Retry shortly.');
- e.detail = 'retryable';
- throw e;
- }
- case 'already_resolved':
- throw new OperationError('invalid_params', err.message, err.hint ?? 'Resolved takes are immutable; supersede instead.');
- case 'fence_unparsed':
- case 'row_inactive':
- case 'no_fields':
- case 'invalid_input':
- throw new OperationError('invalid_params', err.message, err.hint);
- }
- }
- throw err;
-}
-
-/**
- * P1-4/F4: the markdown write already succeeded; a non-empty `mirror_warning`
- * means only the DB mirror deferred to the next reconcile. Surface it so the
- * agent knows the durable row is on disk and MUST NOT retry.
- */
-function mirrorWarnFields(mirror: { mirror_warning?: string }): Record<string, string> {
- return mirror.mirror_warning
- ? { mirror_warning: `row written to markdown; DB mirror deferred to reconcile: ${mirror.mirror_warning}` }
- : {};
-}
const takes_add: Operation = {
name: 'takes_add',
diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.ts
index 11251cf43f..b7c6b18254 100644
--- a/src/core/ops/timeline.ts
+++ b/src/core/ops/timeline.ts
@@ -8,7 +8,8 @@ import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
* (cycle).
*/
-import { OperationError, type Operation } from './contract.ts';
+import { opError, type Operation } from './contract.ts';
+import { opTransport } from './op-fix.ts';
import { readPolicyOpts } from './context.ts';
import {
enforceSubagentSlugFence,
@@ -41,20 +42,22 @@ const add_timeline_entry: Operation = {
enforceClientSlugFence(ctx, p.slug as string, 'add_timeline_entry');
if (ctx.dryRun) return { dry_run: true, action: 'add_timeline_entry', slug: p.slug };
const date = p.date as string;
+ const badDate = (message: string) => opError('invalid_params', message,
+ `Nothing was written. Pass ${opTransport(ctx) === 'cli' ? 'the date argument' : '`date`'} as a strict YYYY-MM-DD calendar date (year 1900-2199), for example 2026-04-03.`);
// Reject anything that isn't a strict YYYY-MM-DD with year 1900-2199 and
// a real calendar day. PG DATE accepts year 5874897 silently — that's a
// semantic bug nobody actually wants.
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
- throw new OperationError('invalid_params', `Invalid date format "${date}" (expected YYYY-MM-DD)`);
+ throw badDate(`Invalid date format "${date}" (expected YYYY-MM-DD)`);
}
const [y, m, d] = date.split('-').map(Number);
if (y < 1900 || y > 2199 || m < 1 || m > 12 || d < 1 || d > 31) {
- throw new OperationError('invalid_params', `Invalid date "${date}" (year 1900-2199, month 1-12, day 1-31)`);
+ throw badDate(`Invalid date "${date}" (year 1900-2199, month 1-12, day 1-31)`);
}
// Round-trip through Date to catch e.g. Feb 30.
const parsed = new Date(date);
if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
- throw new OperationError('invalid_params', `Invalid calendar date "${date}"`);
+ throw badDate(`Invalid calendar date "${date}"`);
}
return submitPageMutation(ctx, { operation: 'add_timeline_entry', params: p });
},
diff --git a/src/core/ops/transcripts.ts b/src/core/ops/transcripts.ts
index 99b23be656..f436d83cda 100644
--- a/src/core/ops/transcripts.ts
+++ b/src/core/ops/transcripts.ts
@@ -7,7 +7,7 @@
*/
import type { Operation } from './contract.ts';
-import { OperationError } from './contract.ts';
+import { hostOnlyError } from './op-fix.ts';
import { GET_RECENT_TRANSCRIPTS_DESCRIPTION } from '../operations-descriptions.ts';
const get_recent_transcripts: Operation = {
@@ -36,10 +36,13 @@ const get_recent_transcripts: Operation = {
// allow-list (subagents always run with remote=true; they would always be
// rejected, which is a footgun if the op is visible).
if (ctx.remote === true) {
- throw new OperationError(
- 'permission_denied',
- 'get_recent_transcripts is local-only — call via the gbrain CLI.',
- );
+ const n = (v: unknown) => (typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? String(v) : undefined);
+ const days = n(p.days);
+ const limit = n(p.limit);
+ throw hostOnlyError(ctx, 'permission_denied', 'get_recent_transcripts is local-only — call via the gbrain CLI.',
+ ['gbrain', 'transcripts', 'recent', ...(days ? ['--days', days] : []), ...(limit ? ['--limit', limit] : []),
+ ...(p.summary === false ? ['--full'] : []), '--json'],
+ 'Raw transcripts are private host files; only the trusted local CLI reads them.');
}
const { listRecentTranscripts } = await import('../transcripts.ts');
return listRecentTranscripts(ctx.engine, {
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 1aee996815..d2d50f1dad 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 229621,
- "stdoutSha256": "c8e5f93cf4806fe7e4c6df1544c77779543b3d51023504dcc140383bb690eb1e",
+ "stdoutBytes": 229624,
+ "stdoutSha256": "4e21afffab1c6333b71a3065e4df4aa0b56edb43fd78302d7a3897ad89a2733f",
"toolNames": [
"remember",
"entity",
@@ -4760,7 +4760,7 @@
"scope": "read"
},
{
- "description": "Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI AND --trusted-extraction.",
+ "description": "Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI with trusted_extraction set.",
"idempotent": false,
"local_only": false,
"mutating": true,