Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/capy/memory-trust-writes' into l1a-taint
garrytandf7a2a6d9d53
diff --cc docs/architecture/key-files/core-utilities-2.mdindex f91976371f,1fd46f82d0..29ed6c23ae--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@@ -41,7 -42,9 +42,9 @@@ Current behavior and load-bearing invar- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.- - `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), `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`. `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/` — 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), `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 v233, 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`.++- `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), `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 v233, 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`. `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/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`; 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/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.diff --cc docs/architecture/system-of-record.mdindex 48815da859,bf1df4d791..f1f0e27979--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@@ -212,7 -214,7 +212,7 @@@ Attributed (inside a request, a coordinor a physical projection that leaves attribution untouched):<!-- write-attribution-covered:start -->- - `src/commands/extract-conversation-facts.ts` (2): the conversation fact index's audit rows write through `writeDerivedFacts` (one `maintenanceTransaction` on unmanaged brains, `withDerivedFactsWrite` on managed brains); its extracted rows go through `insertDerivedFacts` (`persistence/derived-facts.ts`), which stamps the page's taint and runs the write gate.-- `src/commands/extract-conversation-facts.ts` (3): the unmanaged conversation fact index writes through `writeDerivedFacts` (one `maintenanceTransaction`); managed brains publish each page as a receipted `managed_maintenance_conversation_facts` request.++- `src/commands/extract-conversation-facts.ts` (2): the unmanaged conversation fact index's audit rows write through `writeDerivedFacts` (one `maintenanceTransaction` at the page's derived tier) and its extracted rows through `insertDerivedFacts` (`persistence/derived-facts.ts`), which also runs the write gate; managed brains publish each page as a receipted `managed_maintenance_conversation_facts` request.- `src/commands/extract-timeline-db.ts` (2): `gbrain extract timeline --source db` commits one `maintenanceTransaction` per 100-row batch on unmanaged brains; managed brains publish per page through a maintenance request.- `src/commands/migrate-engine.ts` (5): engine copy keeps the source rows' attribution values verbatim.- `src/commands/sync/holds.ts` (1): a full sync's move of a held rename (`updateSlug` and its `source_path`) runs in one `maintenanceTransaction`; managed sources publish renames through the sync request preparer.@@@ -225,17 -226,17 +225,18 @@@- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.- `src/core/cycle/extract-atoms-page-state.ts` (1): the atom completion stamp runs in `maintenanceTransaction`.- `src/core/cycle/extract-atoms.ts` (1): stale atom retirement soft-deletes in 500-page `maintenanceTransaction` chunks.- - `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains write through `withDerivedFactsWrite`.-- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication.-- `src/core/cycle/extract-takes.ts` (2): a receipted `managed_maintenance_takes_reextract` request per changed page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.++- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication. Both reconcile paths write at the page's tier and gate new rows.++- `src/core/cycle/extract-takes.ts` (1): one projected-takes writer stamps each page's tier and runs the write gate: inside a receipted `managed_maintenance_takes_reextract` request per changed page on managed brains, one `maintenanceTransaction` per page tier for the unmanaged batch upsert.+- `src/core/enrichment-service.ts` (2): the enrichment stub fallback write and its auto-timeline entry run in `maintenanceTransaction` at the source page's derived tier (the stub import is lowered to it afterwards).+- `src/core/extract-timeline-from-meetings.ts` (1): each meeting timeline batch runs in `maintenanceTransaction`, one meeting tier per batch.- - `src/core/cycle/extract-takes.ts` (1): one projected-takes writer stamps each page's tier and runs the write gate: coordinated per page on managed brains, one `maintenanceTransaction` per page tier for the unmanaged batch upsert.- `src/core/cycle/grade-takes.ts` (1): unmanaged take auto-resolution runs in `maintenanceTransaction`; managed brains publish a `takes_resolve` request.- `src/core/cycle/phantom-redirect.ts` (3): the unmanaged phantom fact move, canonical body refresh and phantom soft delete run in `maintenanceTransaction`; the managed redirect moves facts inside its coordinated write.-- `src/core/cycle/phases/consolidate.ts` (4): unmanaged consolidation takes and fact updates run in `maintenanceTransaction` per cluster step; managed brains submit a maintenance consolidation request.-- `src/core/cycle/synthesize.ts` (1): the unmanaged dream summary page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.+- `src/core/cycle/phases/consolidate.ts` (4): unmanaged consolidation's take insert or re-promotion, consolidation marks and valid_until writeback run in one `derivedMaintenanceTransaction` per cluster at the cluster's derived tier; managed brains submit a maintenance consolidation request.- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).- `src/core/extract/receipt-writer.ts` (1): the extraction receipt page runs in `maintenanceTransaction`.-- `src/core/facts/backstop.ts` (3): the facts backstop's DB-only fallbacks insert each fact in `maintenanceTransaction`; managed brains publish through the facts request preparer.+- `src/core/facts/backstop.ts` (1): the facts backstop's DB-only fallbacks insert each fact through one helper, in `maintenanceTransaction` at the extraction's derived tier; managed brains publish through the facts request preparer.+ - `src/core/facts/conversation-publication.ts` (3): the managed conversation-facts preparer clears each member page's prior rows and inserts its frozen entry (or a blocked outcome row) inside the coordinator publication of its admitted batch request; the unmanaged cleanup runs the same clear in `maintenanceTransaction`.- `src/core/facts/derivation-inputs.ts` (3): `hideDerivedRows` expires derived facts, deactivates derived takes and soft-deletes derived pages inside the purge's coordinated transaction, attributed to the purge request.- `src/core/facts/fence-write.ts` (2): the markdown-first fence reconcile insert and its page body mirror each run in `maintenanceTransaction`.- `src/core/facts/forget.ts` (4): the legacy fence expiry, withdrawal and strike-through each run in `maintenanceTransaction` (nested inside a caller's coordinated write, they keep its actor).@@@ -257,7 -257,6 +258,7 @@@- `src/core/persistence/canonical-projections.ts` (7): fence projection inside the request's publication.- `src/core/persistence/connector-google-receipts.ts` (2): request preparer.- `src/core/persistence/connector-sync.ts` (2): connector publication inside `withCoordinatedWrite`.- - `src/core/persistence/derived-facts.ts` (1): `withDerivedFactsWrite` (managed derived facts); `writeDerivedFacts` runs legacy writers in `maintenanceTransaction` on unmanaged brains; the gated conversation fact insert stamps the page's taint.++- `src/core/persistence/derived-facts.ts` (1): the gated conversation fact insert (`insertDerivedFacts`) on unmanaged brains, in `writeDerivedFacts`' `maintenanceTransaction` at the page's derived tier.- `src/core/persistence/facts-prepare.ts` (3): managed `extract_facts` request preparer.- `src/core/persistence/file-repair.ts` (2): `managed_file_repair` request preparer (#5988).- `src/core/persistence/grandfather.ts` (2): request preparer.@@@ -286,14 -286,19 +288,17 @@@- `src/core/think/index.ts` (1): the saved `think` result page runs in `maintenanceTransaction`.- `src/core/timeline-dedup-repair.ts` (1): runs only from schema migration v139, before migration v193 adds the attribution columns, so it has no actor to record.- `src/core/timeline-write-through.ts` (2): the timeline write-through's page row splice and entry insert run in one `maintenanceTransaction`.+ - `src/core/trust/fence-guard.ts` (2): the guarded fence re-projection detaches or moves higher-tier fact rows inside the page's coordinated publication.+ - `src/core/trust/owner-actions.ts` (1): an owner release inserts the held fact in a coordinated (managed) or attributed (unmanaged) transaction at user_confirmed.+ - `src/core/trust/supersede-handlers.ts` (2): owner accept/undo of a trust proposal re-tiers the new fact inside the checked supersede's transaction.<!-- write-attribution-covered:end -->-Unattributed (on unmanaged brains these write with `NULL` attribution). These-three writers share the link-extraction and mention-linking code, and they are-routed together with that code's rework:+Unattributed (on unmanaged brains these would write with `NULL` attribution).+The list is empty: `gbrain extract` timeline walks, enrichment and meeting+timeline extraction run as tiered derivers since #5575 (I2). A new writer+that cannot be attributed yet is declared here:<!-- write-attribution-unattributed:start -->-- `src/commands/extract.ts` (4): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback.-- `src/core/enrichment-service.ts` (2): enrichment page and auto-timeline entry.-- `src/core/extract-timeline-from-meetings.ts` (1): meeting timeline batch.<!-- write-attribution-unattributed:end -->## The privacy boundarydiff --cc scripts/function-size-baseline.tsvindex d2a0c18a59,b322e7df38..8510930e39--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@@ -32,8 -32,9 +32,8 @@@ src/core/context-engine.ts createGBrainsrc/core/context/retrieval-reflex.ts resolveEntitiesToPointers 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6195: multi-word weak n-gram norms and the weak-title arm call (logic in weakTitleHits)src/core/cycle.ts runCycle 1279 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts); +2 fix wave 12 #6242: lease-set result and the maintenance-busy skip call (logic in skipBrainWidePhases and cycle/lock-set.ts)src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallback- src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)+ src/core/cycle/extract-facts.ts runExtractFacts 380 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence factssrc/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/cycle/patterns.ts runPhasePatterns 310 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6177: budget sizing call, submitted-reflection slice and the last_run record (logic in cycle/patterns-plan.ts)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout)src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 490 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts)src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1047 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datadiff --cc src/commands/extract-conversation-facts.tsindex 56c11b1a23,2e01aefca3..504ff2a0a4--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@@ -75,8 -75,9 +75,9 @@@ importtype ExtractedFact,} from '../core/facts/extract.ts';import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';- import { insertDerivedFacts, managedDerivedFactsPreflight, replaceDerivedFactsForPage, writeDerivedFacts } from '../core/persistence/derived-facts.ts';-import { writeDerivedFacts } from '../core/persistence/derived-facts.ts';++import { insertDerivedFacts, writeDerivedFacts } from '../core/persistence/derived-facts.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+ import { clearConversationFacts, enqueueManagedPage, flushManagedBatch, managedConversationPublisher, startManagedPage, stopsRun, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';import { noPricingMessage } from '../core/budget/no-pricing.ts';import { conversationFactsCostCap } from '../core/facts/conversation-budget.ts';diff --cc src/core/cycle/concept-publication.tsindex 35340377aa,2c95760035..8a07c89d98--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@@ -202,14 -220,25 +227,27 @@@ export async function publishClassicConthrow Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' });}const title = slug.split('/').pop()!.replace(/-/g, ' ');- const file = page ? await conceptFile(engine, slug, sourceId) : null;+ const file = await conceptFile(engine, slug, sourceId);+ const existing = page && file?.parsed ? file.parsed : null;+ if (existing && !fileHoldsPage(existing, page!, snapshot!.tags)) {+ throw Object.assign(new Error('The concept file holds an edit the database has not imported.'), { code: 'revision_conflict' });+ }const markdown = page- ? composeConceptRepublication({ ...page, ...file }, snapshot!.tags, synthesized, narrative)+ ? composeConceptRepublication({ ...page, ...(existing ? { compiled_truth: existing.compiled_truth, timeline: existing.timeline } : {}) },+ snapshot!.tags, synthesized, narrative): serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });await opts.importPage(markdown);+ // The import stamps the page by its own channel; the derivation lowers it to the members' taint and records the edges.+ if (opts.members) await lowerDerivedPage(engine, await conceptDerivation(engine, sourceId, opts.members), sourceId, slug);- if (file || opts.writeThrough) await writeDerivedPageThrough(engine, slug, sourceId);+ if (existing || opts.writeThrough) {+ const written = await writeDerivedPageThrough(engine, slug, sourceId, file ? { expectedFileBytes: file.bytes } : {});+ if (written.skipped === 'file_changed') {+ throw Object.assign(new Error('The concept file changed while the page was published; the edit was kept.'), { code: 'revision_conflict' });+ }+ if (written.error) {+ throw Object.assign(new Error(`The concept file was not written: ${written.error}`), { code: CONCEPT_WRITE_THROUGH_FAILED_CODE });+ }+ }return narrative;} finally {await lock.release();diff --cc src/core/cycle/extract-facts.tsindex e1ca22711e,bcfd8a1ac6..1d41440c8b--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@@ -46,14 -46,17 +46,21 @@@ import { isQuarantined } from '../quaraimport { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';- import { managedDerivedFactsPreflight, withDerivedFactsWrite } from '../persistence/derived-facts.ts';+ import type { GBrainConfig } from '../config.ts';+ import type { PreparedMutation } from '../persistence/coordinator.ts';+ import { isTerminal, type WriteRequest } from '../persistence/model.ts';+ import { maintenanceTransaction } from '../persistence/attribution.ts';+import { withWriteTrust } from '../persistence/context.ts';+import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';- import type { WriteGateConfig } from '../write-gate.ts';+import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';- import type { WriteTrust } from '../trust/tier.ts';- import { maintenanceTransaction } from '../persistence/attribution.ts';+ import { authorizeWrite } from '../persistence/authority.ts';+ import { digest } from '../persistence/digest.ts';+ import { getWriteRequest } from '../persistence/journal.ts';+ import { maintenanceCallerPreflight, maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+ import { resolveManagedFactsEmbedding } from '../persistence/facts-maintenance.ts';+ import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';+ import { opError, OperationError } from '../ops/contract.ts';import {resolveSupersededByRow,supersessionChainOf,@@@ -252,31 -255,6 +259,31 @@@ async function refuseDestructiveReconcireturn true;}+/**+ * #5575 I2/B3: new fence rows restate the page (no model), so they take its+ * tier capped at operator_curated (the caller's write scope) and pass the+ * write gate at it (an owner page never runs it). Held rows go to+ * write_gate_holds, rejected rows are skipped; inserted rows get input edges+ * and flag receipts.+ */+type ReconcileRow = Parameters<BrainEngine['insertFacts']>[0][number];+async function insertReconciledFacts<F extends ReconcileRow>(- tx: BrainEngine, sourceId: string, slug: string, inserts: F[], derivation: Awaited<ReturnType<typeof deriveTrust>>, gateConfig: (db: BrainEngine) => Promise<WriteGateConfig>, tally: GateTally,++ tx: BrainEngine, sourceId: string, slug: string, inserts: F[], derivation: Awaited<ReturnType<typeof deriveTrust>>, tally: GateTally,+): Promise<{ inserted: { inserted: number; ids: number[] }; allowed: F[] }> {- const cfg = inserts.length ? await gateConfig(tx) : null;++ const cfg = inserts.length ? await derivedGateConfig(tx) : null;+ const decisions = inserts.map(f => decideFactWrite(f, { sourceId, slug, payload: { ...(f as ReconcileRow), embedding: null }, input: derivedGateInput(derivation.trust), cfg: cfg! }));+ for (const d of decisions) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'facts', sourceId }, async () => null, tally);+ const allowed = inserts.filter((_, i) => decisions[i].action === 'insert');+ const flags = decisions.filter(d => d.action === 'insert');+ const inserted = allowed.length === 0 ? { inserted: 0, ids: [] as number[] }+ : await tx.insertFacts(allowed.map(f => ({ ...f, superseded_by_row: undefined })), { source_id: sourceId }); // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB+ for (const [i, id] of inserted.ids.entries()) {+ await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);+ if (inserted.ids.length === allowed.length && await recordFlaggedRow(tx, flags[i], { table: 'facts', id, sourceId }) !== null) tally.flagged++;+ }+ return { inserted, allowed };+}+/*** Run one page's destructive reconcile under its page lock (5s, matching the* fence writers in fence-write.ts / forget.ts). A lock still held past the@@@ -342,6 -320,254 +349,256 @@@ async function listExistingFactsForPage);}+ interface FenceReconcilePlan {+ /** Rows the parsed fence carries (duplicates included), for the pages-with-facts count. */+ fenceRows: number;+ extracted: FenceExtractedFact[];+ matched: Map<number, ExistingPageFact>;+ stale: ExistingPageFact[];+ updates: FenceExtractedFact[];+ toInsert: FenceExtractedFact[];+ chain: SupersessionChain;+ /** Nothing to write: every row matches and every supersession pointer is in place. */+ inSync: boolean;+ }++ /**+ * One page's reconcile plan against its stored rows. Null when the fence is+ * not authoritative (warnings are appended): a warning-bearing parse or a+ * fence below the timeline sentinel preserves the page's existing index.+ */+ async function planFenceReconcile(db: BrainEngine, page: { compiled_truth: string | null; timeline: string | null; effective_date?: Date | string | null },+ slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {+ const parsed = parseFactsFence(page.compiled_truth ?? '');+ if (parsed.warnings.length > 0) {+ // The parser deliberately skips malformed rows and returns any rows it+ // could still recover. That partial result is not authoritative: using+ // it for reconciliation would interpret skipped rows as deletions.+ warnings.push(...parsed.warnings.map(w => `${slug}: ${w}`));+ return null;+ }+ // #3625: a fence below the timeline sentinel lands in page.timeline, where+ // parseFactsFence cannot see it; reading compiled_truth alone would treat+ // its rows as deleted. timelineHasGenuineFactsFenceMarker explains the scan.+ if (timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {+ warnings.push(+ `${slug}: FACTS_FENCE_BELOW_SENTINEL: a ## Facts fence was found below ` ++ `the <!-- timeline --> sentinel, where extract_facts cannot see it. ` ++ `Move the fence above the sentinel and re-save — leaving it in place ` ++ `preserves the existing indexed facts but they will not update.`,+ );+ return null;+ }+ // v0.35.4 (D-ENG-1): page.effective_date is the fallback valid_from, so+ // trajectory queries see claim dates rather than import dates.+ const pageEffectiveDate = page.effective_date ? new Date(page.effective_date) : null;+ // #1781: duplicate ACTIVE rows (same claim and source) index once.+ const duplicates = duplicateActiveFenceRows(parsed.facts);+ const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate })+ .filter(f => !duplicates.has(f.row_num));+ // Reconcile by row number, the fence's own unique identity. A DB row whose+ // (row_num, claim) is still in the fence keeps its id and has its other+ // cells updated in place; a row whose number disappeared or whose claim+ // was rewritten is expired and detached (row_num NULL), never deleted.+ const existing = await listExistingFactsForPage(db, slug, sourceId);+ const desiredByRow = new Map(extracted.map(f => [f.row_num, f]));+ const matched = new Map<number, ExistingPageFact>();+ const stale: ExistingPageFact[] = [];+ for (const fact of existing) {+ const desired = fact.row_num == null ? undefined : desiredByRow.get(Number(fact.row_num));+ if (desired && desired.fact === fact.fact) matched.set(desired.row_num, fact);+ else stale.push(fact);+ }+ const updates = extracted.filter(f => {+ const fact = matched.get(f.row_num);+ return fact !== undefined && factCellsDiffer(fact, f);+ });+ const toInsert = extracted.filter(f => !matched.has(f.row_num));+ const chain = supersessionChainOf(extracted, slug);+ let inSync = false;+ if (stale.length === 0 && updates.length === 0 && toInsert.length === 0) {+ const byRow = new Map([...matched].map(([row, fact]) => [row, { id: Number(fact.id), struck: fact.expired_at != null }]));+ inSync = extracted.every(f => {+ const stored = matched.get(f.row_num)!.superseded_by;+ return resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));+ });+ }+ return { fenceRows: parsed.facts.length, extracted, matched, stale, updates, toInsert, chain, inSync };+ }++ /**+ * The destructive half of a plan. A vector-bearing row is never replaced by+ * a row that could not be embedded: until embedding succeeds, rows keep+ * their positions (stale rows whose claim is still active in the fence stay,+ * others are expired in place, new rows wait). In-place updates still apply.+ */+ function reconcileWrites(plan: FenceReconcilePlan) {+ const deferInserts = plan.toInsert.some(f => !f.embedding) && plan.stale.some(f => f.has_embedding);+ const activeClaims = new Set(plan.extracted.filter(f => f.expired_at == null).map(f => `${f.fact}\u0000${f.source}`));+ return {+ deferInserts,+ detach: deferInserts ? [] : plan.stale,+ expireInPlace: deferInserts ? plan.stale.filter(f => f.expired_at == null && !activeClaims.has(`${f.fact}\u0000${f.source}`)) : [],+ inserts: deferInserts ? [] : plan.toInsert,+ };+ }++ /** One page's reconcile writes, inside a transaction that holds the page key. */+ async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: string, plan: FenceReconcilePlan,- writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal): Promise<{ inserted: number; updated: number; warnings: string[] }> {++ writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal, tally: GateTally = emptyGateTally()): Promise<{ inserted: number; updated: number; warnings: string[] }> {++ // #5575 I2: the fence rows restate the page (no model), so every write here is at the page's tier, capped at operator_curated.++ const derivation = await deriveTrust(tx, [{ table: 'pages', sourceId, slug }], { channel: 'derive:facts_fence', projection: true });++ return withWriteTrust(tx, derivation.trust, async () => {+ for (const fact of writes.expireInPlace) {+ await tx.executeRaw('UPDATE facts SET expired_at = COALESCE(expired_at, now()) WHERE id = $1 AND source_id = $2', [fact.id, sourceId]);+ }+ for (const fact of writes.detach) {+ await tx.executeRaw(+ `UPDATE facts SET expired_at = COALESCE(expired_at, now()), row_num = NULL+ WHERE id = $1 AND source_id = $2`,+ [fact.id, sourceId],+ );+ }+ for (const f of plan.updates) {+ await tx.executeRaw(+ `UPDATE facts SET kind = $3, visibility = $4, notability = $5, context = $6,+ valid_from = COALESCE($7::timestamptz, valid_from),+ valid_until = CASE WHEN $8::boolean THEN $9::timestamptz ELSE valid_until END,+ expired_at = CASE WHEN $10::timestamptz IS NULL THEN NULL ELSE COALESCE(expired_at, $10::timestamptz) END,+ source = $11, confidence = $12,+ claim_metric = $13, claim_value = $14, claim_unit = $15, claim_period = $16+ WHERE id = $1 AND source_id = $2`,+ [plan.matched.get(f.row_num)!.id, sourceId, f.kind ?? 'fact', f.visibility ?? 'private', f.notability ?? 'medium',+ f.context ?? null, f.valid_from?.toISOString() ?? null, f.expired_at == null,+ f.valid_until?.toISOString() ?? null, f.expired_at?.toISOString() ?? null, f.source, f.confidence ?? 1.0,+ f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],+ );+ }- const inserted = writes.inserts.length === 0- ? { inserted: 0 }- : await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB- writes.inserts.map(f => ({ ...f, superseded_by_row: undefined })),- { source_id: sourceId },- );- const insertedRows = new Set(writes.inserts.map(f => f.row_num));++ const { inserted, allowed } = await insertReconciledFacts(tx, sourceId, slug, writes.inserts, derivation, tally);++ const insertedRows = new Set(allowed.map(f => f.row_num));+ const linked = await syncSupersession(tx, sourceId, slug, plan.extracted, plan.chain, insertedRows);+ signal?.throwIfAborted();+ const updated = new Set([...plan.updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);+ return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };++ });+ }++ export const FENCE_FACTS_INTENT = 'managed_maintenance_fence_facts';+ export const DELETED_PAGE_FACTS_INTENT = 'managed_maintenance_deleted_page_facts_expire';++ function maintenanceRequestIdFor(parts: unknown[]): string {+ const h = digest(parts);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+ }++ /**+ * Managed brains: one page's reconcile as a database-only request bound to+ * the page revision. The vectors embedded for new rows ride along; the+ * preparer replans under the page lock and uses a vector only for the same+ * (row, claim) under the brain's current embedding model. Null when the page+ * changed or the request is still pending (the next run retries).+ */+ async function publishFenceReconcile(engine: BrainEngine, authority: MaintenanceAuthority, page: { id: number; knowledge_revision?: string | null },- slug: string, toInsert: FenceExtractedFact[]): Promise<{ inserted: number; updated: number; deleted: number; deferred: boolean; warnings: string[] } | null> {++ slug: string, toInsert: FenceExtractedFact[]): Promise<{ inserted: number; updated: number; deleted: number; deferred: boolean; warnings: string[]; write_gate?: GateTally } | null> {+ const sourceId = authority.writer.sourceId;+ const revision = page.knowledge_revision ?? REVISION_BACKFILL_PENDING;+ const embeddings = toInsert.filter(f => f.embedding).map(f => ({ row_num: f.row_num, fact: f.fact, model: f.embedding_model ?? null, vector: Array.from(f.embedding!) }));+ for (let attempt = 0; ; attempt++) {+ const requestId = maintenanceRequestIdFor(['extract-facts-fence-v1', authority.writer.sourceIncarnation, sourceId, slug, revision, digest(embeddings), attempt]);+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;+ try {+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,+ { kind: FENCE_FACTS_INTENT, expected_revision: revision, page_id: page.id, embeddings }, requestId);+ return { inserted: Number(receipt.inserted ?? 0), updated: Number(receipt.updated ?? 0), deleted: Number(receipt.deleted ?? 0),- deferred: receipt.deferred === true, warnings: Array.isArray(receipt.warnings) ? receipt.warnings.map(String) : [] };++ deferred: receipt.deferred === true, warnings: Array.isArray(receipt.warnings) ? receipt.warnings.map(String) : [],++ ...(receipt.write_gate ? { write_gate: receipt.write_gate as GateTally } : {}) };+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'write_pending'].includes(error.code)) return null;+ throw error;+ }+ }+ }++ /** Preparer for `managed_maintenance_fence_facts`: replans the page's reconcile under its key and applies it. */+ export async function prepareFenceFactsReconcile(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const intent = row.intent as { page_id?: unknown; expected_revision?: unknown; embeddings?: Array<{ row_num: number; fact: string; model: string | null; vector: number[] }> } | null;+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ if (!snapshot || snapshot.page.id !== Number(row.page_id) || Number(intent?.page_id) !== snapshot.page.id) {+ throw opError('page_identity_changed', 'The page was deleted or replaced before its facts fence was reconciled.',+ `Page ${row.slug} in source ${row.source_id} changed before request ${row.request_id} ran, so its fact index was left as it was. The next extract_facts run reconciles the current page.`);+ }+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ return { observedRevision: snapshot.revision, noop: true,+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },+ apply: async tx => {+ const current = await tx.getPage(row.slug, { sourceId: row.source_id });+ const warnings: string[] = [];+ const plan = current ? await planFenceReconcile(tx, current, row.slug, row.source_id, warnings) : null;+ if (!plan || plan.inSync) return { status: 'completed', inserted: 0, updated: 0, deleted: 0, deferred: false, warnings };+ const signature = await resolveManagedFactsEmbedding(tx, config, true);+ const vectors = new Map((intent?.embeddings ?? [])+ .filter(e => signature && e.model === signature.model && e.vector.length === signature.dimensions && e.vector.every(Number.isFinite))+ .map(e => [`${e.row_num}\u0000${e.fact}`, e]));+ for (const fact of plan.toInsert) {+ const vector = vectors.get(`${fact.row_num}\u0000${fact.fact}`);+ if (vector) { fact.embedding = new Float32Array(vector.vector); fact.embedding_model = vector.model; }+ }+ const writes = reconcileWrites(plan);- const written = await writeFenceReconcile(tx, row.source_id, row.slug, plan, writes);++ const tally = emptyGateTally();++ const written = await writeFenceReconcile(tx, row.source_id, row.slug, plan, writes, undefined, tally);+ return { status: 'completed', ...written, deleted: writes.detach.length + writes.expireInPlace.length, deferred: writes.deferInserts,++ ...(tally.flagged || tally.held || tally.rejected ? { write_gate: tally } : {}),+ warnings: [...warnings, ...written.warnings] };+ } };+ }++ /**+ * Managed brains: expire the active fence-owned rows of one soft-deleted+ * page as a database-only request. It admits only a page that is still+ * soft-deleted, never restores it, and the apply rechecks the deletion under+ * the page key, so a concurrent restore wins. Returns the expired ids.+ */+ async function expireDeletedPageFactsManaged(engine: BrainEngine, authority: MaintenanceAuthority, slug: string): Promise<number[]> {+ const sourceId = authority.writer.sourceId;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ if (!snapshot?.page.deleted_at) return [];+ for (let attempt = 0; ; attempt++) {+ const requestId = maintenanceRequestIdFor(['extract-facts-deleted-page-v1', authority.writer.sourceIncarnation, sourceId, slug, snapshot.revision, attempt]);+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;+ try {+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,+ { kind: DELETED_PAGE_FACTS_INTENT, expected_revision: snapshot.revision, page_id: snapshot.page.id, deleted_page: true }, requestId);+ return Array.isArray(receipt.expired) ? receipt.expired.map(Number) : [];+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'write_pending'].includes(error.code)) return [];+ throw error;+ }+ }+ }++ /** Preparer for `managed_maintenance_deleted_page_facts_expire`. */+ export async function prepareDeletedPageFactsExpiry(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if (!snapshot || snapshot.page.id !== Number(row.page_id) || !snapshot.page.deleted_at) {+ throw opError('page_identity_changed', 'The deleted page was restored, purged or replaced before its facts were expired.',+ `Page ${row.slug} in source ${row.source_id} is no longer the soft-deleted page request ${row.request_id} was admitted for, so its facts were left as they are. No action is needed; extract_facts reconciles a restored page from its fence.`);+ }+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ return { observedRevision: snapshot.revision, noop: true,+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },+ apply: async tx => {+ const expired = await tx.executeRaw<{ id: number }>(+ `UPDATE facts f SET expired_at = now()+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.id = $3 AND p.deleted_at IS NOT NULL)+ RETURNING f.id`,+ [row.source_id, row.slug, Number(row.page_id)]);+ return { status: 'completed', expired: expired.map(e => Number(e.id)) };+ } };+ }+export interface ExtractFactsOpts {/** Subset of slugs to reconcile. undefined = walk every page in the brain. */slugs?: string[];@@@ -483,14 -707,13 +740,14 @@@ export async function runExtractFactsopts: ExtractFactsOpts = {},): Promise<ExtractFactsResult> {const sourceId = opts.sourceId ?? 'default';- // Managed brains reconcile the same way, but each database write commits- // inside the coordinator's source capability under the page key.- const managed = await managedDerivedFactsPreflight(engine, sourceId);- let gateCfg: Promise<WriteGateConfig> | undefined;- const gateConfig = (db: BrainEngine) => (gateCfg ??= derivedGateConfig(db));+ // Managed brains reconcile the same way, but each page's writes publish as+ // a receipted database-only maintenance request. The authority is+ // preflighted on the first page that needs a write, so a run with nothing+ // to change never needs one; an unacceptable caller still refuses first.+ const managed = await maintenanceCallerPreflight(engine, sourceId);+ const gateTally = emptyGateTally();- const transact = <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>, trust?: WriteTrust): Promise<T> =>- managed ? withDerivedFactsWrite(engine, sourceId, slugs, tx => trust ? withWriteTrust(tx, trust, () => fn(tx)) : fn(tx)) : maintenanceTransaction(engine, fn, trust);+ let authority: Promise<MaintenanceAuthority | null> | undefined;+ const managedAuthority = () => managed ? authority ??= maintenancePreflight(engine, sourceId) : Promise.resolve(null);const result: ExtractFactsResult = {pagesScanned: 0,pagesWithFacts: 0,@@@ -849,47 -977,20 +1011,20 @@@result.warnings.push(`${slug}: destructive fact reconciliation deferred; existing vectors preserved until embedding succeeds`);}- const derivation = await deriveTrust(engine, [{ table: 'pages', id: page.id }], { channel: 'derive:facts_fence', projection: true });- const apply = async () => {- type Written = { inserted: number; updated: number; warnings: string[]; deleted?: number; deferred?: boolean };++ type Written = { inserted: number; updated: number; warnings: string[]; deleted?: number; deferred?: boolean; write_gate?: GateTally };+ const apply = async (): Promise<Written | null> => {+ const authority = await managedAuthority();+ if (authority) return publishFenceReconcile(engine, authority, page, slug, toInsert);try {- return await transact([slug], async tx => {+ return await maintenanceTransaction(engine, async tx => {opts.signal?.throwIfAborted();if (watermark && !await lockReconcileRevision(tx, sourceId, slug, page.knowledge_revision ?? null)) return null;const current = await tx.getPage(slug, { sourceId });if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;- for (const fact of expireInPlace) {- await tx.executeRaw('UPDATE facts SET expired_at = COALESCE(expired_at, now()) WHERE id = $1 AND source_id = $2', [fact.id, sourceId]);- }- for (const fact of detach) {- await tx.executeRaw(- `UPDATE facts SET expired_at = COALESCE(expired_at, now()), row_num = NULL- WHERE id = $1 AND source_id = $2`,- [fact.id, sourceId],- );- }- for (const f of updates) {- await tx.executeRaw(- `UPDATE facts SET kind = $3, visibility = $4, notability = $5, context = $6,- valid_from = COALESCE($7::timestamptz, valid_from),- valid_until = CASE WHEN $8::boolean THEN $9::timestamptz ELSE valid_until END,- expired_at = CASE WHEN $10::timestamptz IS NULL THEN NULL ELSE COALESCE(expired_at, $10::timestamptz) END,- source = $11, confidence = $12,- claim_metric = $13, claim_value = $14, claim_unit = $15, claim_period = $16- WHERE id = $1 AND source_id = $2`,- [matched.get(f.row_num)!.id, sourceId, f.kind ?? 'fact', f.visibility ?? 'private', f.notability ?? 'medium',- f.context ?? null, f.valid_from?.toISOString() ?? null, f.expired_at == null,- f.valid_until?.toISOString() ?? null, f.expired_at?.toISOString() ?? null, f.source, f.confidence ?? 1.0,- f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],- );- }- const { inserted, allowed } = await insertReconciledFacts(tx, sourceId, slug, inserts, derivation, gateConfig, gateTally);- const insertedRows = new Set(allowed.map(f => f.row_num));- const linked = await syncSupersession(tx, sourceId, slug, extracted, chain, insertedRows);- opts.signal?.throwIfAborted();- const updated = new Set([...updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);- const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal);++ const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal, gateTally);if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);- return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };- }, derivation.trust);+ return written;+ });} catch (error) {if (!isAborted(opts.signal)) throw error;result.warnings.push(`${slug}: fact reconciliation cancelled; transaction rolled back`);@@@ -908,10 -1009,10 +1043,11 @@@if (!outcome) return isAborted(opts.signal) ? 'cancelled' : 'deferred';result.factsInserted += outcome.inserted;result.factsUpdated += outcome.updated;- result.factsDeleted += detach.length + expireInPlace.length;+ result.factsDeleted += outcome.deleted ?? detach.length + expireInPlace.length;// resolveSupersededByRow prefixes each message with the slug + row.for (const w of outcome.warnings) result.warnings.push(w);- return deferInserts ? 'deferred' : 'complete';++ if (outcome.write_gate) { gateTally.flagged += outcome.write_gate.flagged; gateTally.held += outcome.write_gate.held; gateTally.rejected += outcome.write_gate.rejected; }+ return (outcome.deferred ?? deferInserts) ? 'deferred' : 'complete';};for (const slug of slugs) {diff --cc src/core/cycle/extract-takes.tsindex 30dc37066f,ddc6086fa7..5d4380e4ec--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@@ -31,13 -32,16 +32,21 @@@ import type { BrainEngine, TakeBatchInpimport { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-fence.ts';import { walkMarkdownFiles } from '../../commands/extract.ts';import { takesPreparation } from '../takes-write.ts';- import { withCoordinatedWrite, withWriteTrust } from '../persistence/context.ts';++import { withWriteTrust } from '../persistence/context.ts';+import { derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';+import { storedTrustTier } from '../trust/tier.ts';+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';+import { decideTakeWrite, recordFlaggedRow } from '../write-gate-store.ts';- import { maintenanceAttribution, maintenanceTransaction } from '../persistence/attribution.ts';+ import { buildTakeRows } from '../batch-rows.ts';+ import { maintenanceTransaction } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';+ import type { PreparedMutation } from '../persistence/coordinator.ts';+ import { isTerminal, type WriteRequest } from '../persistence/model.ts';+ import { authorizeWrite } from '../persistence/authority.ts';+ import { digest } from '../persistence/digest.ts';+ import { getWriteRequest } from '../persistence/journal.ts';+ import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+ import { opError, OperationError } from '../ops/contract.ts';export interface ExtractTakesOpts {/** Brain repo root. Required for source='fs'. */@@@ -358,17 -350,67 +398,69 @@@ async function reextractCoordinatedrebuild: boolean,result: ExtractTakesResult,): Promise<void> {- const attribution = await maintenanceAttribution(engine);- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {- await tx.lockPageKeys([{ sourceId, slug }]);- const [page] = await tx.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(- 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL',- [sourceId, slug]);- if (!page) return;- const takes = await reconcilePageTakes(tx, page, slug, rebuild, false, result);- if (takes.length === 0) return;- result.takesUpserted += await upsertProjectedTakes(tx, takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)), result, tx);- }, attribution));+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ const [page] = await engine.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(+ 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]);+ if (!snapshot || !page || Number(page.id) !== snapshot.page.id) return;+ const plan = await plannedTakes(engine, page, rebuild);+ if (!plan.changed) {+ const { warnings } = parseTakesFence(`${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`);+ recordTakesWarnings(slug, warnings, result);+ if (plan.takes.length) result.pagesWithTakes++;+ return;+ }+ const authority = await authorityFor(sourceId);+ for (let attempt = 0; ; attempt++) {+ const h = digest(['extract-takes-db-v1', authority.writer.sourceIncarnation, sourceId, slug, snapshot.revision, rebuild, attempt]);+ const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;+ try {+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,+ { kind: TAKES_REEXTRACT_INTENT, expected_revision: snapshot.revision, rebuild }, requestId);+ result.takesUpserted += Number(receipt.takes_upserted ?? 0);++ const gate = receipt.write_gate as GateTally | undefined;++ if (gate) { const t = result.writeGate ??= emptyGateTally(); t.flagged += gate.flagged; t.held += gate.held; t.rejected += gate.rejected; }+ if (receipt.with_takes === true) result.pagesWithTakes++;+ recordTakesWarnings(slug, Array.isArray(receipt.warnings) ? receipt.warnings.map(String) : [], result);+ return;+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'write_pending'].includes(error.code)) {+ result.warnings.push(`${slug}: TAKES_REEXTRACT_DEFERRED: the page changed or its request is still pending (${error.code}); rerun to extract it`);+ return;+ }+ throw error;+ }+ }+ }++ function recordTakesWarnings(slug: string, warnings: string[], result: ExtractTakesResult): void {+ for (const w of warnings) {+ result.warnings.push(`${slug}: ${w}`);+ if (w.startsWith('TAKES_HOLDER_INVALID')) result.failedFiles.push({ path: slug, error: w });+ }+ }++ /** Preparer for `managed_maintenance_takes_reextract`: reconciles one page's takes under its key. */+ export async function prepareTakesReextract(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) {+ throw opError('page_identity_changed', 'The page was deleted or replaced before its takes were extracted.',+ `Page ${row.slug} in source ${row.source_id} changed before request ${row.request_id} ran, so its takes index was left as it was. Run gbrain extract takes --source db again; it reads the current page.`);+ }+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ const rebuild = (row.intent as { rebuild?: unknown } | null)?.rebuild === true;+ return { observedRevision: snapshot.revision, noop: true,+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },+ apply: async tx => {+ const [page] = await tx.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(+ 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [row.source_id, row.slug]);+ const local: ExtractTakesResult = { pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [] };+ const takes = page ? await reconcilePageTakes(tx, page, row.slug, rebuild, false, local) : [];- const upserted = takes.length ? await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(page!.id, t))) : 0;- return { status: 'completed', takes_upserted: upserted, with_takes: local.pagesWithTakes > 0,++ const upserted = takes.length ? await upsertProjectedTakes(tx, takes.map(t => takesPreparation.toCanonicalBatchInput(page!.id, t)), local, tx) : 0;++ return { status: 'completed', takes_upserted: upserted, with_takes: local.pagesWithTakes > 0, ...(local.writeGate ? { write_gate: local.writeGate } : {}),+ warnings: local.warnings.map(w => w.slice(row.slug.length + 2)) };+ } };}/** Single-entry dispatch for `gbrain extract takes` and the v0_28_0 orchestrator. */diff --cc src/core/facts/fence-write.tsindex f9f14b38a8,b52210b8c4..91e7a113e9--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@@ -56,10 -56,7 +56,10 @@@ import { logStubGuardEvent } from './stimport { isFactWithdrawn } from './withdrawal.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';- import { withTrustKeep } from '../persistence/context.ts';+ import { withPageTierKept } from '../trust/fence-append.ts';+import { recordTaintEdges } from '../trust/taint.ts';+import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';+import type { TaintInput, WriteTrust } from '../trust/tier.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {diff --cc src/core/persistence/derived-facts.tsindex 6fd7b6e5b4,9026a67dd7..eeee0e92be--- a/src/core/persistence/derived-facts.ts+++ b/src/core/persistence/derived-facts.ts@@@ -1,152 -1,21 +1,71 @@@-import type { BrainEngine } from '../engine.ts';+import type { BrainEngine, NewFact } from '../engine.ts';- import type { Action } from '../agent-output.ts';import { opError } from '../ops/contract.ts';- import { readFix, trustedCliRequired } from '../ops/op-fix.ts';- import { currentSubmissionAuthority } from '../minions/submission-authority.ts';- import { withCoordinatedWrite, withWriteTrust } from './context.ts';+ import { maintenanceTransaction } from './attribution.ts';+ import { managedPersistenceEnabled } from './ownership.ts';+import { deriveTrust, recordTaintEdges } from '../trust/taint.ts';+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';+import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';- import { maintenanceAttribution, maintenanceTransaction } from './attribution.ts';- import { currentVerifiedLocalWriter } from './identity.ts';- import { managedPersistenceEnabled } from './ownership.ts';- import { assertPersistenceAccepting } from './service.ts';-- const sourcesFix = (sourceId: string): Action => readFix(`Lists sources with their archived state, including ${sourceId}.`, { argv: ['gbrain', 'sources', 'list', '--json'] });-- /**- * Database-only fact rows derived from page text (the fence reconcile, the- * conversation fact index) never touch a canonical file, so a managed brain- * publishes them like derived links: inside the coordinator's source- * capability, serialized on the page key. Returns false on an unmanaged brain.- * Runs before any provider spend.- */- export async function managedDerivedFactsPreflight(engine: BrainEngine, sourceId: string): Promise<boolean> {- if (!await managedPersistenceEnabled(engine)) return false;- assertPersistenceAccepting(engine);- const job = currentSubmissionAuthority();- if (job && job.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {- throw trustedCliRequired('Managed fact maintenance requires a local writer; remote maintenance jobs are not supported.');- }- const [source] = await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);- if (!source || source.archived) {- throw opError('source_changed', 'The fact maintenance source is not active.',- `Source ${sourceId} is archived or missing, so its facts were not maintained and no model was called. Restore the source first if it should be maintained.`,- { fix: sourcesFix(sourceId) });- }- return true;- }-- /**- * One committed transaction holding the source capability and the page keys,- * after revalidating (under a shared source lock, before the page locks) that- * the source is still active: model work may have outlived an archive.- */- export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: string, slugs: readonly string[],- fn: (tx: BrainEngine) => Promise<T>): Promise<T> {- const attribution = await maintenanceAttribution(engine);- return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {- const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);- if (!source || source.archived) {- throw opError('source_changed', 'The fact maintenance source changed during extraction; nothing was written.',- `Source ${sourceId} was archived or removed while its facts were extracted, so nothing was written. Restore the source before maintaining its facts again.`,- { fix: sourcesFix(sourceId) });- }- await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));- return fn(tx);- }, attribution));- }++/**+ * #5575 I2: the conversation fact extractor's context is the page alone, so+ * its rows carry the page's stored tier capped at agent_written (an+ * own-session transcript import is agent_written, a third-party one+ * external_untrusted) and an edge to the page.+ */- const conversationDerivation = (engine: BrainEngine, sourceId: string, slug: string) =>++export const conversationDerivation = (engine: BrainEngine, sourceId: string, slug: string) =>+ deriveTrust(engine, [{ table: 'pages', sourceId, slug }], { channel: 'derive:conversation_facts' });++/** Edges for the fact ids a batch insert returned (`{ ids }`); other results (deletes, counts) record none. */+async function recordInsertedEdges(tx: BrainEngine, sourceId: string, result: unknown, inputs: Awaited<ReturnType<typeof conversationDerivation>>['inputs']) {+ const ids = (result as { ids?: unknown } | null)?.ids;+ for (const id of Array.isArray(ids) ? ids : []) await recordTaintEdges(tx, { table: 'facts', id: Number(id), sourceId }, inputs);+}++/**+ * #5575 B3: one batch of extracted rows through the write gate at the page's+ * declared tier (ENG-18): allowed rows are inserted with their input edges+ * and flag receipts, held rows go to write_gate_holds, rejected rows are+ * counted and skipped.+ */+type FenceRow = NewFact & { row_num: number; source_markdown_slug: string };- async function insertGatedFacts(tx: BrainEngine, sourceId: string, slug: string, rows: FenceRow[],++export async function insertGatedFacts(tx: BrainEngine, sourceId: string, slug: string, rows: FenceRow[],+ derivation: Awaited<ReturnType<typeof conversationDerivation>>): Promise<{ inserted: number; ids: number[]; write_gate: GateTally }> {+ const cfg = await derivedGateConfig(tx);+ const input = derivedGateInput(derivation.trust);+ const write_gate = emptyGateTally();+ const decisions = rows.map(row => decideFactWrite({ fact: row.fact, context: row.context, source: row.source },+ { sourceId, slug, payload: { ...row, embedding: null }, input, cfg }));+ for (const decision of decisions) if (decision.action !== 'insert') await applyGateDecision(tx, decision, { table: 'facts', sourceId }, async () => null, write_gate);+ const allowed = rows.filter((_, i) => decisions[i].action === 'insert');+ const flags = decisions.filter(decision => decision.action === 'insert');+ const result = allowed.length ? await tx.insertFacts(allowed, { source_id: sourceId }) : { inserted: 0, ids: [] }; // gbrain-allow-direct-insert: conversation fact rows that passed the write gate+ for (const [i, id] of result.ids.entries()) {+ await recordTaintEdges(tx, { table: 'facts', id, sourceId }, derivation.inputs);+ if (result.ids.length === allowed.length && await recordFlaggedRow(tx, flags[i], { table: 'facts', id, sourceId }) !== null) write_gate.flagged++;+ }+ return { inserted: result.inserted, ids: result.ids, write_gate };+}+- /** The conversation fact index's gated batch insert, in writeDerivedFacts' transaction shape. */++/** The conversation fact index's gated batch insert, in writeDerivedFacts' transaction shape (unmanaged brains). */+export async function insertDerivedFacts(engine: BrainEngine, sourceId: string, slug: string, rows: FenceRow[]) {+ const derivation = await conversationDerivation(engine, sourceId, slug);+ return writeDerivedFacts(engine, sourceId, slug, db => insertGatedFacts(db, sourceId, slug, rows, derivation));+}/**- * Legacy writers run in one maintenance transaction on unmanaged brains. On a- * managed brain the page must still be live under its lock, so rows are never- * published for a page deleted or purged while the model ran.+ * Unmanaged brains: database-only fact rows derived from page text (the+ * conversation fact index) commit in one maintenance transaction under the- * maintenance principal. A managed brain publishes them as receipted- * maintenance requests instead (facts/conversation-publication.ts,- * cycle/extract-facts.ts), so this refuses there rather than write a guarded- * table without a receipt.++ * maintenance principal, at the page's derived tier (#5575 I2). A managed++ * brain publishes them as receipted maintenance requests instead++ * (facts/conversation-publication.ts, cycle/extract-facts.ts), so this++ * refuses there rather than write a guarded table without a receipt.*/export async function writeDerivedFacts<T>(engine: BrainEngine, sourceId: string, slug: string,fn: (db: BrainEngine) => Promise<T>): Promise<T> {+ if (await managedPersistenceEnabled(engine)) {+ throw opError('writer_coordinator_required', 'Managed brains publish derived facts through receipted maintenance requests.',+ `The derived facts of ${slug} in source ${sourceId} were not written: a managed brain publishes them through the coordinator, which this caller bypassed. Run the extraction command again; report this if it repeats.`);+ }- return maintenanceTransaction(engine, fn);+ const { trust, inputs } = await conversationDerivation(engine, sourceId, slug);- const write = async (db: BrainEngine) => { const result = await fn(db); await recordInsertedEdges(db, sourceId, result, inputs); return result; };- if (!await managedPersistenceEnabled(engine)) return maintenanceTransaction(engine, write, trust);- return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {- const [page] = await tx.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);- if (!page) {- throw opError('page_not_found', 'The page was deleted during fact extraction; nothing was written.',- `Page ${slug} in source ${sourceId} was deleted while its facts were extracted, so nothing was written. No action is needed unless the page should still exist.`);- }- return withWriteTrust(tx, trust, () => write(tx));- });- }-- /**- * Managed replacement of one page's derived fact batch. Nothing is written- * while the model runs; afterwards, under the source capability and page key,- * `isCurrent` rechecks the page the batch was extracted from, then the rows- * whose `source` starts with `sourcePrefix` are deleted and `build(tx)`'s rows- * inserted in the same transaction. A failed extraction or a changed page- * leaves the prior batch in place.- */- export async function replaceDerivedFactsForPage(engine: BrainEngine, sourceId: string, slug: string, input: {- sourcePrefix: string;- isCurrent: (tx: BrainEngine) => Promise<boolean>;- build: (tx: BrainEngine) => Promise<Array<NewFact & { row_num: number; source_markdown_slug: string }>>;- }): Promise<{ deleted: number; inserted: number }> {- return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {- if (!await input.isCurrent(tx)) {- throw opError('revision_conflict', 'The page changed during fact extraction; its prior facts were kept.',- `Page ${slug} in source ${sourceId} changed while its facts were extracted, so its prior facts were kept. The next fact maintenance pass extracts from the current page.`);- }- const [deleted] = await tx.executeRaw<{ count: string }>(- `WITH del AS (DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE $3 RETURNING 1)- SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug, `${input.sourcePrefix}%`]);- const rows = await input.build(tx);- const derivation = await conversationDerivation(tx, sourceId, slug);- const { inserted } = rows.length ? await withWriteTrust(tx, derivation.trust, () => insertGatedFacts(tx, sourceId, slug, rows, derivation)) : { inserted: 0 };- return { deleted: Number(deleted?.count ?? 0), inserted };- });++ return maintenanceTransaction(engine, async db => { const result = await fn(db); await recordInsertedEdges(db, sourceId, result, inputs); return result; }, trust);}diff --cc src/core/persistence/facts-prepare.tsindex a4c934c149,12fc496a69..5873738be7--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@@ -19,11 -19,9 +19,13 @@@ import type { WriteRequest } from './moimport type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';import { assertManagedFactsEmbedding } from './facts-maintenance.ts';import { normalizeTargetFences } from '../fence-repair/import-step.ts';+ import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';+ import { withPageTierKept } from '../trust/fence-append.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';+import { declaredWriteTrust, derivedWriteTrust, readDerivationDeclaration, readTaintInputs, recordTaintEdges } from '../trust/taint.ts';+import { minTrust, type TaintInput, type WriteTrust } from '../trust/tier.ts';+import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally } from '../trust/derived-gate.ts';+import { decideFactWrite, recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'? readFix(`Reads fact request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })