Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/belief-ledger-w1

garrytan463f4a4aa1da
diff --cc docs/architecture/key-files/core-persistence-continued.md
index 709da51ddd,68af073fc0..3fc11b293c
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@@ -23,12 -23,12 +23,12 @@@ Managed connector ingestion, connector
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.
- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
-- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
+- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` and the internal `retention: true` bound to its revision (W1, BELIEF_LEDGER.md 6.5: retention is not an owner purge, so it writes no content tombstone, redacts no history, appends no purge-mirror line and records `page.expired`; `purge-params.ts` accepts `retention` only from a local caller with `purge: true`). On an unmanaged brain each expired tombstone of a source with belief coverage is first deleted under its page key in a belief batch that appends `page.expired`; the bulk delete takes the rest. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).
- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.
- - `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres.
+ - `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, has its optimistic pending count taken back, and is counted in `last_run.purged_skipped` and `purged_items`. A replayed purged receipt is re-checked against the live tombstones (`purgedNow`) before `mayRetry`: still purged, it is skipped even under `--retry-failed`; cleared, it gets one automatic retry. A run that ends on any error except `LockStolenError` or an aborted caller signal records `last_failure` (code, else `connector_error`; message, the item and request when the run ended on that item's receipt, `consecutive`); only a complete `finish()` (cursor saved, nothing pending or failed) clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
- `src/core/persistence/connector-identity.ts` — `connectorIdentity(kind, rawConfig, localPath)` returns the parsed connector config and a digest over every parsed leaf except credential-delivery fields (Google `access`/`tokenCommand`/`tokenEnv`; GitHub `tokenEnv` and `app` under `scope: repos`, `app.pemPath` always; under `scope: auto` the token env without an App and the App ids are identity). `services`/`repos` are sorted and de-duplicated; a parser leaf missing from `CONNECTOR_LEAF_RULES` joins the identity. #6561: a leaf a parser starts emitting with a behavior-preserving default declares it as `elideWhen` (Google `contactsDir: 'people'`) and is left out of the digest while it holds it, so unchanged sources keep the pre-field key; the non-elided digest is kept as `aliasDigests` (`connectorCheckpointKeys` returns the stable key then its alias keys; `connectorIdentityMatches` accepts an admitted write's frozen `configHash` under either). Also `connectorCheckpointKey` and `isConnectorIntentKind`/`connectorIntentSql`, the one predicate for both intent namespaces. Test: `test/connector-identity.test.ts` enumerates every parser leaf.
- - `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account.
+ - `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account. #6831: `purged_items` (newest `CONNECTOR_PURGED_LIMIT` purged skips) and `last_failure` (`ConnectorRunFailure`); `CONNECTOR_STOPPED_RUNS` (3) consecutive failed runs read as stopped in `connector-status.ts` (`sources status` lines, `readConnectorLastError` for `sync status`'s additive `connector_last_error`; `last_error`, `state` and `next` are untouched) and doctor `sync_freshness` (`stoppedConnectorIssues` in `doctor/sync-outcome.ts`).
- `src/core/connectors/item-holds.ts` — fix wave 4 connector item holds, shared by Gmail and GitHub on managed and unmanaged brains: `classifyConnectorError` (the one table: source-scoped, rate-limit and item-scoped codes, content vs transient class) and `ItemHoldsRun` (hold after 3 consecutive attempted runs at one upstream version; circuit breaker at 5 attempted items with half transient or 5 and half one code; backoff 1 h/6 h/24 h/daily for 7 days; cap 100, `connector_holds_exhausted`). A run's changes merge only in `finish()`, so mid-run checkpoints carry the holds the run began with and a cursor never passes an item that is not already held. `carryLegacyFailCounts` reads the retired Gmail ledger once.
- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys. Git-source holds are not read here: only `sources status` (`persistence/connector-status.ts` `readGitHoldStatuses`, `sources status <id>` filters to one source) and `sources retry-held` (a Git source records a `sync-hold-retry` re-screen request for its held paths; `gbrain sync --retry-held` refuses with that pointer) show them beside connector holds. Writer deactivation and activation never read or block on them.
- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.
diff --cc src/core/behavior-change-notice.ts
index fe707de429,f650b33340..5362059dae
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -696,8 -696,10 +696,12 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: '0.60.261.0', text: 'The update check (the startup `UPGRADE_AVAILABLE` marker, `gbrain check-update`, `gbrain self-upgrade`, doctor\'s `self_upgrade_health` and the `auto` channel) now reads the version at the `latest-stable` tag, the published release `bun update` installs, instead of master\'s `VERSION`. A version stamped on master but not yet released is no longer announced, and `auto` no longer tries to install it (#6718, #6828).' },
{ since: '0.60.261.0', text: 'A `gbrain upgrade` whose install step leaves the same version running now prints `No newer version was installed` instead of `Upgrade complete`, and keeps `last_upgrade`, the pending-update marker and the `JUST_UPGRADED` breadcrumb as they were. The `auto` channel no longer exits for a relaunch after such a swap and no longer records the target known-bad: it audits the attempt as `skipped` and retries after 24 hours. A version is recorded known-bad only when it was installed and then failed, under the version actually installed.' },
{ since: '0.60.261.0', text: '`gbrain doctor` (`self_upgrade_health`) now warns when `self_upgrade.failed_versions` holds a version the audit proves was never installed (an earlier release reported a no-op swap as swapped and recorded it known-bad, #6828), so `auto` would skip that release forever. `gbrain self-upgrade --clear-never-installed` previews the entries and the swap that recorded each; `--apply` removes exactly those. A post-upgrade failure recorded with no installable target (`latest`, `unknown`) now clears from `upgrade_errors` once the binary is past the version it failed from.' },
+ // #6831 + #6816 hotfix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.262.0', text: 'A managed Google or GitHub connector item whose content matches a page purge tombstone is now skipped, and the rest of the sync continues (#6831). Before, the pages guard\'s `purged_content` refusal of that one item ended the whole sync job, and every later sync of the source died the same way. Skipped items are listed in `gbrain sources status` ("skipped as purged content"), and `gbrain pages unpurge <slug>` lets one back in. Every other failed connector write still ends the run.' },
+ { since: '0.60.262.0', text: 'A connector source whose syncs keep ending on an error now says so (#6831): `gbrain sources status` names the error, the item and a read-only next step, and reads STOPPED after 3 failed runs in a row; `gbrain sync status --json` adds `connector_last_error` with that read-only fix; doctor `sync_freshness` warns about a STOPPED source even when its last good sync was recent (fails past the fail age). `last_error`, `state` and `next` are unchanged for connector sources.' },
+ { since: '0.60.262.0', text: 'A `claude-cli` usage-policy refusal ("API Error: <model> can\'t help with this ... https://www.anthropic.com/legal/aup", and the older "violate our Usage Policy" and "safeguards flagged this" wordings) is now a provider content block (`claude_cli_usage_policy`, #6816): `extract_atoms` tombstones the item after its consecutive-failure limit instead of re-sending it every run, and with `chat_fallback_on_refusal: false` the prompt is not sent on to the next model in `chat_fallback_chain`. Other `claude-cli` errors are unchanged.' },
+ // W1 belief ledger (#6806). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
- { since: '0.60.261.0', text: 'On a managed brain, `gbrain pages purge-deleted` (retention cleanup of pages soft-deleted more than 72 hours ago) no longer writes purge tombstones: it removes the page as before but records no page, fact or take tombstone, so the same content can be imported again later, as on a brain without managed persistence. Only `gbrain delete <slug> --purge` and `purge_fact` forget content. A page purge now also holds its source exclusively while it publishes, so other writes to that source wait for it.' },
++ { since: '0.60.262.0', text: 'On a managed brain, `gbrain pages purge-deleted` (retention cleanup of pages soft-deleted more than 72 hours ago) no longer writes purge tombstones: it removes the page as before but records no page, fact or take tombstone, so the same content can be imported again later, as on a brain without managed persistence. Only `gbrain delete <slug> --purge` and `purge_fact` forget content. A page purge now also holds its source exclusively while it publishes, so other writes to that source wait for it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */