Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): facts-absorb records write refusals by code and does not retry them (#5362)

garrytan17e0b6f2d74b
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 03481d732e..f355db9d42 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -64,6 +64,7 @@ of making a duplicate.
| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | For a source whose remote is authoritative (it never receives brain writes you need as files), make it a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) once, then advance it and sync without pulling: `gbrain sources mirror-readonly <source> && git -C <checkout> pull --ff-only && gbrain sync --source <source> --no-pull`. The printed `fix` fills in the real source and checkout. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. A coordinated in-gbrain fast-forward refresh is planned; until then this is the supported sequence. |
+| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
### Other error codes
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index 778934120c..fc666eea70 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -38,6 +38,7 @@ export const ERROR_CATALOGUE = {
colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },
embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },
activation_source_path_missing: { code: 'source_changed', docs: 'docs/guides/write-refusals.md#activation_source_path_missing' },
+ facts_absorb_write_refused: { code: 'facts_absorb_write_refused', docs: 'docs/guides/write-refusals.md#facts_absorb_write_refused' },
managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },
} as const satisfies Record<string, CatalogueEntry>;
diff --git a/src/core/facts/absorb-log.ts b/src/core/facts/absorb-log.ts
index c03efb39c4..b4580b56bd 100644
--- a/src/core/facts/absorb-log.ts
+++ b/src/core/facts/absorb-log.ts
@@ -21,6 +21,7 @@
* - 'gateway_auth' — provider authentication/authorization failed.
* - 'gateway_billing' — provider credit, quota, or billing hard limit failed.
* - 'gateway_rate_limit' — provider rate limit; retry policy remains with the caller.
+ * - 'write_refused' — the write path refused the facts write (an OperationError); the detail starts with its code.
* - eligibility_skip is intentionally NOT logged (high cardinality, low signal).
*
* The writer is best-effort — a failure to log SHOULDN'T blow up the
@@ -52,8 +53,25 @@ export const FACTS_ABSORB_REASONS = [
'gateway_auth',
'gateway_billing',
'gateway_rate_limit',
+ 'write_refused',
] as const;
+/**
+ * #5362: write-path refusals that no retry can change until an operator acts
+ * (a claimed canonical worktree before activation, a missing grant, a bad
+ * request, an unregistered writer). The facts-absorb job dead-letters them on
+ * the first attempt instead of re-running inference before the same refusal.
+ */
+export const DETERMINISTIC_WRITE_REFUSALS: readonly string[] = [
+ 'writer_coordinator_required', 'permission_denied', 'invalid_params', 'writer_registration_required',
+];
+
+/** The OperationError code of a write-path refusal, or null. Name check keeps this module import-light. */
+export function writeRefusalCode(err: unknown): string | null {
+ const code = (err as { code?: unknown } | null)?.code;
+ return err instanceof Error && err.name === 'OperationError' && typeof code === 'string' ? code : null;
+}
+
// v0.39.3.0 WARN-4 + CV13 — module-scoped flag so the first-occurrence
// diagnostic log fires ONCE per process. Subsequent occurrences of the
// same 'No database connection' class are suppressed (keeps captures
@@ -134,9 +152,10 @@ export async function writeFactsAbsorbLog(
}
/**
- * Persist a provider failure without copying provider response bodies, keys,
- * or request payloads into ingest_log. Global failures get stable typed
- * reason codes; all other failures retain the existing classifier.
+ * Persist an extraction failure without copying provider response bodies,
+ * keys, or request payloads into ingest_log. A write-path refusal records its
+ * own code (`write_refused`); global provider failures get stable typed reason
+ * codes; all other failures retain the existing classifier.
*/
export async function writeFactsAbsorbFailure(
engine: BrainEngine,
@@ -144,6 +163,12 @@ export async function writeFactsAbsorbFailure(
err: unknown,
sourceId: string = 'default',
): Promise<void> {
+ const errorType = err instanceof Error && err.name ? err.name : 'Error';
+ const refusal = writeRefusalCode(err);
+ if (refusal) {
+ await writeFactsAbsorbLog(engine, ref, 'write_refused', `${refusal} (${errorType}): ${(err as Error).message}`, sourceId);
+ return;
+ }
const globalClass = classifyGlobalLlmError(err);
const reason: FactsAbsorbReason = globalClass === 'auth'
? 'gateway_auth'
@@ -152,8 +177,7 @@ export async function writeFactsAbsorbFailure(
: globalClass === 'rate_limit'
? 'gateway_rate_limit'
: classifyFactsAbsorbError(err);
- const errorType = err instanceof Error && err.name ? err.name : 'Error';
- await writeFactsAbsorbLog(engine, ref, reason, `provider request failed (${errorType})`, sourceId);
+ await writeFactsAbsorbLog(engine, ref, reason, `${reason.startsWith('gateway_') ? 'provider request failed' : 'extraction failed'} (${errorType})`, sourceId);
}
/**
diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.ts
index 4960a5b5c3..738d6cec15 100644
--- a/src/core/minions/handlers/facts-absorb.ts
+++ b/src/core/minions/handlers/facts-absorb.ts
@@ -5,6 +5,8 @@ import type { BrainEngine } from '../../engine.ts';
import type { MinionHandler } from '../types.ts';
import { loadConfig, loadConfigWithEngine } from '../../config.ts';
import type { FactsBackstopResult } from '../../facts/backstop.ts';
+import { UnrecoverableError } from '../errors.ts';
+import { ERROR_CATALOGUE } from '../../error-catalogue.ts';
/** Shared predicate: an inline result reporting execution-time unavailability. */
export function factsAbsorbUnavailable(result: FactsBackstopResult): boolean {
@@ -73,8 +75,14 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {
...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),
},
).catch(async (err: unknown) => {
- const { writeFactsAbsorbFailure } = await import('../../facts/absorb-log.ts');
+ const { writeFactsAbsorbFailure, writeRefusalCode, DETERMINISTIC_WRITE_REFUSALS } = await import('../../facts/absorb-log.ts');
await writeFactsAbsorbFailure(engine, slug, err, sourceId);
+ // #5362: a deterministic write refusal goes straight to dead; retrying re-runs inference before the same refusal.
+ const refusal = writeRefusalCode(err);
+ if (refusal && DETERMINISTIC_WRITE_REFUSALS.includes(refusal)) {
+ throw new UnrecoverableError(`facts_absorb_write_refused (${refusal}): ${(err as Error).message} Not retried. ` +
+ `Fix the cause (gbrain sources writer status ${sourceId}), then gbrain jobs retry ${job.id}. See ${ERROR_CATALOGUE.facts_absorb_write_refused.docs}`);
+ }
throw err;
});
// Execution-time chat_unavailable in a KEYED worker is config drift —
diff --git a/test/facts-absorb-log.test.ts b/test/facts-absorb-log.test.ts
index 543c88d215..c3333d7bb2 100644
--- a/test/facts-absorb-log.test.ts
+++ b/test/facts-absorb-log.test.ts
@@ -129,7 +129,9 @@ describe('writeFactsAbsorbLog — ingest_log row shape', () => {
expect(FACTS_ABSORB_REASONS).toContain('gateway_auth');
expect(FACTS_ABSORB_REASONS).toContain('gateway_billing');
expect(FACTS_ABSORB_REASONS).toContain('gateway_rate_limit');
- expect(FACTS_ABSORB_REASONS.length).toBe(15);
+ // #5362: write-path refusals record their own code.
+ expect(FACTS_ABSORB_REASONS).toContain('write_refused');
+ expect(FACTS_ABSORB_REASONS.length).toBe(16);
});
test.each([
diff --git a/test/facts-absorb-write-refusal.test.ts b/test/facts-absorb-write-refusal.test.ts
new file mode 100644
index 0000000000..f8a272ba24
--- /dev/null
+++ b/test/facts-absorb-write-refusal.test.ts
@@ -0,0 +1,82 @@
+/**
+ * #5362: a facts-absorb job whose facts write is refused by the write path
+ * (here: the fence file sits in a claimed canonical worktree before
+ * activation, so the legacy filesystem guard refuses) records the real code in
+ * ingest_log (`write_refused: writer_coordinator_required …`, not "provider
+ * request failed") and dead-letters on the first attempt instead of
+ * re-running inference before the same refusal.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorb.ts';
+import { UnrecoverableError } from '../src/core/minions/errors.ts';
+import { writeFactsAbsorbFailure, writeRefusalCode } from '../src/core/facts/absorb-log.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-absorb-refusal-'));
+let chatCalls = 0;
+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };
+
+beforeAll(async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ chatCalls++;
+ return { text: JSON.stringify({ facts: [{ fact: 'Prefers weekly status reports.', kind: 'preference', entity: 'people/alice-example', confidence: 1, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };
+ });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);
+ engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+}, 120_000);
+afterAll(async () => {
+ __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway();
+ await disposePersistenceConsumer(engine); await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+const absorbRows = (slug: string) => engine.executeRaw<{ summary: string }>(
+ "SELECT summary FROM ingest_log WHERE source_type='facts:absorb' AND source_ref=$1 ORDER BY id", [slug]);
+
+test('a claimed-worktree refusal is logged with its code and dead-letters without retry', async () => {
+ const root = join(dir, 'brain'); mkdirSync(join(root, 'people'), { recursive: true });
+ const body = 'Alice Example runs the weekly review and prefers written status updates over meetings. '.repeat(12);
+ writeFileSync(join(root, 'people/alice-example.md'), '---\ntitle: Alice Example\ntype: person\n---\nAlice Example.\n');
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, 'notes/weekly-review.md'), `---\ntitle: Weekly review\ntype: note\n---\n${body}\n`);
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['claimed-example', root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example.' }, { sourceId: 'claimed-example' });
+ await engine.putPage('notes/weekly-review', { type: 'note', title: 'Weekly review', compiled_truth: body }, { sourceId: 'claimed-example' });
+ await claimWorktree(engine, 'claimed-example', root);
+ const handler = makeFactsAbsorbHandler(engine);
+ const error = await handler({ id: 4242, name: 'facts-absorb', data: { slug: 'notes/weekly-review', sourceId: 'claimed-example', source: 'sync:import' } } as never)
+ .catch((e: Error) => e) as Error;
+ expect(chatCalls).toBeGreaterThan(0);
+ expect(error).toBeInstanceOf(UnrecoverableError);
+ expect(error.message).toContain('facts_absorb_write_refused (writer_coordinator_required)');
+ expect(error.message).toContain('gbrain jobs retry 4242');
+ expect(error.message).toContain('docs/guides/write-refusals.md#facts_absorb_write_refused');
+ const rows = await absorbRows('notes/weekly-review');
+ expect(rows.at(-1)?.summary).toStartWith('write_refused: writer_coordinator_required (OperationError)');
+ expect(rows.map(r => r.summary).join('\n')).not.toContain('provider request failed');
+ });
+}, 60_000);
+
+test('only provider-class failures say "provider request failed"; write refusals carry their own code', async () => {
+ await writeFactsAbsorbFailure(engine, 'notes/refused', new OperationError('permission_denied', 'The grant does not cover this source.'));
+ await writeFactsAbsorbFailure(engine, 'notes/parse', new Error('Unexpected token in JSON at position 3'));
+ expect((await absorbRows('notes/refused'))[0].summary).toBe('write_refused: permission_denied (OperationError): The grant does not cover this source.');
+ expect((await absorbRows('notes/parse'))[0].summary).not.toContain('provider request failed');
+ expect(writeRefusalCode(new Error('plain'))).toBeNull();
+});