Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): facts-absorb checks a claimed source root before extraction, so a pre-activation refusal costs no model call (#5362)

garrytanafe0cc596ce5
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e1048206b6..e78f634ed4 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -66,7 +66,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). |
+| <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; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; 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/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.ts
index 738d6cec15..7a806de085 100644
--- a/src/core/minions/handlers/facts-absorb.ts
+++ b/src/core/minions/handlers/facts-absorb.ts
@@ -51,6 +51,27 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {
const input = await readFactsBackstopJobPage(engine, job.data);
if ('skipped' in input) return { skipped: input.skipped, slug, sourceId };
const page = input.page;
+ const refuse = async (err: unknown): Promise<never> => {
+ 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;
+ };
+ // #5362: before activation the legacy fence writer refuses every file in a claimed
+ // worktree, so check the source root before any inference is paid for.
+ const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ if (!brain?.enabled) {
+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);
+ if (source?.local_path) {
+ const { assertLegacyFilesystemWriter } = await import('../../persistence/filesystem-guard.ts');
+ await assertLegacyFilesystemWriter(engine, source.local_path).catch(refuse);
+ }
+ }
const { runFactsBackstop, coerceNotabilityFilter } = await import('../../facts/backstop.ts');
const KNOWN_SOURCES = ['sync:import', 'mcp:put_page', 'mcp:extract_facts', 'file_upload', 'code_import', 'hook:writeback'] as const;
const source = (KNOWN_SOURCES as readonly string[]).includes(job.data.source as string)
@@ -74,17 +95,7 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {
visibility: job.data.visibility === 'world' ? 'world' : 'private',
...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),
},
- ).catch(async (err: unknown) => {
- 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;
- });
+ ).catch(refuse);
// Execution-time chat_unavailable in a KEYED worker is config drift —
// throw (typed) so minion retry/backoff parks it as a VISIBLE, re-runnable
// failure instead of consuming the job and silently losing the facts. A
diff --git a/test/facts-absorb-write-refusal.test.ts b/test/facts-absorb-write-refusal.test.ts
index f8a272ba24..b569947b89 100644
--- a/test/facts-absorb-write-refusal.test.ts
+++ b/test/facts-absorb-write-refusal.test.ts
@@ -4,7 +4,8 @@
* 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.
+ * re-running inference before the same refusal. The claimed root is checked
+ * before extraction, so the refusal costs no model call.
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -62,7 +63,8 @@ test('a claimed-worktree refusal is logged with its code and dead-letters withou
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);
+ // The bound-root precheck refuses before any inference is paid for.
+ expect(chatCalls).toBe(0);
expect(error).toBeInstanceOf(UnrecoverableError);
expect(error.message).toContain('facts_absorb_write_refused (writer_coordinator_required)');
expect(error.message).toContain('gbrain jobs retry 4242');