Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): B4 write-receipt remediation without a schema migration; principal-aware receipt recovery; keyless embed advice from readiness

garrytan796249655a22
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 43f2d0906f..c0c17d33ce 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -73,7 +73,7 @@ src/core/persistence/connector-google-receipts.ts 10
src/core/persistence/connector-sync.ts 39
src/core/persistence/context.ts 1
src/core/persistence/control.ts 1
-src/core/persistence/coordinator.ts 17
+src/core/persistence/coordinator.ts 16
src/core/persistence/database-write.ts 2
src/core/persistence/deactivation.ts 2
src/core/persistence/derived-facts.ts 5
@@ -92,7 +92,7 @@ src/core/persistence/facts-prepare.ts 13
src/core/persistence/grandfather.ts 6
src/core/persistence/identity.ts 9
src/core/persistence/import-mutations.ts 3
-src/core/persistence/import-prepare.ts 23
+src/core/persistence/import-prepare.ts 22
src/core/persistence/ipc.ts 9
src/core/persistence/journal.ts 8
src/core/persistence/limits.ts 1
@@ -100,10 +100,10 @@ src/core/persistence/local-client.ts 5
src/core/persistence/loop-fact-retirement.ts 4
src/core/persistence/managed-sources.ts 5
src/core/persistence/memory-mutations.ts 4
-src/core/persistence/memory-prepare.ts 5
+src/core/persistence/memory-prepare.ts 4
src/core/persistence/ownership.ts 20
src/core/persistence/page-mutations.ts 6
-src/core/persistence/page-prepare.ts 13
+src/core/persistence/page-prepare.ts 11
src/core/persistence/page-visibility.ts 1
src/core/persistence/prepared-maintenance.ts 26
src/core/persistence/projection-reindex.ts 7
@@ -118,7 +118,7 @@ src/core/persistence/reconcile-state.ts 11
src/core/persistence/reconcile.ts 11
src/core/persistence/reindex-administration.ts 5
src/core/persistence/root-registry.ts 2
-src/core/persistence/semantic-pages.ts 4
+src/core/persistence/semantic-pages.ts 3
src/core/persistence/service.ts 5
src/core/persistence/skill-activation.ts 1
src/core/persistence/source-lifecycle.ts 25
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 3599944dd7..a1f4a00ecb 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -393,26 +393,83 @@ function diagnosticFix(ctx: AgentErrorContext, why: string): Action {
};
}
+/** The journal fields a receipt-bearing error carries (OperationError.receiptFields), never serialized. */
+type ReceiptFields = NonNullable<OperationError['receiptFields']>;
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const TEMPLATE_VALUE: Record<string, RegExp> = {
+ slug: /^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,511}$/,
+ source_id: /^[a-z0-9][a-z0-9_-]{0,63}$/i,
+ request_id: UUID_RE,
+ operation: /^[a-z][a-z0-9_]{0,63}$/,
+};
+
/**
- * A1 safe-recovery invariant: a mutating op with an unknown or pending
- * outcome is never told to retry. The fix inspects state: the caller's own
- * receipt on its channel, a job's status, or nothing (no receipt → no receipt
- * command; the op's read-side diagnostic stays the fix).
+ * Fill a registry fix template (`{slug}`, `{source_id}`, `{request_id}`,
+ * `{operation}`) from envelope/receipt fields. Every value must pass its strict
+ * id pattern; one missing or unsafe value drops the whole template (B4, A1
+ * argv safety), so no placeholder ever reaches the wire.
*/
-function recoveryFix(p: EnvelopeParts, ctx: AgentErrorContext): Action | undefined {
+export function fillFixTemplate(template: Action, fields: Record<string, string | null | undefined>): Action | undefined {
+ let ok = true;
+ const fill = (v: string): string => v.replace(/\{([a-z_]+)\}/g, (_m, key: string) => {
+ const value = fields[key];
+ if (typeof value !== 'string' || !TEMPLATE_VALUE[key]?.test(value)) { ok = false; return ''; }
+ return value;
+ });
+ const args = (a: Record<string, unknown>) => Object.fromEntries(Object.entries(a).map(([k, v]) => [k, typeof v === 'string' ? fill(v) : v]));
+ const filled: Action = {
+ ...template,
+ ...(template.argv ? { argv: template.argv.map(fill) } : {}),
+ ...(template.mcp ? { mcp: { tool: template.mcp.tool, arguments: args(template.mcp.arguments) } } : {}),
+ };
+ return ok ? filled : undefined;
+}
+
+/** The registry default fix for a code, filled from the fields this error carries (undefined when it has none or cannot be filled). */
+function registryTemplateFix(code: string, fields: Record<string, string | null | undefined> | undefined): Action | undefined {
+ const template = codeEntry(code)?.fix;
+ if (!template || !fields) return undefined;
+ return fillFixTemplate(template, fields);
+}
+
+const RECEIPT_CHANNEL: Record<Transport, string> = { cli: 'local_cli', stdio: 'local_stdio', http: '' };
+
+/**
+ * A1 safe-recovery invariant, principal-aware: a write with an unknown or
+ * pending outcome, or a replayed terminal receipt, is never told to retry. The
+ * fix reads the receipt on the channel that owns it: `gbrain write-request` on
+ * the CLI for a CLI-principal receipt, `get_write_request` over MCP where it is
+ * callable for this principal; another principal's receipt (or no callable
+ * receipt tool) gets the separately authorized host inspection, actor
+ * host_admin. No receipt → no receipt command.
+ */
+function recoveryFix(p: EnvelopeParts, ctx: AgentErrorContext, fields?: ReceiptFields): Action | undefined {
const outcomeOpen = ctx.outcome === 'unknown' || ctx.outcome === 'pending';
- if (!ctx.mutating || !outcomeOpen) return undefined;
- const receipt = p.write_request as { request_id?: unknown } | undefined;
- const requestId = typeof receipt?.request_id === 'string' && /^[0-9a-f-]{36}$/i.test(receipt.request_id) ? receipt.request_id : undefined;
+ if (!fields && (!ctx.mutating || !outcomeOpen)) return undefined;
+ const receipt = p.write_request as { request_id?: unknown; state?: unknown } | undefined;
+ const requestId = typeof receipt?.request_id === 'string' && UUID_RE.test(receipt.request_id) ? receipt.request_id : undefined;
if (!requestId) return undefined;
- const why = 'The write may still commit; its receipt says whether it did. Do not resubmit until the receipt is terminal.';
- if (ctx.transport === 'cli') {
+ const terminal = typeof receipt?.state === 'string' && ['committed', 'conflict', 'failed', 'cancelled'].includes(receipt.state);
+ const why = terminal
+ ? 'The receipt is final; read it (and the target) before deciding whether a new write is needed.'
+ : 'The write may still commit; its receipt says whether it did. Do not resubmit until the receipt is terminal.';
+ const owner = fields?.principal_kind;
+ const samePrincipal = owner !== 'oauth_client' || !ctx.render.principal || fields?.principal_id === ctx.render.principal;
+ const ownChannel = owner === undefined || samePrincipal && (ctx.transport === 'http' ? !owner.startsWith('local_') : owner === RECEIPT_CHANNEL[ctx.transport]);
+ if (ownChannel && ctx.transport === 'cli') {
return { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', why, requires_exclusive: false };
}
+ if (ownChannel && ctx.render.isCallable('get_write_request')) {
+ return { mcp: { tool: 'get_write_request', arguments: { request_id: requestId } }, consent: [], actor: 'agent', why, requires_exclusive: false };
+ }
+ const source = fields && TEMPLATE_VALUE.source_id!.test(fields.source_id) ? [fields.source_id] : [];
return {
- argv: ['gbrain', 'write-request', '--', requestId],
- mcp: { tool: 'get_write_request', arguments: { request_id: requestId } },
- consent: [], actor: 'agent', why, requires_exclusive: false,
+ argv: ['gbrain', 'sources', 'writer', 'status', ...source, '--probe', '--json'],
+ consent: [], actor: 'host_admin',
+ why: `${why} This connection cannot read that receipt itself, so the brain host's operator inspects the write on the owner.`,
+ user_message: 'A write gbrain accepted needs a check on the brain host before anything is resubmitted. Please ask whoever runs this brain to run the command shown.',
+ requires_exclusive: false,
};
}
@@ -439,7 +496,8 @@ const ROWS: Row[] = [
match: e => e instanceof OperationError,
map: (e: OperationError, ctx) => {
const j = e.toJSON() as Record<string, unknown>;
- let fix = e.fix;
+ const receiptId = (j.write_request as { request_id?: string } | undefined)?.request_id;
+ let fix = e.fix ?? registryTemplateFix(e.canonicalCode, e.receiptFields ? { ...e.receiptFields, request_id: receiptId } : undefined);
if (!fix && REFRESH_REFUSALS.has(e.code) && e.suggestion) {
const argv = argvFromCommand(e.suggestion);
if (argv) fix = { argv, consent: [], actor: 'agent', why: e.message, requires_exclusive: false };
@@ -498,6 +556,14 @@ const ROWS: Row[] = [
};
},
},
+ {
+ match: named('EmbeddingDisabledError'),
+ map: (e: Error & { fix?: Action }) => ({
+ error: 'embedding_disabled', code: 'embedding_disabled', reason: 'disabled_by_choice',
+ message: e.message.split('\n')[0]!, why: e.fix?.why, fix: e.fix,
+ suggestion: 'Embeddings are off by choice on this brain; keyword search still works. Turning them on needs the user\'s consent.',
+ }),
+ },
{
match: named('CredentialError'),
map: (e: Error & { code: string; problem: string; cause_text: string; fix: string; doc_url: string }) => ({
@@ -603,7 +669,7 @@ export function toAgentError(e: unknown, ctx: AgentErrorContext): AgentEnvelope
const typed = row && ROWS.indexOf(row) < FIRST_GENERIC_ROW;
let parts = typed ? row.map(e, ctx) : dbParts(e, ctx) ?? (row ? row.map(e, ctx) : unknownParts(e, ctx));
if (!parts.fix) {
- const recovery = recoveryFix(parts, ctx);
+ const recovery = recoveryFix(parts, ctx, e instanceof OperationError ? e.receiptFields : undefined);
if (recovery) parts = { ...parts, fix: recovery };
}
if (!parts.fix && (codeClass(parts.code) === 'server' || codeClass(parts.code) === 'unavailable')) {
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index 465a74fb29..70f371af7a 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -179,8 +179,8 @@ export function dimsProviderOptions(
const max = maxOpenAITextEmbedding3Dim(modelId)!;
throw new AIConfigError(
`OpenAI model "${modelId}" supports embedding_dimensions in 1..${max}, got ${dims}.`,
- `Set \`embedding_dimensions\` to a value between 1 and ${max} ` +
- `(\`gbrain config set embedding_dimensions ${Math.min(1024, max)}\` is a common default).`,
+ `Use a width between 1 and ${max} (${Math.min(1024, max)} is a common default). On an existing brain a width change re-embeds; ` +
+ `preview it with \`gbrain migrate embeddings --to openai:${modelId} --dim ${Math.min(1024, max)} --dry-run\` (pages and facts are kept).`,
);
}
return { openai: { dimensions: dims } };
@@ -267,8 +267,8 @@ export function dimsProviderOptions(
const max = maxOpenAITextEmbedding3Dim(bareModelId)!;
throw new AIConfigError(
`OpenAI model "${modelId}" supports embedding_dimensions in 1..${max}, got ${dims}.`,
- `Set \`embedding_dimensions\` to a value between 1 and ${max} ` +
- `(\`gbrain config set embedding_dimensions ${Math.min(1024, max)}\` is a common default).`,
+ `Use a width between 1 and ${max} (${Math.min(1024, max)} is a common default). On an existing brain a width change re-embeds; ` +
+ `preview it with \`gbrain migrate embeddings --to <provider>:${modelId} --dim ${Math.min(1024, max)} --dry-run\` (pages and facts are kept).`,
);
}
return { openaiCompatible: { dimensions: dims } };
diff --git a/src/core/embed-facts.ts b/src/core/embed-facts.ts
index 4313031e51..62ea7a57bf 100644
--- a/src/core/embed-facts.ts
+++ b/src/core/embed-facts.ts
@@ -93,7 +93,7 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
if (disabled !== null && disabled !== 'true' && disabled !== 'false') {
throw new Error('Selected brain embedding_disabled must be true or false');
}
- assertEmbeddingEnabled({ embedding_disabled: disabled === 'true' });
+ assertEmbeddingEnabled({ engine: target.kind, ...selectedConfig, embedding_disabled: disabled === 'true' });
};
await assertEnabled(engine);
const shape = await readFactsEmbeddingDim(engine);
diff --git a/src/core/embedding-dim-check.ts b/src/core/embedding-dim-check.ts
index f4888f8374..91cfc223b3 100644
--- a/src/core/embedding-dim-check.ts
+++ b/src/core/embedding-dim-check.ts
@@ -14,6 +14,9 @@
*/
import type { BrainEngine } from './engine.ts';
+import type { GBrainConfig } from './config.ts';
+import { shellQuote, type Action } from './agent-output.ts';
+import { embeddingEnablement } from './readiness.ts';
import { OperationError } from './ops/contract.ts';
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS, hnswMaxDimsForType } from './vector-index.ts';
import { gbrainPath } from './config.ts';
@@ -62,22 +65,29 @@ export const PGVECTOR_COLUMN_MAX_DIMS = 16000;
* handlers) bubble it back as a structured job failure.
*/
export class EmbeddingDisabledError extends Error {
- constructor(message: string) {
+ constructor(message: string, public readonly fix?: Action) {
super(message);
this.name = 'EmbeddingDisabledError';
}
}
-export function assertEmbeddingEnabled(cfg: { embedding_disabled?: boolean } | null): void {
- if (cfg?.embedding_disabled) {
- throw new EmbeddingDisabledError(
- 'This brain was initialized with `--no-embedding` (deferred setup).\n' +
- 'Configure an embedding provider before running embed / import:\n' +
- ' gbrain config set embedding_model <provider>:<model>\n' +
- ' gbrain config set embedding_dimensions <N>\n' +
- ' gbrain init --force --embedding-model <provider>:<model> # re-init to size schema\n',
- );
- }
+/**
+ * Keyless-by-choice guard. The enable step comes from readiness's one
+ * `embeddingEnablement` (resolved datastore path, a provider whose key is
+ * present, effects credentials + paid), never `gbrain config set
+ * embedding_model`, which the config command refuses.
+ */
+export function assertEmbeddingEnabled(cfg: GBrainConfig | null): void {
+ if (!cfg?.embedding_disabled) return;
+ const fix = embeddingEnablement(cfg);
+ const step = fix.argv ? shellQuote(fix.argv) : undefined;
+ const lines = [
+ 'This brain was initialized with `--no-embedding` (deferred setup): embeddings are off by choice, so nothing was embedded.',
+ ...(step ? [`To turn on semantic search (pages and facts are kept): ${step}`] : []),
+ `Why: ${fix.why}`,
+ ...(fix.consent.length ? [`This needs ${fix.consent.join(' + ')} consent: ask the user first.${fix.user_message ? ` ${fix.user_message}` : ''}`] : []),
+ ];
+ throw new EmbeddingDisabledError(lines.join('\n'), fix);
}
export interface ColumnDimResult {
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9d25f43de9..1d84a1108c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -26,7 +26,12 @@ export interface CodeEntry {
docs?: string;
/** Default prose suggestion when a site supplies none. */
suggestion?: string;
- /** Default fix template: read-only diagnostics only (scanner-checked). */
+ /**
+ * Default fix template: read-only diagnostics only (scanner-checked).
+ * `{slug}`, `{source_id}`, `{request_id}`, `{operation}` placeholders are
+ * filled from envelope/receipt fields at render time; an unfillable
+ * template is dropped, never rendered with a placeholder.
+ */
fix?: Action;
effects?: readonly Effect[];
actor?: Actor;
@@ -169,8 +174,8 @@ export const CODES = {
not_found: { class: 'caller', summary: "The requested resource does not exist or is not visible to this caller.", legacy_error: 'invalid_params' },
overlapping_path: { class: 'caller', summary: "Sources cannot claim overlapping canonical directories." },
owner_unavailable: { class: 'retryable', summary: "The brain's persistence owner is not reachable right now." },
- page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran." },
- page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed' },
+ page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
+ page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },
parse_error: { class: 'caller', summary: "The request body is not valid JSON." },
pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },
payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
@@ -204,7 +209,7 @@ export const CODES = {
requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },
resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
- revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches." },
+ revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },
revision_required: { class: 'caller', summary: "Review the current policy and supply its expected_policy_epoch before changing disclosure." },
revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },
scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 4a4e64e81c..4f22831c95 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -87,6 +87,12 @@ export class OperationError extends Error {
* value (A1 frozen pairs, e.g. `error: invalid_params`, `code: not_found`).
*/
public canonical?: RegistryCode;
+ /**
+ * Agent contract v1 (B4): the journal row's own fields on a write-receipt
+ * error, never serialized. toAgentError fills the registry's fix template
+ * from them and picks the principal-correct receipt channel.
+ */
+ public receiptFields?: { operation: string; source_id: string; slug: string | null; principal_kind: string; principal_id: string };
constructor(
public code: ErrorCode,
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index cc6b8f2606..8e166c4c51 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:
import { dirname } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
+import { pageIdentityError } from './page-identity.ts';
import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';
import { flushDirectory } from '../fs-durable.ts';
import { isWriteTargetContained } from '../path-confine.ts';
@@ -205,7 +206,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug },...(prepared.additionalPageKeys??[])]);
const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
await authorizePageVisibility(tx, row.authority, row.slug);
- if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.');
+ if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page was deleted or recreated.');
await assertUnboundPublication(tx, row, snapshot?.page.source_path);
if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');
}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index c2e8c9c77f..e6b848b33b 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -330,7 +330,7 @@ export async function assertEmbeddingEffectEnabled(engine: BrainEngine, config:
if (disabled !== null && disabled !== 'true' && disabled !== 'false') {
throw new OperationError('embedding_configuration', 'Selected brain embedding_disabled must be true or false.');
}
- assertEmbeddingEnabled({ embedding_disabled: disabled === 'true' });
+ assertEmbeddingEnabled({ engine: engine.kind, ...config, embedding_disabled: disabled === 'true' });
}
function embeddingStorageFailure(error: unknown): unknown {
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 0022986ffd..b0e9c706d0 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -8,7 +8,8 @@ import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { applyInference } from '../frontmatter-inference.ts';
import { getCompanyBrainProfile } from '../company-brain/profile.ts';
import { hasMalformedPathSegment, isCodeFilePath, slugifyCodePath, slugifyPath } from '../sync.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { yamlLocator } from './page-identity.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
@@ -51,7 +52,10 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa
if (!/\.mdx?$/i.test(sourcePath)) throw new OperationError('invalid_params', 'Managed import supports Markdown, code and supported image files.');
const original = parseMarkdown(content, sourcePath, { validate: true });
const invalid = original.errors?.find(error => error.code === 'YAML_PARSE');
- if (invalid) throw new OperationError('invalid_params', `Invalid YAML frontmatter: ${invalid.message}`);
+ if (invalid) {
+ throw opError('invalid_params', `Invalid YAML frontmatter${yamlLocator(invalid.message)} in ${sourcePath}.`,
+ `Quote frontmatter values that contain ": " or start with a special character in ${sourcePath}, then run the import again.`);
+ }
content = applyInference(sourcePath, content).content;
const parsed = parseMarkdown(content, sourcePath, { validate: true, ...(activePack ? { activePack } : {}) });
const expected = slugifyPath(sourcePath);
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index af7eb82b7c..f97ad4f580 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -1,6 +1,7 @@
import type { BrainEngine, NewFact } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError } from '../ops/contract.ts';
+import { pageIdentityError } from './page-identity.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
@@ -38,7 +39,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const input: SingleFactIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as SingleFactIntent['kind'],
visibility: (p.visibility ?? 'world') as SingleFactIntent['visibility'], entity_slug: p.entity_slug as string | null };
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
- if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted entity was deleted or recreated.');
+ if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');
if (p.expected_revision !== undefined) assertPageRevision(snapshot, engineMutationPrecondition(parseMutationPrecondition(p)));
const observedRevision = snapshot?.revision ?? null;
await assertFactNotWithdrawn(engine, row.source_id, input);
diff --git a/src/core/persistence/page-identity.ts b/src/core/persistence/page-identity.ts
new file mode 100644
index 0000000000..e31d9143d5
--- /dev/null
+++ b/src/core/persistence/page-identity.ts
@@ -0,0 +1,38 @@
+/**
+ * Agent contract v1 (B4): one accepted page, two failure shapes. The page is
+ * gone → canonical `page_not_found`; it was replaced by another page →
+ * `page_identity_changed`. Both keep the frozen wire `error`
+ * `page_identity_changed`, which is also what the journal stores, so a replay
+ * recovers the distinction from the stored message alone (no schema change).
+ */
+import { opError, type OperationError } from '../ops/contract.ts';
+
+export const PAGE_MISSING_MESSAGE = 'The accepted page no longer exists.';
+
+/** Messages journaled for a missing page (current and pre-v1 rows). */
+const MISSING_MESSAGES: ReadonlySet<string> = new Set([PAGE_MISSING_MESSAGE]);
+
+export function isMissingPageMessage(message: string | null | undefined): boolean {
+ return message != null && MISSING_MESSAGES.has(message);
+}
+
+/** The error for an accepted page whose identity no longer matches: `present` says whether any page holds the slug now. */
+export function pageIdentityError(present: boolean, replacedMessage: string): OperationError {
+ if (!present) {
+ return opError('page_not_found', PAGE_MISSING_MESSAGE,
+ 'The page was deleted before this write published. Check whether it exists now; recreating it is a new write with a new request_id.',
+ { legacy_error: 'page_identity_changed' });
+ }
+ return opError('page_identity_changed', replacedMessage,
+ 'Another page took this slug while the write was queued. Read the current page before deciding to submit again with a new request_id.');
+}
+
+/**
+ * B4: a content-free locator for a YAML frontmatter failure (` at line 3,
+ * column 5`). Only the numbers are kept: parser messages quote the offending
+ * text, and receipts persist this message.
+ */
+export function yamlLocator(text: string | null | undefined): string {
+ const m = /\bline (\d+)(?:,? column (\d+))?/i.exec(text ?? '') ?? /\((\d+):(\d+)\)/.exec(text ?? '');
+ return m ? ` at line ${m[1]}${m[2] ? `, column ${m[2]}` : ''}` : '';
+}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 46e7973d8b..7fef44b1d7 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -7,7 +7,8 @@ import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
import { importFromContent, type ParsedPage } from '../import-file.ts';
import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { pageIdentityError, yamlLocator } from './page-identity.ts';
import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
@@ -173,7 +174,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
signal?.throwIfAborted();
assertPageRevision(snapshot, preparedIntent ? { expectedRevision: preparedIntent.expectedRevision } : engineMutationPrecondition(parseMutationPrecondition(p)));
- if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page identity changed.');
+ if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page identity changed.');
const observedRevision = snapshot?.revision ?? null;
const activePack = (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;
if (row.operation === 'put_page' && p.allow_empty !== true && snapshot && !snapshot.page.deleted_at
@@ -273,9 +274,13 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
signal?.throwIfAborted();
if (!prepared) {
const oversized = result.error?.startsWith('Content too large') === true;
- throw new OperationError(oversized ? 'request_too_large' : 'invalid_params', oversized ? result.error!
- : /yaml/i.test(result.error ?? '') ? 'Invalid YAML frontmatter. Quote scalar values or fix the frontmatter block.'
- : 'The content was rejected before publication.');
+ const yaml = !oversized && /yaml/i.test(result.error ?? '');
+ throw opError(oversized ? 'request_too_large' : 'invalid_params', oversized ? result.error!
+ : yaml ? `Invalid YAML frontmatter${yamlLocator(result.error)}. Quote scalar values or fix the frontmatter block.`
+ : 'The content was rejected before publication.',
+ oversized ? 'Split the content into smaller pages, then submit each with its own request_id.'
+ : yaml ? 'Quote frontmatter values that contain ": " or start with a special character, then submit the corrected content with a new request_id.'
+ : 'Check the content and frontmatter, then submit the corrected content with a new request_id.');
}
const ready = prepared;
if (ready.observedRevision !== observedRevision) throw new OperationError('revision_conflict', 'The page changed during import preparation.');
diff --git a/src/core/persistence/semantic-pages.ts b/src/core/persistence/semantic-pages.ts
index a1ef594926..e92eb67f24 100644
--- a/src/core/persistence/semantic-pages.ts
+++ b/src/core/persistence/semantic-pages.ts
@@ -2,6 +2,7 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { OperationError } from '../ops/contract.ts';
+import { pageIdentityError } from './page-identity.ts';
import { renderTimelineEntry, spliceTimelineBlock } from '../timeline-write-through.ts';
import { extractTimelineFromContent } from '../timeline-extract.ts';
import { preparePageMutation } from './page-prepare.ts';
@@ -39,7 +40,7 @@ export function regeneratedByWriter(sourceKind: string | null | undefined, page:
export async function prepareSemanticPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
- if (!snapshot || snapshot.page.id !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page no longer exists.');
+ if (!snapshot || snapshot.page.id !== row.page_id) throw pageIdentityError(snapshot != null, 'The accepted page was replaced by another page.');
const p = row.intent!;
if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));
if (row.operation === 'add_tag' || row.operation === 'remove_tag') {
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index cc9843cb05..d9e1bd0a12 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -11,6 +11,7 @@ import { registerPgliteReopen } from '../pglite-lifecycle.ts';
import { assertMutationProtocol } from './protocol.ts';
import { pendingWriteHint } from './health.ts';
import { receiptDeliveredHint } from './connector-errors.ts';
+import { isMissingPageMessage } from './page-identity.ts';
interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }
const services = new WeakMap<BrainEngine, Service>();
@@ -133,6 +134,13 @@ export async function waitForWrite(engine: BrainEngine, row: WriteRequest, confi
}
return row;
}
+/** B4: what a terminal receipt means for the caller, without guessing a mutation. */
+function terminalReceiptHint(row: WriteRequest, reason: string): string {
+ const what = `The ${row.operation ? `${row.operation} ` : ''}write (request_id ${row.request_id}) ended ${row.state} with ${reason}; it will not publish.`;
+ return row.state === 'cancelled'
+ ? `${what} Submit again only if the change is still wanted, with a new request_id.`
+ : `${what} Read the current state before deciding to submit again; a new attempt needs a new request_id.`;
+}
export function writeResponse(row: WriteRequest): Record<string, unknown> {
const receipt = receiptFor(row);
if (row.state === 'committed') return { ...receipt, write_request: receipt };
@@ -141,8 +149,10 @@ export function writeResponse(row: WriteRequest): Record<string, unknown> {
const error = new OperationError(reason, !isTerminal(row) ? 'The write is accepted and is still pending.'
: row.error_message ?? 'The write did not commit.', !isTerminal(row)
? pendingWriteHint(receipt)
- : delivered?.suggestion ?? 'Inspect this receipt before submitting a new request_id.', delivered?.docs);
+ : delivered?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);
if (delivered?.detail) error.detail = delivered.detail;
+ if (reason === 'page_identity_changed' && isMissingPageMessage(row.error_message)) error.canonical = 'page_not_found';
+ error.receiptFields = { operation: row.operation, source_id: row.source_id, slug: row.slug || null, principal_kind: row.principal_kind, principal_id: row.principal_id };
error.writeRequest = receipt as WriteReceipt;
error.writeError = isWriteErrorCode(reason) ? reason : reason === 'page_identity_changed' ? 'source_changed' : 'storage_error';
throw error;
diff --git a/test/ai/dims-openai.test.ts b/test/ai/dims-openai.test.ts
index 3583639697..e96b409091 100644
--- a/test/ai/dims-openai.test.ts
+++ b/test/ai/dims-openai.test.ts
@@ -101,7 +101,8 @@ describe('dimsProviderOptions — OpenAI native path', () => {
expect(msg).toContain('3072');
// Paste-ready fix appears in the `fix` property of AIConfigError.
const fix = (err as AIConfigError).fix ?? '';
- expect(fix).toContain('gbrain config set embedding_dimensions');
+ expect(fix).toContain('gbrain migrate embeddings --to openai:text-embedding-3-large --dim 1024 --dry-run');
+ expect(fix).not.toContain('config set embedding_dimensions');
}
});
diff --git a/test/connector-wave3.test.ts b/test/connector-wave3.test.ts
index f4aab48f4c..683e728552 100644
--- a/test/connector-wave3.test.ts
+++ b/test/connector-wave3.test.ts
@@ -281,7 +281,7 @@ test('mixed versions: a v2 receipt refused by an old consumer names the consumer
const denied = refusal(receipt('permission_denied', kind));
expect(denied.code).toBe('permission_denied');
expect(denied.detail).toBeUndefined();
- expect(denied.suggestion).toBe('Inspect this receipt before submitting a new request_id.');
+ expect(denied.suggestion).toMatch(/^The submit_job write \(request_id [0-9a-f-]{36}\) ended failed with permission_denied; it will not publish\. Read the current state before deciding to submit again; a new attempt needs a new request_id\.$/);
}
// A binary that predates the v2 namespace falls through to the same code for any kind it does not know.
await expect(preparePersistedMutation({} as BrainEngine, receipt('', 'connector_v3_import') as WriteRequest & { operation: string }, { engine: 'pglite' }))
diff --git a/test/embedding-disabled-advice.test.ts b/test/embedding-disabled-advice.test.ts
new file mode 100644
index 0000000000..8d39f8f27a
--- /dev/null
+++ b/test/embedding-disabled-advice.test.ts
@@ -0,0 +1,41 @@
+/**
+ * The keyless guard's advice comes from readiness's embeddingEnablement:
+ * never the refused `gbrain config set embedding_model`, always the resolved
+ * datastore path, and it asks the user (credentials + paid).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { assertEmbeddingEnabled, EmbeddingDisabledError } from '../src/core/embedding-dim-check.ts';
+import { cliRenderContext, toAgentError } from '../src/core/agent-output.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const keyless = { engine: 'pglite' as const, embedding_disabled: true, database_path: '/tmp/gbrain-example/brain.pglite' };
+
+function thrown(): EmbeddingDisabledError {
+ try { assertEmbeddingEnabled(keyless as never); } catch (e) { return e as EmbeddingDisabledError; }
+ throw new Error('expected EmbeddingDisabledError');
+}
+
+describe('assertEmbeddingEnabled advice', () => {
+ test('an enabled brain passes', () => {
+ expect(() => assertEmbeddingEnabled({ engine: 'pglite' } as never)).not.toThrow();
+ expect(() => assertEmbeddingEnabled(null)).not.toThrow();
+ });
+
+ test('never recommends the refused config set embedding_model', async () => {
+ await withEnv({ OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, GBRAIN_HOME: '/tmp/gbrain-example-home' }, async () => {
+ const e = thrown();
+ expect(e.message).not.toContain('config set embedding_model');
+ expect(e.message).toContain('gbrain init --force --embedding-model');
+ expect(e.fix).toMatchObject({ consent: ['credentials', 'paid'], requires_exclusive: true });
+ expect(e.fix?.argv).toContain('--path');
+ });
+ });
+
+ test('normalises to embedding_disabled with the enablement fix; the agent asks first', async () => {
+ await withEnv({ VOYAGE_API_KEY: 'test-key', GBRAIN_HOME: '/tmp/gbrain-example-home' }, async () => {
+ const env = toAgentError(thrown(), { transport: 'cli', command: 'embed', render: cliRenderContext() });
+ expect(env).toMatchObject({ error: 'embedding_disabled', code: 'embedding_disabled', reason: 'disabled_by_choice', fix: { next: 'ask_user' } });
+ expect(env.fix?.command).toContain('gbrain init --force --embedding-model');
+ });
+ });
+});
diff --git a/test/persistence-unbound-source.test.ts b/test/persistence-unbound-source.test.ts
index 749c435a07..0970d90f2a 100644
--- a/test/persistence-unbound-source.test.ts
+++ b/test/persistence-unbound-source.test.ts
@@ -49,6 +49,7 @@ describe('receipt-delivered unbound_source failure', () => {
test('leaves other owner_unavailable receipts unchanged', () => {
const error = delivered('The accepted worktree ownership or source topology changed.');
expect(error.detail).toBeUndefined();
- expect(error.suggestion).toBe('Inspect this receipt before submitting a new request_id.');
+ expect(error.suggestion).toContain('ended failed with owner_unavailable; it will not publish. Read the current state before deciding to submit again; a new attempt needs a new request_id.');
+ expect(error.suggestion).not.toContain('unbound');
});
});
diff --git a/test/readiness-advice-lint.test.ts b/test/readiness-advice-lint.test.ts
index 412bd0f50b..9c9d2c81a6 100644
--- a/test/readiness-advice-lint.test.ts
+++ b/test/readiness-advice-lint.test.ts
@@ -26,9 +26,7 @@ const ALLOWLIST: Record<string, { count: number; reason: string }> = {
'src/commands/reindex-code.ts': { count: 2, reason: 'Lane E: reindex-code embedding hint' },
'src/commands/reinit-pglite.ts': { count: 2, reason: 'usage examples of reinit-pglite\'s own --embedding-model flag' },
'src/core/advisor/collect-setup-smells.ts': { count: 2, reason: 'Lane E: advisor setup smells read readiness' },
- 'src/core/ai/dims.ts': { count: 2, reason: 'Lane B: dims validation error hints' },
'src/core/embed-preflight.ts': { count: 5, reason: 'Lane E: embed preflight refusals carry the readiness fix' },
- 'src/core/embedding-dim-check.ts': { count: 2, reason: 'Lane E: keyless embed/import refusal (advises a refused config set)' },
};
const WIPE = /\bmv\s+\S+\s+\S+\.bak\b|\bmv\s+\S*brain\.pglite/;
diff --git a/test/write-receipt-remediation.test.ts b/test/write-receipt-remediation.test.ts
new file mode 100644
index 0000000000..44113e6248
--- /dev/null
+++ b/test/write-receipt-remediation.test.ts
@@ -0,0 +1,128 @@
+/**
+ * B4 + A1 principal rule: a replayed write receipt derives its fix from the
+ * registry template filled from the journal row's own fields (no schema
+ * change: the journal keeps code + message), keeps the frozen `error`, and
+ * reads the receipt on the channel that owns it.
+ */
+import { describe, expect, test } from 'bun:test';
+import { writeResponse } from '../src/core/persistence/service.ts';
+import { pageIdentityError, PAGE_MISSING_MESSAGE, yamlLocator } from '../src/core/persistence/page-identity.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { fillFixTemplate, toAgentError, type RenderContext, type Transport } from '../src/core/agent-output.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+
+const REQUEST_ID = '6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b';
+
+/** A journal row exactly as a pre-wave release stored it: code + message, no new columns. */
+function oldStyleRow(over: Partial<WriteRequest> = {}): WriteRequest {
+ return {
+ id: '1', request_id: REQUEST_ID, operation: 'put_page', source_id: 'notes', slug: 'people/alice-example',
+ principal_kind: 'local_stdio', principal_id: 'p-stdio', state: 'failed',
+ error_code: 'page_identity_changed', error_message: PAGE_MISSING_MESSAGE,
+ outcome: null, created_at: new Date(0), updated_at: new Date(0), ...over,
+ } as unknown as WriteRequest;
+}
+
+function replay(row: WriteRequest): OperationError {
+ try { writeResponse(row); } catch (e) { return e as OperationError; }
+ throw new Error('writeResponse did not throw for a terminal failure');
+}
+
+const render = (transport: Transport, callable: string[] = [], principal?: string): RenderContext => ({
+ transport, isCallable: t => callable.includes(t), preapproved: () => false, ...(principal ? { principal } : {}),
+});
+const envelope = (e: unknown, transport: Transport, callable: string[] = [], principal?: string) =>
+ toAgentError(e, { transport, op: 'put_page', mutating: true, outcome: 'failed', render: render(transport, callable, principal) });
+
+describe('replayed receipts (B4)', () => {
+ test('an old-style missing-page row: error stays page_identity_changed, code becomes page_not_found, fix reads the page', () => {
+ const e = replay(oldStyleRow());
+ expect(e.code).toBe('page_identity_changed');
+ expect(e.suggestion).not.toContain('Inspect this receipt');
+ const mcp = envelope(e, 'stdio', ['get_page', 'get_write_request']);
+ expect(mcp).toMatchObject({
+ error: 'page_identity_changed', code: 'page_not_found', write_error: 'page_identity_changed',
+ write_request: { request_id: REQUEST_ID, state: 'failed' },
+ fix: { mcp: { tool: 'get_page', arguments: { slug: 'people/alice-example', source_id: 'notes' } }, actor: 'agent', next: 'run', consent: [] },
+ });
+ const cli = envelope(e, 'cli');
+ expect(cli.fix).toMatchObject({ argv: ['gbrain', 'get', '--source', 'notes', '--', 'people/alice-example'], next: 'run' });
+ expect(cli.suggestion).toContain('gbrain get --source notes -- people/alice-example');
+ });
+
+ test('a replaced page keeps code page_identity_changed', () => {
+ const e = replay(oldStyleRow({ error_message: 'The accepted page identity changed.' }));
+ expect(envelope(e, 'cli')).toMatchObject({ error: 'page_identity_changed', code: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', 'notes', '--', 'people/alice-example'] } });
+ });
+
+ test('revision_conflict fills the same read from receipt fields', () => {
+ const e = replay(oldStyleRow({ state: 'conflict', error_code: 'revision_conflict', error_message: 'The page changed during preparation.' }));
+ expect(envelope(e, 'cli').fix?.command).toBe('gbrain get --source notes -- people/alice-example');
+ });
+
+ test('an unsafe slug drops the template; the fix falls back to the receipt read', () => {
+ const e = replay(oldStyleRow({ slug: '--yes', principal_kind: 'local_cli' }));
+ const env = envelope(e, 'cli');
+ expect(env.fix?.argv).toEqual(['gbrain', 'write-request', '--', REQUEST_ID]);
+ expect(JSON.stringify(env)).not.toContain('{slug}');
+ });
+});
+
+describe('principal-aware receipt recovery (A1)', () => {
+ const storage = (over: Partial<WriteRequest>) => replay(oldStyleRow({ error_code: 'storage_error', error_message: 'disk full', ...over }));
+
+ test('CLI principal on the CLI: gbrain write-request', () => {
+ expect(envelope(storage({ principal_kind: 'local_cli' }), 'cli').fix).toMatchObject({ argv: ['gbrain', 'write-request', '--', REQUEST_ID], actor: 'agent', next: 'run' });
+ });
+
+ test('stdio principal over stdio: get_write_request when callable, never the CLI command (a different principal)', () => {
+ const env = envelope(storage({ principal_kind: 'local_stdio' }), 'stdio', ['get_write_request']);
+ expect(env.fix).toMatchObject({ mcp: { tool: 'get_write_request', arguments: { request_id: REQUEST_ID } }, actor: 'agent', next: 'run' });
+ expect(env.fix?.argv).toBeUndefined();
+ });
+
+ test('receipt tool not callable: host inspection, actor host_admin', () => {
+ const env = envelope(storage({ principal_kind: 'local_stdio' }), 'stdio', []);
+ expect(env.fix).toMatchObject({ argv: ['gbrain', 'sources', 'writer', 'status', 'notes', '--probe', '--json'], actor: 'host_admin', next: 'tell_user_to_run' });
+ });
+
+ test("another OAuth client's receipt over http: host inspection", () => {
+ const own = envelope(storage({ principal_kind: 'oauth_client', principal_id: 'gbrain_cl_a' }), 'http', ['get_write_request'], 'gbrain_cl_a');
+ expect(own.fix?.mcp?.tool).toBe('get_write_request');
+ const other = envelope(storage({ principal_kind: 'oauth_client', principal_id: 'gbrain_cl_b' }), 'http', ['get_write_request'], 'gbrain_cl_a');
+ expect(other.fix).toMatchObject({ actor: 'host_admin', next: 'tell_user_to_run' });
+ expect(other.fix?.mcp).toBeUndefined();
+ });
+
+ test('a pending write never says retry and is not retryable for a non-idempotent op', () => {
+ const e = replay(oldStyleRow({ state: 'running', error_code: null, error_message: null, principal_kind: 'local_cli' }));
+ expect(e.code).toBe('write_pending');
+ const env = toAgentError(e, { transport: 'cli', op: 'put_page', mutating: true, idempotent: false, outcome: 'pending', render: render('cli') });
+ expect(env.retryable).toBe(false);
+ expect(env.fix?.argv).toEqual(['gbrain', 'write-request', '--', REQUEST_ID]);
+ });
+});
+
+describe('live page identity errors and YAML locators', () => {
+ test('a missing page throws the frozen error with canonical page_not_found', () => {
+ const missing = pageIdentityError(false, 'replaced');
+ expect(missing.code).toBe('page_identity_changed');
+ expect(missing.canonicalCode).toBe('page_not_found');
+ expect(missing.message).toBe(PAGE_MISSING_MESSAGE);
+ const replaced = pageIdentityError(true, 'The accepted page identity changed.');
+ expect(replaced.canonicalCode).toBe('page_identity_changed');
+ });
+
+ test('yamlLocator keeps only line/column numbers', () => {
+ expect(yamlLocator('YAML parse failed: Malformed YAML frontmatter at line 4')).toBe(' at line 4');
+ expect(yamlLocator('bad indentation of a mapping entry (3:5)\n\n 3 | secret: [x')).toBe(' at line 3, column 5');
+ expect(yamlLocator('no position here: secret')).toBe('');
+ });
+
+ test('fillFixTemplate refuses unknown or missing fields', () => {
+ const t = { argv: ['gbrain', 'get', '--', '{slug}'], consent: [], actor: 'agent' as const, why: 'w', requires_exclusive: false };
+ expect(fillFixTemplate(t, { slug: 'a/b' })?.argv).toEqual(['gbrain', 'get', '--', 'a/b']);
+ expect(fillFixTemplate(t, {})).toBeUndefined();
+ expect(fillFixTemplate(t, { slug: 'a b; rm' })).toBeUndefined();
+ });
+});