Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract): extract_entities writes through the coordinator on managed brains (#6262)

time-attack1792026482ff
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 572b341135..85005fa7ff 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -65,7 +65,7 @@ src/core/engine-sql/sources.ts 1 projection Source settings (the sources.config
src/core/engine-sql/takes.ts 6 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/engine-sql/timeline.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/engine.ts 2 contract Engine contract or explanatory SQL references; execution is in guarded engine implementations.
-src/core/enrichment-service.ts 4 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).
+src/core/enrichment-service.ts 4 coordinator #6262: on a managed brain extract_entities submits the stub as a create-only put_page and lowers its tier, adds the timeline row and adds the backlink in coordinatedDatabaseWrite transactions under the caller's authority; no direct-write fallback. Unmanaged brains keep the direct importFromContent and maintenance-transaction writes.
src/core/extract/receipt-writer.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/extract-timeline-from-meetings.ts 2 coordinator #6273: on a managed brain each entity page's meeting rows publish as one database-only managed_maintenance_meeting_timeline request, re-gated at the meetings' stored tier inside the coordinated apply; the unmanaged batch insert runs in maintenanceTransaction, which the guard refuses on a managed brain.
src/core/facts/backstop.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 66569744d4..b3d3707089 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/dry-fix.ts` — `gbrain doctor --fix` engine. `autoFixDryViolations(fixes, {dryRun})` rewrites inlined rules to `> **Convention:** see [path](../path).` callouts via three shape-aware expanders (bullet / blockquote / paragraph). Five guards: working-tree-dirty (`getWorkingTreeStatus()` 3-state `'clean' | 'dirty' | 'not_a_repo'`), no-git-backup, inside-code-fence, already-delegated (40-line proximity, consistent with detector), ambiguous-multi-match, block-is-callout. `execFileSync` array args (no shell, no injection surface). EOF newline preserved. Safety primitives are in `src/core/skill-fix-gates.ts` (back-compat re-exports preserved). `MISSING_RULE_PATTERNS` INSERT pattern type lives alongside REPLACE patterns — same auto-fix entry point + git-safety gates, but places a canonical callout at a target offset (`after-h1-paragraph` only). First INSERT pattern is `brain_first`, auto-inserting `> **Convention:** see [conventions/brain-first.md](../../conventions/brain-first.md) for the lookup chain (search → query → get_page → external).` on any flagged SKILL.md whose verdict is `missing_brain_first`. Idempotent — re-runs detect the existing callout and skip.
-- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`.
+- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.
- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 96ff8db048..148b4b83b7 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `USER_SAID_TRUST_LABEL` (the label of an `agent_written` row whose `write_origin.content_origin` is `user_said`; the tier never rises, the eval harness reads the constant), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`. Write side (lane L1a): `channel.ts` computes the tier once per write from the channel (`requestChannelTrust`: agent verbs agent_written, `content_origin: tool_output` external_untrusted, connector jobs external_untrusted; owner sync/import `ownerImportTrust`: operator_curated or the `sources set-trust` default, lowered by frontmatter markers `frontmatterTrustCaps`) and `stampTrustMarker` (the lower-only `trust_tier` marker, CEO-21); `page-write.ts` wires it into page-prepare (marker stamp, fence edits keep the page tier via `withTrustKeep`, `lower_page` proposals on agent rewrites, the page gate tier); `proposals.ts` is the `trust_proposals` store and handler dispatch (`decide.ts` loads every handler); `supersede-handlers.ts` is guarded supersession (`supersessionGuarded`, contested fact/take/ontology proposals, remote `forget_requires_owner`, the trust store for the checked decide_proposals supersede); `fence-guard.ts` guards the facts-fence re-projection and gates new fence rows; `gate-outcomes.ts` is the DX-1 `gate` field and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15). `owner-actions.ts`: `previewOwnerAction` / `applyOwnerAction` for confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and a `binding` of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with `preview_changed` and a raising action without a confirmation with `confirmation_required` (`ownerActionFix` is the DX-3 `tell_user_to_run` fix). Fact and take confirms are tier-only updates under `withTrustPromotion` (inside `withCoordinatedWrite` on a managed brain); the hold store is an isolated adapter over `write_gate_holds` (`__setHoldStoreForTests`, `TODO(L2a-merge)`); `disable --all` writes `write_gate.external_mode=off`, `write_gate.agent_mode=off`, `trust.agent_activation=allow` with the `trust.kill_switch` receipt that `--undo` restores from. `page-handlers.ts`: `confirmPage` (removes the CEO-21 `trust_tier` marker through a journaled `trust_owner_page` mutation on a managed brain, `importFromContent` otherwise; tier only when no marker), `revertPageToVersion` (the version's content and its snapshot tier, `unknown` for legacy versions), the coordinator preparer `prepareTrustOwnerPageMutation` (dispatched from `persistence/service.ts`; re-checks the approved revision and refuses a remote request without `memory_confirm`), and the `lower_page` handler (accept = confirm, reject = dismiss, `revertLoweredPage` = restore the prior owner version). `refs.ts`: typed refs `f<id>`, `t<id>`, `h<id>`, `tp<id>`, `a<id>`, `p:<source>/<slug>`, bare slugs resolved by `--source` or a single source (ambiguity refuses). `review.ts`: `buildTrustReview` (pending proposals, lowered pages, unconfirmed standing preferences, holds, allow rules, kill-switch state, grouped by day and page, complete argv) and `explainTrust`. `allow-rules.ts`: the `trust_allow_rules` table (migration v229, receipted, removal keeps the row) and the pure `matchTrustAllowRule` over server-stamped fields. `owner-ipc.ts`: the `trust_read` / `trust_preview` / `trust_apply` administration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests: `test/trust-owner-actions.test.ts` (PGLite and Postgres), `test/trust-owner-ipc.test.ts`, `test/trust-cli.test.ts`. Derived-row taint (`taint.ts`, `derived-gate.ts`, `timeline-projection.ts`): see [security](security.md).
- `src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts` — the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14). `policy.ts`: `resolveReadEligibility` returns the effective floor (the strictest of `AuthInfo.minTrust`, the caller's `min_trust` and `trust.read_policy=filter`'s own `unknown` floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, `suppressFlagged` unless `trust.agent_activation=allow`. `sql.ts`: vetted predicates over a caller alias (closed vocabularies only): `trustFloorSql`, `pageEligibleSql` (spliced by `buildVisibilityClause` and `pageReadFilter`, so every search arm filters before LIMIT; a chunk's tier is its page's), `projectionEligibleSql` (facts, takes and timeline reads: a quarantined page's projections and `needs_rederive` rows are hidden, never expired) and `activationSuppressedSql` (tier at or below `agent_written` plus an instruction-family `write_gate_receipts` flag). `labels.ts`: `trust_tier` + a short server-stamped `origin` (`trustFields` appends `:user_said` for a relayed user statement, which `trustLabelWords` reads as `USER_SAID_TRUST_LABEL` unless the row is flagged unconfirmed); compact per-item text labels with the fixed words, `unknown` as a short origin line, and the `<external-data>` envelope only below `unknown`. `registry.ts`: `OP_READ_TRUST` classifies every read-scope op `filtered | labeled | text_free` (the dispatcher refuses a `labeled` op for a floored token) and `PROACTIVE_SURFACES` lists the injecting surfaces, each calling `proactiveEligibility(ctx, id)`; drift-tested by `test/eligibility-registry.test.ts`. `stamp.ts` labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows `unconfirmed`. `activation.ts` partitions proactive candidates (`partitionForActivation`, `pageActivationVerdicts`) and builds the `memory_suppressed` notice (count + `gbrain trust review`, never content). `scan.ts` (`gbrain trust scan`, doctor `trust_scan`) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans). `explain.ts` is the `gbrain trust explain` data API: tier, origin, receipts and the per-surface decision for a typed ref. Tests: `test/eligibility-{policy,registry,reads}.test.ts`.
-- `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is above): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated. Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.
+- `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is above): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` (and `lowerDerivedPageIn`, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated. Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.
- `src/core/trust/claim.ts` + `claim-state.ts` + `claim-notice.ts`, `src/commands/trust-claim.ts`: #5575 legacy content. `gbrain trust claim-sources` (local CLI; typed source id on a TTY, `--yes` never counts, non-TTY refuses `confirmation_required` with a tell_user_to_run fix) records a claim in `sources.config` (`trust_tier: operator_curated`, `trust_claimed_at`, `trust_claim_lifted_at`) and lifts the source's legacy `unknown` rows (ids at or below `write_gate.scan_baseline`) through `trust/backfill.ts` scoped to the claimed sources (own cursor, `write_origin.channel` `trust_claim`), lowered by `frontmatterTrustCapsSql` (channel.ts, pinned to `frontmatterTrustCaps`) and every backfill signal, never above operator_curated; connector sources refuse. Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the behavior-change notice name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`.
- `src/core/write-gate.ts` + `src/core/write-gate-patterns.ts` — the #5575 blocking write gate, separate from observe-only `guardrails.ts` (never imported). Deterministic and model-free (P8): `WRITE_GATE_PATTERNS` (bounded clones of the detection-grade `think/sanitize.ts` `INJECTION_DETECTION_PATTERNS`, the exported transcript `IMPERATIVE_RES`, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed to <address>" rules and direct cc/bcc) and credential patterns; families `override`, `standing_instruction`, `exfiltration`, `credential`). `detectInstructionLike` decodes tag characters, strips invisibles and NFKC-folds compatibility forms only when present, finds anchor words in one allocation-light hash pass (one tight loop per word), then runs each pattern only on 4 KB windows (overlap `MAX_MATCH_CHARS` + `MAX_PRECEDING_CHARS`) holding its anchors, tracked as sliding per-window anchor counts, and inside a window only within the pattern's longest match (`write-gate-regex.ts`, the analysis the regex lint uses) of its own anchor words, except `WHOLE_WINDOW_PATTERNS`; `preceded` regexes check context before a rare-token match, a `neg` group rejects negated matches. `assessPageForGate` (title, body minus managed fence table rows, frontmatter strings), `assessFactForGate` (fact, context, value, provenance, pre-sanitized `source_text`), `assessTakeForGate` and `assessTimelineForGate` scan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed; `external_untrusted` -> `write_gate.external_mode` (`flag` default per the paid eval, `quarantine` opt-in, `reject`, `off`), detector error -> quarantine; `agent_written`/`unknown` -> `flag` (`write_gate.agent_mode=off`), detector error -> allow. `writeGateOutcome` is the DX-1 `gate` shape; `writeHeldError` / `writeGateRejectedError` build the `write_held` / `write_gate_rejected` refusals (families only, no pattern names). `scripts/check-write-gate-regex.ts` (in verify) proves every pattern bounded. Tests: `test/write-gate.test.ts`, `test/write-gate-perf.slow.test.ts`, `test/write-gate-anchor-ranges.test.ts` (sampled matches of every narrowed pattern hold an anchor word within its longest match), and `test/write-gate-detector-differential.test.ts` (identical hits to the pre-optimization detector v2 kept as `test/helpers/write-gate-detector-reference.ts`, over the detector corpora, BrainBench fixtures, docs/skills and a seeded random corpus).
diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsv
index 0471d98e25..7056a785be 100644
--- a/docs/architecture/managed-mutating-writers.tsv
+++ b/docs/architecture/managed-mutating-writers.tsv
@@ -53,7 +53,7 @@ op request_tools no_canonical_write Persists the calling client's MCP tool surfa
op connector_sync coordinator Managed connector sync admits pages and checkpoints through the coordinator.
op ontology_propose engine_guard mergeOntologyFact inserts into facts; the managed writer trigger refuses it on a managed brain.
op chronicle_backfill no_canonical_write Queues chronicle jobs; the chronicle extractor publishes through publishMaintenancePage.
-op extract_entities early_refusal enrichment-service writes through direct importFromContent, which refuses on managed brains.
+op extract_entities coordinator #6262: the stub is a create-only put_page through submitPageMutation; its tier lowering, timeline row and backlink are coordinatedDatabaseWrite transactions. A refusal or pending write returns its envelope and stops the batch.
op extraction_review no_canonical_write Review queue state only.
op entity_identity_link no_canonical_write entity_identity side table.
op entity_identity_unlink no_canonical_write entity_identity side table.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 051eeba8d2..a9fac3c779 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -376,7 +376,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.157.0', text: 'A page whose database frontmatter carries the v0.13.1 grandfather `validate: false` while its canonical file does not is no longer refused `source_changed` on write; the next coordinated write publishes the stamp to the file. `remember` and other caller writes that were refused that way are counted by doctor (`lost_caller_writes`) and replayed by `gbrain repair failed-writes --source <id>` on the brain host, after the user agrees to the previewed set.' },
// Fix wave 13 PR2 (GBRA-57); `since` is the placeholder until the merge-slot stamp.
{ since: '0.60.158.0', text: 'Managed sync: a Postgres publish still running 30 s past `persistence.publication_ceiling_ms` (default 5 min) is cancelled (its connection is discarded, nothing commits, and the write is queued again); one that still does not settle makes its owner report `restart_required`. `gbrain sync` stops `drain_stalled` (`publication_overdue`, or `no_admission` after 5 minutes with nothing admitted) instead of waiting forever, and a source more than 100,000 changes behind catches up in bounded stages instead of refusing. `gbrain migrate` with the legacy copier now forwards each page\'s origin path, kind, provenance, `ingested_at` and aliases, and rebuilds the text projections of pages the source had sealed before it switches the engine; a failed rebuild keeps the old engine active and exits 1.' },
- { since: '0.60.158.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades.' },
+ { since: '0.60.158.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs `put_page` in the grant); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.ts
index f13f07fbd5..6bb76eac01 100644
--- a/src/core/enrichment-service.ts
+++ b/src/core/enrichment-service.ts
@@ -14,6 +14,8 @@
*/
import type { BrainEngine } from './engine.ts';
+import type { OperationContext } from './ops/contract.ts';
+import { OperationError } from './ops/contract.ts';
import { waitForCapacity } from './backoff.ts';
import { quarantineMarkers } from './extraction-review.ts';
import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';
@@ -28,7 +30,8 @@ import { isAvailable } from './ai/gateway.ts';
// gazetteer and drives the junk_entity_hubs doctor check.
import { isJunkEntityName } from './entity-name-quality.ts';
import { maintenanceTransaction } from './persistence/attribution.ts';
-import { deriveTrust, derivedMaintenanceTransaction, lowerDerivedPage } from './trust/taint.ts';
+import { managedPersistenceEnabled } from './persistence/ownership.ts';
+import { deriveTrust, derivedMaintenanceTransaction, lowerDerivedPage, lowerDerivedPageIn } from './trust/taint.ts';
import { derivedGateConfig, derivedGateInput, recordTimelineFlag, timelineRowAllowed } from './trust/derived-gate.ts';
import { assessTimelineForGate } from './write-gate.ts';
@@ -63,6 +66,8 @@ export interface EnrichmentTrustOptions {
trusted?: boolean;
/** Source to read/write in (multi-source brains). Omitted → engine default. */
sourceId?: string;
+ /** #6262: the caller's context; on a managed brain every write goes through the coordinator under its authority. */
+ ctx?: OperationContext;
}
export interface EnrichmentResult {
@@ -156,6 +161,13 @@ export async function enrichEntity(
const scope = opts?.sourceId ? { sourceId: opts.sourceId } : undefined;
// #5575 I2: a stub and its timeline row restate the source page's mention, so they carry its taint (capped at agent_written).
const derivation = await deriveTrust(engine, [{ table: 'pages', sourceId, slug: request.sourceSlug }], { channel: 'derive:enrichment' });
+ const ctx = opts?.ctx;
+ // #6262: a managed brain refuses direct writes, so each one goes through the coordinator under the caller's authority.
+ const managed = ctx !== undefined && await managedPersistenceEnabled(engine);
+ const coordinated = async <T>(lockSlugs: string[], write: (tx: BrainEngine) => Promise<T>) => {
+ const { coordinatedDatabaseWrite } = await import('./persistence/database-write.ts');
+ return coordinatedDatabaseWrite(ctx!, 'extract_entities', slug, lockSlugs, write, derivation.trust);
+ };
// 1. Count existing mentions for tier auto-escalation
const { mentionCount, mentionSources } = await countMentions(engine, request.entityName, opts?.sourceId);
@@ -215,7 +227,14 @@ export async function enrichEntity(
// carry provenance + unverified markers until the owner reviews them.
...(trusted ? {} : quarantineMarkers()),
};
- try {
+ if (managed) {
+ // No direct-write fallback: a refusal or a pending write reaches the caller as its envelope.
+ const { submitPageMutation } = await import('./persistence/page-mutations.ts');
+ const md = serializeMarkdown(frontmatter, content, '', { type, title, tags: [] });
+ await submitPageMutation(ctx!, { operation: 'put_page', params: { slug, content: md,
+ ...(derivation.trust.tier === 'external_untrusted' ? { content_origin: 'tool_output' } : {}) } });
+ await coordinated([slug], tx => lowerDerivedPageIn(tx, derivation, sourceId, slug));
+ } else try {
// #3994: canonical import pipeline so the stub is chunked (+ embedded
// when a provider is configured) and reachable by the recall arms.
const md = serializeMarkdown(frontmatter, content, '', { type, title, tags: [] });
@@ -248,21 +267,27 @@ export async function enrichEntity(
const entry = { date: new Date().toISOString().split('T')[0] ?? '', summary: `Referenced in [${request.sourceSlug}](${request.sourceSlug}) — ${request.context}`, source: request.sourceSlug };
// #5575 B3: the caller's context lands on the entity page, so it passes the write gate at the derived tier.
const assessment = assessTimelineForGate(entry, derivedGateInput(derivation.trust), await derivedGateConfig(engine));
- timelineAdded = timelineRowAllowed(assessment) && await maintenanceTransaction(engine, async tx => {
+ const write = async (tx: BrainEngine) => {
const added = await tx.addTimelineEntry(slug, entry, scope); // gbrain-allow-direct-insert: auto-timeline reconciliation triggered by entity reference in source markdown
if (added) await recordTimelineFlag(tx, assessment, { slug, source_id: sourceId, ...entry });
return true;
- }, derivation.trust);
- } catch {
+ };
+ timelineAdded = timelineRowAllowed(assessment) &&
+ (managed ? (await coordinated([slug], write))!.value : await maintenanceTransaction(engine, write, derivation.trust));
+ } catch (e) {
+ if (managed) throw e;
// Timeline add failed (page might not support it)
}
// 5. Add backlink from entity to source
let backlinkCreated = false;
try {
- await engine.addLink(slug, request.sourceSlug, `Entity mention from ${request.sourceSlug}`, undefined, undefined, undefined, undefined, opts?.sourceId ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId } : undefined); // gbrain-allow-direct-insert: auto-link reconciliation triggered by entity reference in source markdown
+ const link = (tx: BrainEngine) => tx.addLink(slug, request.sourceSlug, `Entity mention from ${request.sourceSlug}`, undefined, undefined, undefined, undefined, opts?.sourceId ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId } : undefined); // gbrain-allow-direct-insert: auto-link reconciliation triggered by entity reference in source markdown
+ if (managed) await coordinated([slug, request.sourceSlug], link);
+ else await link(engine);
backlinkCreated = true;
- } catch {
+ } catch (e) {
+ if (managed && e instanceof OperationError) throw e;
// Link might already exist
}
@@ -295,7 +320,15 @@ export async function enrichEntities(
if (config?.throttle !== false) {
await waitForCapacity({ maxAttempts: 5 }); // shorter timeout for batch items
}
- const result = await enrichEntity(engine, req, { trusted: config?.trusted, sourceId: config?.sourceId });
+ let result: EnrichmentResult;
+ try { result = await enrichEntity(engine, req, { trusted: config?.trusted, sourceId: config?.sourceId, ctx: config?.ctx }); }
+ catch (e) {
+ // #6262: a managed refusal stops the batch and says which entities were already written.
+ if (e instanceof OperationError && results.length) {
+ e.why = `${e.why ?? ''} ${results.length} of ${requests.length} entities were written before ${req.entityName}: ${results.map(r => r.slug).join(', ')}. Run extract_entities again on the same text once the write can commit; written entities are updated, not duplicated.`.trim();
+ }
+ throw e;
+ }
results.push(result);
config?.onProgress?.(results.length, requests.length, req.entityName);
}
diff --git a/src/core/ops/extraction.ts b/src/core/ops/extraction.ts
index d1b40aae2d..52aa9e5467 100644
--- a/src/core/ops/extraction.ts
+++ b/src/core/ops/extraction.ts
@@ -86,6 +86,7 @@ const extract_entities: Operation = {
{
trusted,
...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}),
+ ctx,
// Pure local DB writes — no external API call to pace, so the
// system-load capacity gate would only stall the caller.
throttle: false,
diff --git a/src/core/trust/taint.ts b/src/core/trust/taint.ts
index 45ddc902a9..391df55070 100644
--- a/src/core/trust/taint.ts
+++ b/src/core/trust/taint.ts
@@ -156,9 +156,16 @@ export async function derivedMaintenanceTransaction<T>(engine: BrainEngine, deri
*/
export async function lowerDerivedPage(engine: BrainEngine, derivation: { trust: WriteTrust; inputs: readonly TaintInput[] },
sourceId: string, slug: string): Promise<void> {
- await derivedMaintenanceTransaction(engine, derivation, async tx => ({ result: undefined,
- rows: (await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))
- .map(row => ({ table: 'pages' as const, id: Number(row.id), sourceId })) }));
+ await maintenanceTransaction(engine, tx => lowerDerivedPageIn(tx, derivation, sourceId, slug), derivation.trust);
+}
+
+/** lowerDerivedPage inside a caller's transaction (a managed brain's coordinated write). */
+export async function lowerDerivedPageIn(tx: BrainEngine, derivation: { trust: WriteTrust; inputs: readonly TaintInput[] },
+ sourceId: string, slug: string): Promise<void> {
+ for (const row of await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug])) {
+ await lowerToDerivedTier(tx, 'pages', [Number(row.id)], derivation.trust);
+ await recordTaintEdges(tx, { table: 'pages', id: Number(row.id), sourceId }, derivation.inputs);
+ }
}
// ---------------------------------------------------------------------------
diff --git a/test/extract-entities-managed.test.ts b/test/extract-entities-managed.test.ts
new file mode 100644
index 0000000000..bfc025313f
--- /dev/null
+++ b/test/extract-entities-managed.test.ts
@@ -0,0 +1,116 @@
+/**
+ * #6262 (P2.17): on a managed brain extract_entities wrote stubs, timeline rows and backlinks directly. The writer
+ * guard refused the stub with a raw P0001, the fail-open fallback was refused too, and an existing entity's timeline
+ * refusal was swallowed (`status: ok, timelineAdded: false`). Every write now goes through the coordinator at the
+ * source page's derived tier; a refusal reaches the caller as its envelope. Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operations } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const op = operations.find(o => o.name === 'extract_entities')!;
+const run = (ctx: OperationContext, text: string) => op.handler(ctx, { text, source_slug: 'meetings/notes' }) as Promise<{
+ status: string; quarantined: number; entities: Array<{ slug: string; action: string; timelineAdded: boolean; backlinkCreated: boolean; quarantined?: boolean }> }>;
+
+async function seed(engine: BrainEngine) {
+ await engine.putPage('meetings/notes', { type: 'meeting', title: 'Notes', compiled_truth: 'Met people.', timeline: '', frontmatter: {} });
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'A person.', timeline: '', frontmatter: {} });
+}
+const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ trust_tier: string; frontmatter: Record<string, unknown> }>(
+ "SELECT trust_tier, frontmatter FROM pages WHERE slug=$1 AND deleted_at IS NULL", [slug]))[0];
+const timeline = async (engine: BrainEngine, slug: string) => engine.executeRaw<{ trust_tier: string }>(
+ 'SELECT t.trust_tier FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1', [slug]);
+const backlinks = async (engine: BrainEngine, slug: string) => Number((await engine.executeRaw<{ n: number | string }>(
+ `SELECT count(*) AS n FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE f.slug=$1 AND t.slug='meetings/notes' AND l.context LIKE 'Entity mention from %'`, [slug]))[0]!.n);
+
+const snapshot = async (engine: BrainEngine) => Object.fromEntries(await Promise.all(['people/cedar-example', 'people/alice-example'].map(async slug => {
+ const row = await page(engine, slug);
+ return [slug, { tier: row?.trust_tier, provenance: row?.frontmatter.provenance, status: row?.frontmatter.status,
+ timeline: (await timeline(engine, slug)).map(t => t.trust_tier), backlinks: await backlinks(engine, slug) }];
+})));
+const TEXT = 'Lunch with Cedar Example and Alice Example today.';
+const UNTRUSTED_TEXT = 'Lunch with Cedar Example today.';
+type Baseline = { result: Awaited<ReturnType<typeof run>>; rows: Awaited<ReturnType<typeof snapshot>> };
+const plainEngines: PGLiteEngine[] = [];
+let baseline: Baseline;
+let untrustedBaseline: Baseline;
+beforeAll(async () => {
+ baseline = await unmanaged(TEXT, false);
+ untrustedBaseline = await unmanaged(UNTRUSTED_TEXT, true);
+}, 120_000);
+afterAll(async () => { for (const engine of plainEngines) await engine.disconnect(); });
+/** The same call on an unmanaged brain: the managed result must match it row for row. */
+async function unmanaged(text: string, untrusted: boolean): Promise<Baseline> {
+ const plain = new PGLiteEngine();
+ plainEngines.push(plain);
+ await plain.connect({}); await plain.initSchema();
+ await seed(plain);
+ if (untrusted) await plain.executeRaw("UPDATE pages SET trust_tier='external_untrusted' WHERE slug='meetings/notes'");
+ const result = await run({ engine: plain, config: { engine: 'pglite', embedding_disabled: true }, sourceId: 'default', remote: false, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext, text);
+ return { result, rows: await snapshot(plain) };
+}
+
+for (const databaseUrl of [undefined, ...(process.env.DATABASE_URL ? [process.env.DATABASE_URL] : [])])
+describe(`extract_entities on a managed brain (#6262, ${databaseUrl ? 'postgres' : 'pglite'})`, () => {
+ test('a new entity gets a quarantined stub, a timeline row and a backlink; an existing entity gets its timeline row', async () => {
+ const text = TEXT;
+ const plain = baseline;
+ expect(plain.rows['people/cedar-example']).toMatchObject({ provenance: 'auto-extracted', status: 'unverified' });
+ expect(plain.rows['people/cedar-example']!.timeline).toHaveLength(1);
+ expect(plain.rows['people/alice-example']!.timeline).toHaveLength(1);
+ await managedBrain(async ({ engine, ctx }) => {
+ const result = await run(ctx, text);
+ expect(result.status).toBe('ok');
+ expect(result.entities.find(e => e.slug === 'people/cedar-example')).toMatchObject({ action: 'created', quarantined: true, timelineAdded: true, backlinkCreated: true });
+ expect(result.entities.find(e => e.slug === 'people/alice-example')).toMatchObject({ action: 'updated', timelineAdded: true, backlinkCreated: true });
+ expect(result.entities.map(({ slug, action, timelineAdded, backlinkCreated }) => ({ slug, action, timelineAdded, backlinkCreated })))
+ .toEqual(plain.result.entities.map(({ slug, action, timelineAdded, backlinkCreated }) => ({ slug, action, timelineAdded, backlinkCreated })));
+ expect(await snapshot(engine)).toEqual(plain.rows);
+ const journal = await engine.executeRaw<{ operation: string; state: string }>(
+ "SELECT operation, state FROM persistence_requests WHERE slug='people/cedar-example'");
+ expect(journal).toEqual([{ operation: 'put_page', state: 'committed' }]);
+ }, { databaseUrl, setup: ({ engine }) => seed(engine) });
+ }, 180_000);
+
+ test('an untrusted source page caps the stub and timeline tier as on an unmanaged brain', async () => {
+ const plain = untrustedBaseline;
+ expect(plain.rows['people/cedar-example']!.tier).toBe('external_untrusted');
+ await managedBrain(async ({ engine, ctx }) => {
+ await run(ctx, UNTRUSTED_TEXT);
+ expect(await snapshot(engine)).toEqual(plain.rows);
+ }, { databaseUrl, setup: async ({ engine }) => {
+ await seed(engine);
+ await engine.executeRaw("UPDATE pages SET trust_tier='external_untrusted' WHERE slug='meetings/notes'");
+ } });
+ }, 180_000);
+
+ test('a refused write returns its envelope, never a raw guard error, and writes no stub', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true),set_config('gbrain.persistence_protocol','2',true)");
+ await tx.executeRaw("UPDATE sources SET archived=true WHERE id='default'");
+ });
+ const error = await run(ctx, 'Lunch with Cedar Example today.').then(() => null, e => e as { code?: string; message: string });
+ expect(error?.code).toBe('source_changed');
+ expect(error?.message).not.toContain('writer_coordinator_required');
+ expect(await page(engine, 'people/cedar-example')).toBeUndefined();
+ }, { databaseUrl, setup: ({ engine }) => seed(engine) });
+ }, 180_000);
+
+ test('a stub write still pending stops the batch with write_pending and names what was already written', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const error = await run({ ...ctx, writeWaitMs: 0 }, 'Lunch with Alice Example and Cedar Example today.')
+ .then(() => null, e => e as { code?: string; why?: string });
+ expect(error?.code).toBe('write_pending');
+ expect(error?.why).toContain('1 of 2 entities were written before Cedar Example: people/alice-example');
+ // The accepted stub publishes on its own; its timeline row and backlink wait for the rerun.
+ expect(await timeline(engine, 'people/cedar-example')).toEqual([]);
+ expect(await backlinks(engine, 'people/cedar-example')).toBe(0);
+ }, { databaseUrl, setup: ({ engine }) => seed(engine) });
+ }, 180_000);
+});
diff --git a/test/extract-timeline-from-meetings-managed.test.ts b/test/extract-timeline-from-meetings-managed.test.ts
index 5621f283ef..f18cf11915 100644
--- a/test/extract-timeline-from-meetings-managed.test.ts
+++ b/test/extract-timeline-from-meetings-managed.test.ts
@@ -4,7 +4,7 @@
* one coordinated maintenance request per entity page, re-gated at the meeting's stored tier at apply time, exactly as
* an unmanaged run gates them. Synthetic content only.
*/
-import { describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { extractTimelineFromMeetings } from '../src/core/extract-timeline-from-meetings.ts';
@@ -32,17 +32,21 @@ const flags = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n
const requests = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number | string }>(
"SELECT count(*) AS n FROM persistence_requests WHERE intent->>'kind'='managed_maintenance_meeting_timeline'"))[0]!.n);
+/** The same run on an unmanaged brain: the managed rows must match it. */
+let unmanaged: { rows: Awaited<ReturnType<typeof rows>>; flags: number; result: Awaited<ReturnType<typeof extractTimelineFromMeetings>> };
+let plain: PGLiteEngine;
+beforeAll(async () => {
+ plain = new PGLiteEngine();
+ await plain.connect({}); await plain.initSchema();
+ await seed(plain);
+ const result = await extractTimelineFromMeetings(plain);
+ unmanaged = { rows: await rows(plain), flags: await flags(plain), result };
+}, 120_000);
+afterAll(async () => { await plain.disconnect(); });
+
for (const databaseUrl of [undefined, ...(process.env.DATABASE_URL ? [process.env.DATABASE_URL] : [])])
describe(`extract timeline --from-meetings on a managed brain (#6273, ${databaseUrl ? 'postgres' : 'pglite'})`, () => {
test('rows publish through the coordinator, gated like an unmanaged run; a rerun admits nothing; the job completes', async () => {
- const plain = new PGLiteEngine();
- await plain.connect({}); await plain.initSchema();
- let unmanaged: { rows: Awaited<ReturnType<typeof rows>>; flags: number; result: Awaited<ReturnType<typeof extractTimelineFromMeetings>> };
- try {
- await seed(plain);
- const result = await extractTimelineFromMeetings(plain);
- unmanaged = { rows: await rows(plain), flags: await flags(plain), result };
- } finally { await plain.disconnect(); }
expect(unmanaged.result.batch_errors).toBe(0);
expect(unmanaged.rows.length).toBeGreaterThan(0);
// The hostile meeting at the lowest tier is gated: the parity below compares a gate that acted.
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 2738eeb5c2..f12d3ed403 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -28,6 +28,7 @@ test/doctor-routing-skill-pack-source.test.ts
test/embedding-completion-atomic.serial.test.ts
test/engine-sql-facts-keyset.test.ts
test/extract-endpoint-revision.serial.test.ts
+test/extract-entities-managed.test.ts
test/extract-timeline-from-meetings-managed.test.ts
test/fence-repair-receipts.test.ts
test/graduation-copy.test.ts