Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): remember onto a page of an unbound Postgres source follows the put_page rule (#6608)

time-attack47e811d56d1f
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 3c9e50a4a1..cf648d5988 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -50,7 +50,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. FENCE REPAIR RECEIPT: `fence_repair` is a reserved `put_page` param; `preparePageAdmission` refuses it (`invalid_params`) on every operation unless the call is a trusted local (`ctx.remote === false`) `put_page` whose value `parseFenceRepairReceipt` accepts; `page-prepare.ts` re-parses it from the stored intent, returns it in the outcome as `fence_repair` and gives the page's file target the `fenceRepairCommit` note for its source-relative path. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode` and `commit`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).
-- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
+- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot (`mayReprepare`: `revision_conflict` or, #5385 [R13], `revision_required`, both only when the caller named no `expected_revision`); exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The `add_timeline_entry` receipt carries `bullet`, the rendered Markdown line (#5970): there is no update/remove verb because the page is the system of record, so the caller corrects an entry by editing that line with `edit_page` and the row follows the page (both timeline op descriptions say so; `test/timeline-correction-path-5970.test.ts`). #5251: `add_tag` / `remove_tag` prepare with `deferEmbedding: true` (a tag change leaves every chunk's text as it was, so no `embedding` effect is queued and `embedding_state` reads `deferred`; the stale sweep still covers any chunk the republication left without a vector); the full page republication they ride stays, so the issue stays open. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 81bb3c5ad3..8db7ff36a5 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -74,7 +74,7 @@ of making a duplicate.
| <a id="connector-holds-exhausted"></a>`connector_holds_exhausted` | `connector_holds_exhausted` | A Google or GitHub source already holds 100 items and this sync would hold another. The sync stopped without advancing its cursor. So many held items usually means a source-wide problem (a broken renderer, a revoked scope), not bad items. | `gbrain sources status <source>` to see the held items and their error codes, fix the cause, then `gbrain sources retry-held <source>` and `gbrain sync --source <source>`. `gbrain sync --source <source> --full` also clears every hold. |
| <a id="connector-fence-below-timeline"></a>`fence_not_carried` | `connector_fence_below_timeline` | A managed connector re-render would have dropped a facts or takes fence the stored page keeps below its timeline sentinel, or one that is duplicated, unbalanced or unparseable. The write was refused so those rows are not expired; the item is counted toward a hold. | Preview `gbrain repair connector-fences --source <source>`, apply it after review with `--apply`, then `gbrain sources retry-held <source>`. A page the repair counts as ambiguous needs a manual edit (see [repair](repair.md)). |
| <a id="unsupported-mutation-protocol"></a>`consumer_upgrade_required` | `unsupported_mutation_protocol` | A connector on v0.60.11.0 or later sent a `connector_v2_*` write to a persistence consumer older than v0.60.11.0, which does not know the format. Other `permission_denied` refusals on connector receipts are never relabeled as upgrades. | `gbrain upgrade` on every consumer and worktree-owner host, then `gbrain sync --source <source>`. Upgrade those hosts before connector hosts. |
-| `unbound_source` | `owner_unavailable` | On Postgres, a page write went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Classic mode: write the file, commit, `gbrain sync --source <source>` (a remote agent asks the user to). Otherwise bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. Not retryable. See [unbound sources on Postgres](#unbound-sources-on-postgres). |
+| `unbound_source` | `owner_unavailable` (`remember`: `unavailable` with `write_error: owner_unavailable`) | On Postgres, a page write or a `remember` about an existing page went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Classic mode: write the file, commit, `gbrain sync --source <source>` (a remote agent asks the user to). Otherwise bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. Not retryable. See [unbound sources on Postgres](#unbound-sources-on-postgres). |
| <a id="embedding_zero_norm"></a>`zero_norm`, `non_finite` or `empty_input` | `embedding_zero_norm` | The embedding provider returned a vector with no direction (all zeros, NaN or infinity) for a chunk, or the chunk text was empty. A vector index silently skips such a row, so gbrain refuses to store it. Only that chunk is refused: the page text and every other chunk's vector are saved, and the page is left for `gbrain embed --stale`. It is never retried as a rate limit or network error. | Inspect the named page's chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, fix it, then run `gbrain embed <slug>` (add `--source <source>` for a non-default source). If normal text also returns zero vectors, the provider or model is broken; check it with `gbrain doctor`. |
| `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. An effect `error_code` of `git_index_stale` means an index lock older than 10 minutes blocks the checkout: `.git/index.lock` in it (`git -C <checkout> rev-parse --git-path index.lock` for a linked worktree). Remove it only if no git command is running there, then run the `retry-effects` command. A fresher lock (`git_index_locked`) is retried as contention and never parks. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |
| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |
@@ -526,7 +526,9 @@ of a self-hosted Postgres brain that never ran
of truth: gbrain reads it and does not write files into it. Page writes through
`put_page`, `capture`, `delete_page`, `restore_page`, `revert_version`,
`add_tag`, `remove_tag`, `add_timeline_entry` and the `takes_*` tools refuse
-with `unbound_source`. What works:
+with `unbound_source`, and so does `remember` about an existing entity page
+(its frozen code stays `unavailable`, with `write_error: owner_unavailable`
+and the same detail and fix). What works:
1. **Write the file, commit, sync** (the classic write path). Write or edit
`<checkout>/<slug>.md`, check generated frontmatter with
@@ -567,8 +569,9 @@ out with the real source filled in:
brain host). Every page write to a page with no recorded canonical file
(a new page, or one with no stored source path) then writes to the
database only: `put_page`, `capture`, `delete_page`, `restore_page`,
- `revert_version`, `add_tag`, `remove_tag`, `add_timeline_entry` and the
- `takes_*` writes. Its result says
+ `revert_version`, `add_tag`, `remove_tag`, `add_timeline_entry`, the
+ `takes_*` writes, and a `remember` (or loop-close retirement) whose fact
+ is fenced into that page's database body. Its result says
`write_through: { written: false, skipped: "unbound_source" }` with a
warning. Pages written this way stay database-only: binding the source
later does not materialize them into canonical files, later writes keep
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ce3b34c701..9d92b63af8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -631,6 +631,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.243.0', text: 'A write refused because its page\'s canonical file holds a committed Git change that managed sync has not imported yet now says so (`source_changed`, reason `pending_import`, "The canonical file holds a committed Git change that sync has not imported yet.") instead of "an uncoordinated local edit". A `remember` refused that way, or refused because sync held the file, is kept: after each managed sync, gbrain replays those remembers whose page now matches its file, once, with the fact\'s original date and the caller\'s original authority (at most 50 per sync; the sync result\'s `replayedRemembers` counts them), so the agent should not save the fact again. `put_page` and other writes are not replayed: resubmit after the next sync. Remembers refused before this release are listed by `gbrain repair failed-writes --source <id>`.' },
// #6686 (D8): a facts fence below the timeline sentinel.
{ since: '0.60.243.0', text: 'A page whose only `## Facts` fence sits below the timeline sentinel keeps it there: `remember` and `extract_facts` now add their rows to that fence (and strike a replaced row where it lives) instead of adding a second fence above the sentinel, and `extract_facts` reconciles such a fence instead of warning `FACTS_FENCE_BELOW_SENTINEL` and freezing its facts. A page that already has a fence on each side of the sentinel still warns, now naming `gbrain repair split-facts --source <id>`, an explicit preview-then-apply repair that merges the two fences under their own row numbers and refuses a page whose fences share a row number.' },
+ // #6608: fact writers onto a page of an unbound source.
+ { since: '0.0.0-wave17', text: 'On Postgres, `remember` about an existing page of a source that has a checkout but no canonical owner now follows the same rule as `put_page`: with `persistence.unbound_write=database_only` a page without a canonical file gets the fact fenced into its database body (database-only, `write_through.skipped: unbound_source`), and otherwise the refusal (still `unavailable` with `write_error: owner_unavailable`) carries `detail: unbound_source`, the opt-in or classic file path, and an ask-the-user fix instead of the generic writer hint. `loops_close` fact retirement and `gbrain facts relink` fence such pages the same way.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.ts
index 2d6b41d9c8..1d78dd9854 100644
--- a/src/core/facts/relink-publish.ts
+++ b/src/core/facts/relink-publish.ts
@@ -274,7 +274,13 @@ export async function submitRelinkGroup(engine: BrainEngine, config: GBrainConfi
}
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot) return { ok: false, reason: 'no_page', message: `${slug} no longer exists` };
- const target = await resolveFactWriteTarget(engine, sourceId, source);
+ let target: Awaited<ReturnType<typeof resolveFactWriteTarget>>;
+ try {
+ target = await resolveFactWriteTarget(engine, sourceId, source, { fileBacked: Boolean(snapshot.page.source_path), remote: false });
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'owner_unavailable') return { ok: false, reason: 'unfenceable', message: error.message };
+ throw error;
+ }
if (target.kind === 'unbound') return { ok: false, reason: 'unfenceable', message: `source ${sourceId} writes through to ${target.root} but has no canonical owner` };
const authority = await submissionAuthority(ctx, RELINK_OPERATION, sourceId, source.incarnation, slug);
if (target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;
diff --git a/src/core/persistence/fact-write-target.ts b/src/core/persistence/fact-write-target.ts
index 8748f82283..19737b673f 100644
--- a/src/core/persistence/fact-write-target.ts
+++ b/src/core/persistence/fact-write-target.ts
@@ -1,29 +1,33 @@
import type { BrainEngine } from '../engine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
-import { isConnectorSourceKind } from './connector-identity.ts';
+import { decideUnboundWrite } from './unbound-source.ts';
import type { WriteAuthority } from './model.ts';
/**
* Where a fact fenced onto an existing entity page publishes: the canonical
* file through the source's worktree binding, or the database page body only.
- * `unbound` is a write-through source with a root but no owner yet; remember
- * claims one automatically on PGLite, while maintenance writers (relink)
- * refuse rather than claim.
+ * A write-through source with a root but no owner follows `decideUnboundWrite`
+ * (#6608): `unbound` is its claim outcome (PGLite), which remember takes
+ * automatically while maintenance writers (relink) refuse rather than claim;
+ * an unbound Postgres source writes a page without a canonical file
+ * database-only under `persistence.unbound_write=database_only` and refuses
+ * otherwise. `fileBacked` is whether the target page records a canonical file;
+ * the refusal names the checkout only to trusted local (`remote: false`) callers.
*/
export type FactWriteTarget =
| { kind: 'publish'; binding: WorktreeBinding | null; databaseOnlyReason?: WriteAuthority['databaseOnlyReason'] }
| { kind: 'unbound'; root: string };
export async function resolveFactWriteTarget(engine: BrainEngine, sourceId: string,
- source: { local_path: string | null; kind: string | null }, opts: { sandbox?: boolean } = {}): Promise<FactWriteTarget> {
+ source: { local_path: string | null; kind: string | null },
+ opts: { sandbox?: boolean; fileBacked: boolean; remote: boolean }): Promise<FactWriteTarget> {
const configured = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
const writeThrough = configured && !opts.sandbox;
const reason = opts.sandbox ? 'subagent_sandbox' as const : !configured ? 'disabled_by_config' as const : undefined;
if (!writeThrough) return { kind: 'publish', binding: null, databaseOnlyReason: reason };
const binding = await getWorktreeBinding(engine, sourceId);
const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);
- // An unbound connector source is database-only by design; never claim it for a fence write.
- if (root && !binding && isConnectorSourceKind(source.kind)) return { kind: 'publish', binding: null, databaseOnlyReason: 'connector_database' };
- if (root && !binding) return { kind: 'unbound', root };
- return { kind: 'publish', binding };
+ if (!root || binding) return { kind: 'publish', binding };
+ const decision = await decideUnboundWrite(engine, { sourceId, sourceKind: source.kind, fileBacked: opts.fileBacked, path: opts.remote ? null : root });
+ return decision.kind === 'claim' ? { kind: 'unbound', root } : { kind: 'publish', binding: null, databaseOnlyReason: decision.reason };
}
diff --git a/src/core/persistence/loop-fact-retirement.ts b/src/core/persistence/loop-fact-retirement.ts
index 89b169d9d9..49272c86a4 100644
--- a/src/core/persistence/loop-fact-retirement.ts
+++ b/src/core/persistence/loop-fact-retirement.ts
@@ -155,11 +155,11 @@ export async function retireLoopFact(ctx: OperationContext, loopId: number): Pro
"SELECT incarnation, archived, local_path, config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
if (!source || source.archived) return { fact_expired: false, retryable: false, reason: 'source_changed' };
const slug = fact.source_markdown_slug ?? 'memory/unattributed';
- const target = await resolveFactWriteTarget(engine, sourceId, source);
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ const target = await resolveFactWriteTarget(engine, sourceId, source, { fileBacked: Boolean(snapshot?.page.source_path), remote: ctx.remote !== false });
if (target.kind === 'unbound') return { fact_expired: false, retryable: true, reason: 'owner_unavailable' };
const authority = await submissionAuthority(scoped, LOOP_FACT_RETIREMENT_OPERATION, sourceId, source.incarnation, slug);
if (target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;
- const snapshot = await engine.readPageSnapshot(slug, { sourceId });
const intent = { kind: LOOP_FACT_RETIREMENT_KIND, loop_id: loopId };
const row = await admitWrite(engine, {
principal, operation: LOOP_FACT_RETIREMENT_OPERATION, sourceId, sourceIncarnation: source.incarnation, slug, pageId: snapshot?.page.id ?? null,
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 234792aa36..0e97637b07 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -19,7 +19,6 @@ import { assertPersistenceAccepting, registerMutationPreparer, waitForWrite, wri
import { claimWorktree } from './ownership.ts';
import { declareDurablePersistence } from './protocol.ts';
import { resolveFactWriteTarget } from './fact-write-target.ts';
-import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';
import { withCoordinatedWrite } from './context.ts';
import { requestAttribution } from './attribution.ts';
@@ -97,13 +96,16 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
const writeThrough = configuredWriteThrough && !sandbox;
if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';
else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';
- const target = fence ? await resolveFactWriteTarget(ctx.engine, sourceId, source, { sandbox }) : null;
+ // An inferred link never designates an owner or reports a missing one.
+ const target = fence ? await resolveFactWriteTarget(ctx.engine, sourceId, source,
+ { sandbox, fileBacked: Boolean(snapshot!.page.source_path), remote: ctx.remote !== false }).catch((error: unknown) => {
+ if (inferred && error instanceof OperationError) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
+ throw error;
+ }) : null;
let binding = target?.kind === 'publish' ? target.binding : null;
if (target?.kind === 'publish' && target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;
if (target?.kind === 'unbound') {
- // An inferred link never designates an owner or reports a missing one.
if (inferred) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
- if (ctx.engine.kind !== 'pglite') throw new OperationError('owner_unavailable', 'This source has no designated canonical owner.', WRITER_INSPECTION_HINT);
binding = await claimWorktree(ctx.engine, sourceId, target.root, undefined, undefined, { automatic: true });
}
// An inferred link is optional: a canonical file it could not publish (missing,
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 516a9a8403..700bb4b828 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -27,19 +27,18 @@ import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequ
import { submissionAuthority, authorizeStoredRequest } from './authority.ts';
import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
import type { BrainEngine } from '../engine.ts';
-import { claimWorktree, getWorktreeBinding, managedPersistenceEnabled } from './ownership.ts';
+import { claimWorktree, getWorktreeBinding } from './ownership.ts';
import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
import type { Principal, WriteRequest } from './model.ts';
import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarning } from './page-input.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { isUnboundSourcePage, readDatabaseOnlyActivatedSources, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';
+import { decideUnboundWrite, isUnboundSourcePage } from './unbound-source.ts';
import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';
import { publishesDatabaseOnly } from './page-prepare.ts';
import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';
import { pipelined } from '../page-state/transactions.ts';
import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
-import { isConnectorSourceKind } from './connector-identity.ts';
export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {
// #5994: a failed-writes replay is admitted under the original writer.
@@ -371,25 +370,14 @@ export async function preparePageAdmission(ctx: OperationContext,
if (!matches) throw new OperationError('invalid_params', 'The CLI directory must match the selected source canonical root.',
'Register the source canonical path, then omit --dir or use that same path.');
}
- // A connector source without a canonical owner is database-only by design
- // (connector_database): a page write never claims it or refuses as unbound.
- if (writeThrough && root && !binding && isConnectorSourceKind(source.kind)) authority.databaseOnlyReason = 'connector_database';
- else if (writeThrough && root && !binding) {
- // #6449: a source activation listed database-only (sync.write_through was off) is never claimed by a flip of that
- // setting: the write refuses with the claim named (or stays database-only under persistence.unbound_write), as on Postgres.
- const databaseOnlyActivated = ctx.engine.kind === 'pglite' && (await readDatabaseOnlyActivatedSources(ctx.engine)).includes(sourceId);
- if (ctx.engine.kind === 'pglite' && !databaseOnlyActivated) binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });
- else {
- // #5393: the opt-in covers every page mutation whose target has no
- // recorded canonical file; a revert is also judged on the version it writes.
- const fileBacked = Boolean(snapshot?.page.source_path) || (input.operation === 'revert_version' && snapshot
- && (await ctx.engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM page_versions WHERE id=$1 AND page_id=$2',
- [p.version_id, snapshot.page.id]))[0]?.source_path);
- if (fileBacked || await readUnboundWritePolicy(ctx.engine) !== 'database_only') {
- throw unboundSourceError(sourceId, ctx.remote === false ? root : null, fileBacked ? 'file_backed' : 'database_only_eligible', !await managedPersistenceEnabled(ctx.engine));
- }
- authority.databaseOnlyReason = 'unbound_source';
- }
+ if (writeThrough && root && !binding) {
+ // #5393: a revert is also judged on the version it writes.
+ const fileBacked = Boolean(snapshot?.page.source_path) || Boolean(input.operation === 'revert_version' && snapshot
+ && (await ctx.engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM page_versions WHERE id=$1 AND page_id=$2',
+ [p.version_id, snapshot.page.id]))[0]?.source_path);
+ const decision = await decideUnboundWrite(ctx.engine, { sourceId, sourceKind: source.kind, fileBacked, path: ctx.remote === false ? root : null });
+ if (decision.kind === 'claim') binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });
+ else authority.databaseOnlyReason = decision.reason;
}
// #5032: this host publishes the canonical file, and on Windows a ':' in its
// name cannot be stored; refuse before admission. Database-only writes pass,
diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.ts
index 83dacd26ad..668727d0ea 100644
--- a/src/core/persistence/unbound-source.ts
+++ b/src/core/persistence/unbound-source.ts
@@ -1,6 +1,8 @@
import type { BrainEngine } from '../engine.ts';
import { opError, OperationError } from '../ops/contract.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
+import { managedPersistenceEnabled } from './ownership.ts';
+import { isConnectorSourceKind } from './connector-identity.ts';
/**
* #5254: a Postgres page write to a filesystem source with no canonical owner
@@ -98,6 +100,28 @@ export function unboundSourceError(sourceId: string, path: string | null, scope:
return error;
}
+export type UnboundWriteDecision = { kind: 'claim' } | { kind: 'database_only'; reason: 'connector_database' | 'unbound_source' };
+
+/**
+ * The one rule for a write-through write to a source with a checkout root but
+ * no worktree binding, shared by page writers and fact writers (#6608):
+ * a connector source is database-only by design and never claimed; PGLite
+ * claims the source automatically unless activation listed it database-only
+ * (#6449); otherwise a target with a recorded canonical file, or any
+ * `persistence.unbound_write` other than `database_only`, refuses with
+ * `unboundSourceError`, and the rest is written database-only (`unbound_source`).
+ * `path` names the checkout in the refusal; pass it only for trusted local callers.
+ */
+export async function decideUnboundWrite(engine: BrainEngine,
+ input: { sourceId: string; sourceKind: string | null; fileBacked: boolean; path: string | null }): Promise<UnboundWriteDecision> {
+ if (isConnectorSourceKind(input.sourceKind)) return { kind: 'database_only', reason: 'connector_database' };
+ if (engine.kind === 'pglite' && !(await readDatabaseOnlyActivatedSources(engine)).includes(input.sourceId)) return { kind: 'claim' };
+ if (input.fileBacked || await readUnboundWritePolicy(engine) !== 'database_only') {
+ throw unboundSourceError(input.sourceId, input.path, input.fileBacked ? 'file_backed' : 'database_only_eligible', !await managedPersistenceEnabled(engine));
+ }
+ return { kind: 'database_only', reason: 'unbound_source' };
+}
+
export function unboundPublicationHint(sourceId: string): string {
return `Source '${sourceId}' gained a canonical owner, or the page gained a canonical file, after this database-only write was accepted, so nothing was written. `
+ 'Read the page again and submit the write with a new request_id; a bound source publishes it to its canonical file.';
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 998c80926e..4e7c34da10 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -165,6 +165,8 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
const frozen = verbError(code,diagnostic?.message ?? error.message,diagnostic?.suggestion ?? error.suggestion ?? 'Inspect writer status before retrying.');
if (diagnostic) frozen.detail = diagnostic.reason;
if (error.code === 'idempotency_conflict' && error.fix) frozen.fix = error.fix;
+ // #6608: an unbound-source refusal keeps its detail, docs and ask-the-user fix additively; the frozen code stays.
+ if (error.detail === 'unbound_source') Object.assign(frozen, { detail: error.detail, docs: error.docs, fix: error.fix, retryable: error.retryable });
if (isWriteErrorCode(error.code)) frozen.writeError=error.code;
throw frozen;
}
diff --git a/test/e2e/unbound-source-postgres.test.ts b/test/e2e/unbound-source-postgres.test.ts
index 17830a844b..4a4a79fa7c 100644
--- a/test/e2e/unbound-source-postgres.test.ts
+++ b/test/e2e/unbound-source-postgres.test.ts
@@ -377,3 +377,60 @@ d('#5254 Postgres put_page to an unbound filesystem source', () => {
});
});
+
+// #6608: remember onto an existing entity page of an unbound source follows the
+// same rule as put_page. It refused every case with the generic
+// writer-inspection hint (no detail, no opt-in), so no fact could be saved
+// about any existing page of an unbound classic Postgres source. remember is a
+// frozen MEMORY_VERBS v1 verb: its wire code stays `unavailable` with
+// `write_error: owner_unavailable`, and the detail and fix ride along.
+d('#6608 Postgres remember onto a page of an unbound filesystem source', () => {
+ const entity = 'notes/entity-example';
+ async function createDatabaseOnlyEntity(): Promise<void> {
+ await engine.setConfig('persistence.unbound_write', 'database_only');
+ expect((await put('An entity written database-only.', entity)).payload.state).toBe('committed');
+ }
+ const remember = (fact: string) => dispatch('remember', { fact, entity, provenance: 'unbound-source test', request_id: randomUUID() });
+
+ test('with the opt-in, the fact is fenced into the database-only page body', async () => {
+ await createDatabaseOnlyEntity();
+ const saved = await remember('Entity Example prefers tea.');
+ expect(saved.response.isError, JSON.stringify(saved.payload)).not.toBe(true);
+ expect(saved.payload.state).toBe('committed');
+ expect(saved.payload.write_through).toMatchObject({ written: false, skipped: 'unbound_source' });
+ const [fact] = await engine.executeRaw<{ row_num: number | null; source_markdown_slug: string | null }>(
+ "SELECT row_num, source_markdown_slug FROM facts WHERE source_id='default' AND entity_slug=$1", [entity]);
+ expect(fact).toEqual({ row_num: 1, source_markdown_slug: entity });
+ const page = await engine.getPage(entity, { sourceId: 'default' });
+ expect(page?.compiled_truth).toContain('Entity Example prefers tea.');
+ expect(page?.source_path ?? null).toBeNull();
+ expect(await classification(entity)).toBe('unbound_source');
+ expect(existsSync(join(root, `${entity}.md`))).toBe(false);
+ });
+
+ test('a page with a recorded canonical file refuses with the bind branch only', async () => {
+ await createDatabaseOnlyEntity();
+ await engine.executeRaw("UPDATE pages SET source_path=$2 WHERE source_id='default' AND slug=$1", [entity, `${entity}.md`]);
+ const refused = await remember('Entity Example prefers juice.');
+ expect(refused.payload.error).toBe('unavailable');
+ expect(refused.payload.write_error).toBe('owner_unavailable');
+ expect(refused.payload.detail).toBe('unbound_source');
+ expect(refused.payload.fix.next).toBe('ask_user');
+ expect(refused.payload.suggestion).toContain('came from a canonical file');
+ expect(refused.payload.suggestion).not.toContain('gbrain config set persistence.unbound_write database_only');
+ expect((await engine.executeRaw("SELECT 1 FROM facts WHERE source_id='default' AND entity_slug=$1", [entity])).length).toBe(0);
+ });
+
+ test('without the opt-in, the refusal names it instead of the generic owner hint', async () => {
+ await createDatabaseOnlyEntity();
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.unbound_write'");
+ const refused = await remember('Entity Example prefers coffee.');
+ expect(refused.payload.error).toBe('unavailable');
+ expect(refused.payload.write_error).toBe('owner_unavailable');
+ expect(refused.payload.detail).toBe('unbound_source');
+ expect(refused.payload.retryable).toBe(false);
+ expect(refused.payload.fix.next).toBe('ask_user');
+ expect(refused.payload.docs).toBe(docsUrl(DOCS));
+ expect(refused.payload.suggestion).toContain('gbrain config set persistence.unbound_write database_only');
+ });
+});
diff --git a/test/persistence-unbound-source.test.ts b/test/persistence-unbound-source.test.ts
index 165a03e244..555aa1cc55 100644
--- a/test/persistence-unbound-source.test.ts
+++ b/test/persistence-unbound-source.test.ts
@@ -10,7 +10,8 @@ import { describe, expect, test } from 'bun:test';
import { OperationError } from '../src/core/ops/contract.ts';
import { writeResponse } from '../src/core/persistence/service.ts';
import type { WriteRequest } from '../src/core/persistence/model.ts';
-import { parseUnboundWriteValue, readUnboundWritePolicy, UNBOUND_PUBLICATION_MESSAGE, UNBOUND_SOURCE_DOCS } from '../src/core/persistence/unbound-source.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { decideUnboundWrite, parseUnboundWriteValue, readUnboundWritePolicy, UNBOUND_PUBLICATION_MESSAGE, UNBOUND_SOURCE_DOCS } from '../src/core/persistence/unbound-source.ts';
describe('persistence.unbound_write', () => {
test('accepts only refuse and database_only', () => {
@@ -27,6 +28,65 @@ describe('persistence.unbound_write', () => {
});
});
+// #6608: the one rule page writers and fact writers (remember, loop retirement,
+// relink) apply to a write-through source with a root and no owner. remember
+// used to refuse every Postgres case with the generic writer-inspection hint.
+describe('decideUnboundWrite', () => {
+ const engine = (kind: 'postgres' | 'pglite', config: Record<string, string> = {}) => ({
+ kind,
+ getConfig: async (key: string) => config[key] ?? null,
+ executeRaw: async () => [{ enabled: false }],
+ }) as unknown as BrainEngine;
+ const input = (over: Partial<Parameters<typeof decideUnboundWrite>[1]> = {}) =>
+ ({ sourceId: 'notes', sourceKind: null, fileBacked: false, path: '/srv/notes', ...over });
+ const refusal = async (promise: Promise<unknown>): Promise<OperationError> => {
+ try { await promise; } catch (error) { return error as OperationError; }
+ throw new Error('decideUnboundWrite did not refuse');
+ };
+ const DATABASE_ONLY = { 'persistence.unbound_write': 'database_only' };
+
+ test('a connector source is database-only by design on every engine, file-backed or not', async () => {
+ for (const kind of ['postgres', 'pglite'] as const) {
+ expect(await decideUnboundWrite(engine(kind), input({ sourceKind: 'google', fileBacked: true })))
+ .toEqual({ kind: 'database_only', reason: 'connector_database' });
+ }
+ });
+
+ test('PGLite claims the source automatically, whatever the policy', async () => {
+ expect(await decideUnboundWrite(engine('pglite'), input({ fileBacked: true }))).toEqual({ kind: 'claim' });
+ expect(await decideUnboundWrite(engine('pglite', DATABASE_ONLY), input())).toEqual({ kind: 'claim' });
+ });
+
+ test('a PGLite source activation listed database-only (#6449) follows the Postgres rule', async () => {
+ const listed = { 'persistence.database_only_sources': JSON.stringify(['notes']) };
+ expect((await refusal(decideUnboundWrite(engine('pglite', listed), input()))).detail).toBe('unbound_source');
+ expect(await decideUnboundWrite(engine('pglite', { ...listed, ...DATABASE_ONLY }), input()))
+ .toEqual({ kind: 'database_only', reason: 'unbound_source' });
+ });
+
+ test('Postgres with the opt-in writes a page without a canonical file database-only', async () => {
+ expect(await decideUnboundWrite(engine('postgres', DATABASE_ONLY), input())).toEqual({ kind: 'database_only', reason: 'unbound_source' });
+ });
+
+ test('Postgres without the opt-in refuses with the opt-in named and the user asked', async () => {
+ const error = await refusal(decideUnboundWrite(engine('postgres'), input()));
+ expect(error.code).toBe('owner_unavailable');
+ expect(error.detail).toBe('unbound_source');
+ expect(error.retryable).toBe(false);
+ expect(error.fix?.ask_user).toBe(true);
+ expect(error.suggestion).toContain('gbrain config set persistence.unbound_write database_only');
+ expect(error.suggestion).toContain('write the page as /srv/notes/<slug>.md');
+ });
+
+ test('a page with a recorded canonical file refuses even with the opt-in, and a remote caller never sees the path', async () => {
+ const error = await refusal(decideUnboundWrite(engine('postgres', DATABASE_ONLY), input({ fileBacked: true, path: null })));
+ expect(error.detail).toBe('unbound_source');
+ expect(error.suggestion).toContain('came from a canonical file');
+ expect(error.suggestion).not.toContain('gbrain config set persistence.unbound_write database_only');
+ expect(error.suggestion).not.toContain('/srv/notes');
+ });
+});
+
describe('receipt-delivered unbound_source failure', () => {
const row = (error_message: string) => ({
request_id: '00000000-0000-4000-8000-000000000001', state: 'failed', source_id: 'notes-example',