Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W1 trust prerequisites: hold lower-tier take/timeline removals for the owner; propagate tier lowerings to derived rows (#6783 §12 (a), (b))

garrytan937057a76972
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index c9c38dd25a..cae103ae69 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.
-- `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/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, and holds take and timeline rows a lower-tier write would delete, replace or deactivate (`guardFenceTakes`, `heldRows`, `contestHeldRows`; projection, `takes_remove`, takes reconcile, timeline orphan prune; W1 #6783 §12 (a)); `held-removals.ts` is the owner's accept of those `forget` proposals (the page's text rules the row; a refused `takes_remove` reruns as an owner `takes_remove` bound by a nonce); `propagation.ts` lowers rows derived from a lowered input through `derivation_inputs` and never promotes (`propagateTierLowering`, §12 (b)); tests `test/trust-held-removals.test.ts` (PGLite and Postgres); `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` (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. `claim-sources --relower [--dry-run]` (`relowerClaimedRows`, backfill.ts) is the lower-only #6533 repair: `trust_claim` rows whose page rule now ranks below their stored tier (legacy `extracted_by: extract_atoms-*` atoms) drop to it, pages first with child rows following through the relower-mode page taint, receipt `write_origin.channel` `trust_relower`; the dry run reports the same rows; doctor `trust_sources_unclaimed` names it. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`, `test/trust-claim-relower.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a763f639b9..dca88d4e23 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1198,7 +1198,7 @@ More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-edit
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A remote caller asked to forget a fact more trusted than its own writes, so nothing was forgotten and the owner was asked instead. | Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired. | Do not retry. Tell the user the fact needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host). | user | `repeat the read that failed` | 3 | no |
+| A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead. | Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired. | Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host). | user | `repeat the read that failed` | 3 | no |
### frontmatter_slug_conflict
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1d6359f1e2..802fa99a9c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -642,6 +642,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },
{ since: '0.60.249.0', text: 'On a brain without managed persistence, `gbrain restore` / `restore_page` of a soft-deleted page whose recorded file is gone from the checkout now refuses (`source_changed`, detail `canonical_file_absent`) when the restore writes no file, instead of restoring a page the next `gbrain sync --full` deletes again. Put the file back and sync, or pass `--detach` (`detach: true`) to restore it database-only (`database_only_reason=detached`, no `source_path`); a file synced back at its path binds the page again. New doctor check `missing_recorded_files` lists live pages a full sync would delete this way.' },
{ since: '0.60.250.0', text: 'Remote agents and token-floor connections now get stored contradiction findings from `find_contradictions` instead of an availability note or a refusal: only findings whose two sides they can read now, each side re-read live with its `source_id` and `trust_tier`, never the stored report text; `min_trust` and the token floor filter instead of refusing. A local `gbrain find-contradictions --source <id>` (or `GBRAIN_SOURCE`) now gets that scoped view instead of the note; the bare command still reads the whole stored run.' },
+ // W1 #6783 §12 (a) and (b).
+ { since: '0.60.250.0', text: 'A write less trusted than a take or timeline row no longer deletes, replaces or deactivates it. A page publish (`put_page`, sync, a maintenance republish) that drops or rewrites such a row, `takes_remove`, the takes reconcile (`gbrain extract takes`) and the timeline orphan prune now keep the row as it is and file a `forget` proposal (`gbrain trust review`): `gbrain trust confirm tp<id>` applies the change, `gbrain trust drop tp<id>` keeps the row. A refused `takes_remove` returns `forget_requires_owner` with the proposal ref. The page text keeps what the writer published, and the put_page response lists the proposals under `contested`.' },
+ { since: '0.60.250.0', text: 'Lowering a row\'s trust tier now lowers what was derived from it: facts, takes, pages and timeline rows reached through their recorded derivation inputs drop to the least trusted of their current inputs (an agent edit that lowers a page, an owner tier change, `gbrain trust claim-sources --relower`, a derived republish, a fence field rewrite). Raising a tier never promotes a derivative, and recorded history keeps its tiers. A lowered row\'s `write_origin.input_lowered` names the tier it had; on a managed brain a dependent in another source is marked `needs_rederive` instead.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.ts
index 5d4380e4ec..063de2bdad 100644
--- a/src/core/cycle/extract-takes.ts
+++ b/src/core/cycle/extract-takes.ts
@@ -34,7 +34,8 @@ import { walkMarkdownFiles } from '../../commands/extract.ts';
import { takesPreparation } from '../takes-write.ts';
import { withWriteTrust } from '../persistence/context.ts';
import { derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';
-import { storedTrustTier } from '../trust/tier.ts';
+import { storedTrustTier, type TrustTier } from '../trust/tier.ts';
+import { contestHeldRows, guardTakeRows, heldRows, type HeldChange } from '../trust/fence-guard.ts';
import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
import { decideTakeWrite, recordFlaggedRow } from '../write-gate-store.ts';
import { buildTakeRows } from '../batch-rows.ts';
@@ -104,6 +105,29 @@ async function getPageIdForSlug(engine: BrainEngine, slug: string, sourceId: str
return rows[0]?.id ?? null;
}
+/** The tier a takes reconcile restates the page at: its page's tier, capped as a projection (upsertProjectedTakes). */
+async function reconcileTier(engine: BrainEngine, pageId: number): Promise<{ tier: TrustTier; sourceId: string; slug: string } | null> {
+ const [page] = await engine.executeRaw<{ source_id: string; slug: string; trust_tier: string | null }>('SELECT source_id, slug, trust_tier FROM pages WHERE id = $1', [pageId]);
+ if (!page) return null;
+ const tier = derivedWriteTrust({ channel: 'derive:takes_fence', inputs: [{ table: 'pages', id: pageId, tier: storedTrustTier(page.trust_tier) }], projection: true }).tier;
+ return { tier, sourceId: page.source_id, slug: page.slug };
+}
+
+/**
+ * W1 #6783 §12 (a): of the stored takes a reconcile would delete, those more trusted than the page's restatement or held
+ * by an open contest stay; each gets the owner's `forget` proposal. Then the rest are deleted.
+ */
+async function deleteUnheldTakes(engine: BrainEngine, pageId: number, where: string, params: unknown[], change: HeldChange): Promise<void> {
+ const candidates = (await engine.executeRaw<{ id: number }>(`SELECT id FROM takes WHERE page_id = $1 AND ${where}`, [pageId, ...params])).map(r => Number(r.id));
+ if (!candidates.length) return;
+ const page = await reconcileTier(engine, pageId);
+ const held = page ? await heldRows(engine, 'takes', candidates, { writer: page.tier, pending: true }) : new Map();
+ if (page && held.size) await contestHeldRows(engine, { sourceId: page.sourceId, slug: page.slug, table: 'takes', proposer: 'takes_reextract', writer: page.tier,
+ rows: [...held].map(([id, tier]) => ({ id, tier, change })) });
+ const ids = candidates.filter(id => !held.has(id));
+ if (ids.length) await engine.executeRaw('DELETE FROM takes WHERE id = ANY($1::bigint[])', [ids]);
+}
+
/**
* Remove takes whose rows left the page's fence. Only a fence that parsed
* cleanly is authoritative (a skipped malformed row is not a deletion), and a
@@ -118,17 +142,14 @@ async function pruneRemovedTakes(
dryRun: boolean,
): Promise<void> {
if (dryRun || warnings.length > 0 || !body.includes(TAKES_FENCE_BEGIN)) return;
- await engine.executeRaw(
- 'DELETE FROM takes WHERE page_id = $1 AND NOT (row_num = ANY($2::integer[]))',
- [pageId, takes.map(t => t.rowNum)],
- );
+ await deleteUnheldTakes(engine, pageId, 'NOT (row_num = ANY($2::integer[]))', [takes.map(t => t.rowNum)], 'removed');
}
/** Rebuild: drop indexed rows the fence no longer carries with the same claim; rows that still match keep resolution and vector. */
async function deleteDivergedTakes(engine: BrainEngine, pageId: number, takes: ParsedTake[]): Promise<void> {
- await engine.executeRaw(`DELETE FROM takes WHERE page_id = $1 AND NOT EXISTS (
+ await deleteUnheldTakes(engine, pageId, `NOT EXISTS (
SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) AS f(row_num int, claim text) WHERE f.row_num = takes.row_num AND f.claim = takes.claim)`,
- [pageId, JSON.stringify(takes.map(t => ({ row_num: t.rowNum, claim: t.claim })))]);
+ [JSON.stringify(takes.map(t => ({ row_num: t.rowNum, claim: t.claim })))], 'replaced');
}
function parsedTakeToBatchInput(pageId: number, t: ParsedTake): TakeBatchInput {
@@ -173,8 +194,17 @@ async function upsertProjectedTakes(engine: BrainEngine, rows: TakeBatchInput[],
const decisions = group.map(r => decideTakeWrite({ claim: r.claim, source: r.source }, { sourceId: pages.get(r.page_id)?.source_id ?? 'default',
slug: pages.get(r.page_id)?.slug ?? null, payload: { ...r }, input: derivedGateInput(trust), cfg }));
for (const [i, d] of decisions.entries()) if (d.action !== 'insert') await applyGateDecision(tx, d, { table: 'takes', sourceId: pages.get(group[i].page_id)?.source_id ?? 'default' }, async () => null, tally);
- const allowed = group.filter((_, i) => decisions[i].action === 'insert');
- const flags = decisions.filter(d => d.action === 'insert');
+ // W1 #6783 §12 (a): a row that would replace or deactivate a more trusted (or contested) take is not written.
+ const held = await guardTakeRows(tx, group.filter((_, i) => decisions[i].action === 'insert').map(r => ({ page_id: r.page_id, row_num: r.row_num, claim: r.claim,
+ kind: r.kind, holder: r.holder, active: r.active ?? true })), [], { pending: true });
+ for (const pageId of new Set(held.map(h => h.page_id))) {
+ const page = pages.get(pageId);
+ if (page) await contestHeldRows(tx, { sourceId: page.source_id, slug: page.slug, table: 'takes', proposer: 'takes_reextract', rows: held.filter(h => h.page_id === pageId) });
+ }
+ const heldKeys = new Set(held.map(h => `${h.page_id}:${h.row_num}`));
+ const insertable = (r: TakeBatchInput, i: number) => decisions[i].action === 'insert' && !heldKeys.has(`${r.page_id}:${r.row_num}`);
+ const allowed = group.filter(insertable);
+ const flags = decisions.filter((d, i) => insertable(group[i], i));
const count = allowed.length ? await tx.addTakesBatch(allowed) : 0;
for (const [i, r] of allowed.entries()) {
const page = pages.get(r.page_id);
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 01178a9914..720ba8e83f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -208,7 +208,7 @@ export const CODES = {
file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
- forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A remote caller asked to forget a fact more trusted than its own writes, so nothing was forgotten and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
+ forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 94b4a597c9..e9b8d7a0c4 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -16,7 +16,8 @@ import type { OperationError } from '../ops/contract.ts';
import { protectedRegions } from '../fence-scan.ts';
import { FENCE_ROWS_MAX, fenceOperationError, scanCanonicalFences } from '../fence-repair/refusal.ts';
import type { FenceSection } from '../fence-repair/types.ts';
-import { guardFenceRows } from '../trust/fence-guard.ts';
+import { contestHeldRows, factsAboveWriter, guardFenceRows, guardFenceTakes, heldRows } from '../trust/fence-guard.ts';
+import { propagateFactLowering } from '../trust/propagation.ts';
import { loadWriteGateConfig } from '../trust/gate-outcomes.ts';
const FENCE_PAIRS=[{begin:FACTS_FENCE_BEGIN,end:FACTS_FENCE_END},{begin:TAKES_FENCE_BEGIN,end:TAKES_FENCE_END}];
@@ -323,6 +324,15 @@ function insertCanonicalTimeline(tx: BrainEngine, pageId: number, entries: Extra
ON CONFLICT (page_id,date,md5(summary),source) DO NOTHING`, [pageId, rows]);
}
+/** The page body's own entry for one timeline row (same date, source and summary), inserted when the page carries it. */
+export async function reprojectTimelineRow(tx: BrainEngine, pageId: number, body: CanonicalBody, slug: string,
+ row: { date: string; source: string | null; summary: string }): Promise<boolean> {
+ const entry = canonicalTimeline(body, slug).get(timelineKey({ ...row, date: String(row.date) }));
+ if (!entry) return false;
+ await insertCanonicalTimeline(tx, pageId, [entry]);
+ return true;
+}
+
export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {
const scan=scanCanonicalFences(page);
if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);
@@ -374,11 +384,11 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
const projectFences = !isQuarantined(page.frontmatter);
const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],
page, prior?.page ?? null, slug, writer, policy);
- const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete')
- .map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' })));
- const refreshes = JSON.stringify(pinned.filter(row => row.action === 'refresh_detail')
+ const deletionRows = pinned.filter(row => row.action === 'delete')
+ .map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' }));
+ const refreshRows = pinned.filter(row => row.action === 'refresh_detail')
.map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) }))
- .filter(row => row.next !== row.detail));
+ .filter(row => row.next !== row.detail);
const priorTakes = prior ? canonicalTakeRows(prior.page) : new Set<number>();
// TE1 (#6188): when the prior takes fence does not parse, its stored rows count as prior canonical rows, so a
// row Tier 1 normalized (same number, holder `system` -> `brain`) updates its stored take instead of colliding.
@@ -403,6 +413,19 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
if (id == null) return { timelineRowsRemoved: null };
// #5969: only rows this statement actually deleted count; a row changed since preparation is left alone and uncounted.
const removedDates: string[] = [];
+ // W1 #6783 §12 (a): a timeline row or take more trusted than the writer is never deleted, replaced or deactivated by
+ // it. It stays as it is and a `forget` proposal asks the owner (trust/fence-guard.ts), decided before any statement runs.
+ const heldTimeline = await heldRows(tx, 'timeline_entries', [...deletionRows, ...refreshRows].map(row => Number(row.id)));
+ const deletions = JSON.stringify(deletionRows.filter(row => !heldTimeline.has(Number(row.id))));
+ const refreshes = JSON.stringify(refreshRows.filter(row => !heldTimeline.has(Number(row.id))));
+ const heldTakes = projectFences ? await guardFenceTakes(tx, id, takes, takeRowsGone) : [];
+ const heldRowNums = new Set(heldTakes.map(row => row.row_num));
+ const projectedTakes = heldRowNums.size ? takes.filter(take => !heldRowNums.has(take.rowNum)) : takes;
+ const contestHeld = async () => [
+ ...await contestHeldRows(tx, { sourceId, slug, table: 'timeline_entries', proposer: 'fence_projection',
+ rows: [...heldTimeline].map(([rowId, tier]) => ({ id: rowId, tier, change: deletionRows.some(row => Number(row.id) === rowId) ? 'removed' as const : 'detail_changed' as const })) }),
+ ...await contestHeldRows(tx, { sourceId, slug, table: 'takes', proposer: 'fence_projection', rows: heldTakes }),
+ ];
if (quoted && projectFences) await refuseQuotedFenceLoss(tx, id, quoted, takeRowsGone, factRows, slug, sourceId);
// Fact IDs in permanent receipts remain meaningful when a canonical row is
// removed/replaced. Expire and detach its row position instead of deleting it.
@@ -429,10 +452,10 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
expired_at text,source text,confidence real,claim_metric text,claim_value double precision,claim_unit text,claim_period text,attributed_to text)
WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num=r.row_num`, [sourceId, slug, fieldRows]) : Promise.resolve([]);
const checkTakes = () => refuseCollisions(tx, id);
- const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone]);
+ const dropTakes = () => tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])', [id, takeRowsGone.filter(n => !heldRowNums.has(n))]);
// Full canonical versions include resolution fields; a revert restores those
// fields from Markdown too, without the ordinary immutable-resolution API.
- const resolutions = JSON.stringify(takes.map(take => ({ row_num: take.rowNum, resolved_at: take.resolvedAt ?? null,
+ const resolutions = JSON.stringify(projectedTakes.map(take => ({ row_num: take.rowNum, resolved_at: take.resolvedAt ?? null,
resolved_quality: take.resolvedQuality ?? null,
resolved_outcome: take.resolvedQuality === 'correct' ? true : take.resolvedQuality === 'incorrect' ? false : null,
resolved_source: take.resolvedEvidence ?? null, resolved_value: take.resolvedValue ?? null, resolved_unit: take.resolvedUnit ?? null,
@@ -463,7 +486,8 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
try {
if (!projectFences) {
await step('timeline', () => pipelined(tx, timelineRows));
- return { timelineRowsRemoved: removedSummary(removedDates) };
+ const held = await step('held', contestHeld);
+ return { timelineRowsRemoved: removedSummary(removedDates), ...(held.length ? { contested: held } : {}) };
}
// #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).
// The timeline rows are independent of the fact and take rows, so they ride in the first pipeline.
@@ -471,14 +495,18 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
() => pipelined(tx, [expireFacts, ...timelineRows])));
if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
const contested = await step('fact_trust', () => guard.finish(tx));
+ // W1 #6783 §12 (b): a fence row's field rewrite can lower a more trusted fact (the tier trigger); what was derived from it follows.
+ const above = factRows.length ? await factsAboveWriter(tx, sourceId, slug) : [];
await step('fact_fields', () => pipelined(tx, [factFields, checkTakes, dropTakes]));
- if (takes.length) {
+ if (above.length) await propagateFactLowering(tx, above);
+ if (projectedTakes.length) {
await step('takes', async () => {
- await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
+ await tx.addTakesBatch(projectedTakes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
await resolveTakes();
});
}
- return { timelineRowsRemoved: removedSummary(removedDates), ...(contested.length ? { contested } : {}) };
+ const all = [...contested, ...await step('held', contestHeld)];
+ return { timelineRowsRemoved: removedSummary(removedDates), ...(all.length ? { contested: all } : {}) };
} finally {
// #6574: a slow projection names its slow step and its row counts, so a round-trip-bound publish is visible in one line.
const elapsed = Date.now() - started;
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index 934ca3efac..3f103bc375 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -19,7 +19,13 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';
import { requestChannelTrust } from '../trust/channel.ts';
import { gateField, gateInput, heldOutcome, loadWriteGateConfig } from '../trust/gate-outcomes.ts';
import { finishOwnerAcceptedTake, ownerAcceptedTake, recordContestedTake, supersessionGuarded } from '../trust/supersede-handlers.ts';
-import { storedTrustTier } from '../trust/tier.ts';
+import { storedTrustTier, type TrustTier } from '../trust/tier.ts';
+import { contestHeldRows } from '../trust/fence-guard.ts';
+import { ownerAcceptedRemoval } from '../trust/held-removals.ts';
+import { transitionTrustProposal } from '../trust/proposals.ts';
+import { tierRaiseFix } from '../trust/confirm.ts';
+import { requestAttribution } from './attribution.ts';
+import { withWriteAttribution } from './context.ts';
import { decideTakeWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';
import { writeGateRejectedError } from '../write-gate.ts';
@@ -67,6 +73,20 @@ function fail(error: unknown): never {
: error.code === 'page_not_found' ? 'page_not_found' : 'invalid_params';
throw new OperationError(code, error.message, error.hint);
}
+/**
+ * A lower-tier takes_remove of a more trusted take: files the `forget` proposal in its own transaction (attributed to the
+ * request) and returns the refusal carrying its ref; nothing was removed. A retry reuses the proposal.
+ */
+async function takeRemovalRequiresOwner(engine: BrainEngine, row: WriteRequest, take: { id: number; tier: TrustTier; rowNum: number }, writer: TrustTier): Promise<OperationError> {
+ const [ref] = await engine.transaction(tx => withWriteAttribution(tx, requestAttribution(row), () => contestHeldRows(tx, { sourceId: row.source_id, slug: row.slug,
+ table: 'takes', proposer: 'takes_remove', writer, rows: [{ id: take.id, tier: take.tier, change: 'removed' }] })));
+ const error = opError('forget_requires_owner', `Take row #${take.rowNum} on ${row.slug} is ${take.tier}; this write cannot remove it. Proposal ${ref} asks the owner.`,
+ `Do not retry. Tell the user take row #${take.rowNum} on ${row.slug} needs their decision: they can remove it with gbrain trust confirm ${ref} on the brain host.`);
+ error.fix = tierRaiseFix(['gbrain', 'trust', 'confirm', ref!], 'Removing a take the owner confirmed or curated is their decision; the confirm prompt applies the removal.',
+ `Run on the brain host, in a terminal: gbrain trust confirm ${ref}`);
+ return error;
+}
+
export async function prepareTakesMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
try { return await prepare(engine,row,config); } catch (error) { return fail(error); }
}
@@ -102,6 +122,7 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
const trust = requestChannelTrust(row) ?? { tier: 'unknown' as const, origin: null };
let contestedOld: { id: number; tier: string } | undefined;
let acceptedProposal: { id: number; newId: number; newRow: number } | null = null;
+ let acceptedRemoval: number | null = null;
// W9F item 4: a new row number never seen on this page, fence rows (reservations included) and stored rows alike.
let allocated: number | undefined;
const nextRow = async () => nextFreeRowNum({ compiled_truth: body, timeline: '' },
@@ -126,9 +147,13 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
const citing=parsed.takes.find(t=>t.rowNum!==number && Number(t.source?.match(/superseded by #(\d+)/)?.[1])===number);
if (citing) throw takesRefusal('invalid_params',`Row #${number} replaces row #${citing.rowNum}.`,row,
`Row #${citing.rowNum} on ${row.slug} cites row #${number} as "superseded by #${number}"; remove row #${citing.rowNum} first, or keep both.`);
- const [stored]=await engine.executeRaw<{claim:string}>('SELECT claim FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,number]);
+ const [stored]=await engine.executeRaw<{id:number;claim:string;trust_tier:string}>('SELECT id,claim,trust_tier FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,number]);
if (stored && stored.claim!==target.claim) throw takesRefusal('invalid_params',`Row #${number}'s database copy disagrees with the page's takes fence; run gbrain takes rebuild ${row.slug} --source-id ${row.source_id} first.`,row,
`Rebuild the page's takes index from its fence first with gbrain takes rebuild ${row.slug} --source-id ${row.source_id}, check the row, then remove it again.`);
+ // W1 #6783 §12 (a): a lower-tier writer never removes a more trusted take; a `forget` proposal asks the owner.
+ acceptedRemoval=stored ? await ownerAcceptedRemoval(engine,row,Number(stored.id)) : null;
+ if (stored && acceptedRemoval===null && supersessionGuarded(trust.tier,stored.trust_tier)) throw await takeRemovalRequiresOwner(engine,row,
+ {id:Number(stored.id),tier:storedTrustTier(stored.trust_tier),rowNum:number},trust.tier);
removedRow=number;
next=edit.replaceFence(body,parsed.takes.filter(t=>t.rowNum!==number),[number]);
result={slug:row.slug,row_num:number,removed:true};
@@ -213,6 +238,7 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
t.rowNum===oldRow?Number(result.new_row):null));
if (batch.length) await tx.addTakesBatch(batch);
if (removedRow!==undefined) await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,removedRow]);
+ if (acceptedRemoval!==null && !await transitionTrustProposal(tx,acceptedRemoval,'pending','accepted')) throw new Error(`trust proposal tp${acceptedRemoval} is no longer pending`);
if (row.operation==='takes_resolve') {
const t=changed[0];
await tx.resolveTake(snapshot.page.id,t.rowNum,{quality:t.resolvedQuality!,outcome:t.resolvedOutcome,
diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.ts
index 4720f84631..7912b0184c 100644
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@ -176,9 +176,20 @@ export async function retractRemovedTimelineEntries(
for (const key of markdownTimelineKeys(text, slug)) produced.add(key);
for (const entry of supersededCitationTimeline(text)) superseded.add(tupleKey(entry));
}
- const orphans = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row)))
+ const found = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row)))
.map(({ detail: _detail, ...row }) => row);
- if (!orphans.length || opts.dryRun) return orphans;
+ if (!found.length) return [];
+ // W1 #6783 §12 (a): a row more trusted than the page's restatement, or held by an open contest, stays; the owner decides.
+ const [{ contestHeldRows, heldRows }, { derivedWriteTrust }, { storedTrustTier }] = await Promise.all([
+ import('./trust/fence-guard.ts'), import('./trust/taint.ts'), import('./trust/tier.ts')]);
+ const [page] = await engine.executeRaw<{ id: number; trust_tier: string | null }>('SELECT id, trust_tier FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]);
+ const writer = derivedWriteTrust({ channel: 'derive:timeline', inputs: page ? [{ table: 'pages', id: Number(page.id), tier: storedTrustTier(page.trust_tier) }] : [], projection: true }).tier;
+ const held = await heldRows(engine as BrainEngine, 'timeline_entries', found.map(row => Number(row.id)), { writer, pending: true });
+ const orphans = found.filter(row => !held.has(Number(row.id)));
+ if (opts.dryRun) return orphans;
+ await contestHeldRows(engine as BrainEngine, { sourceId, slug, table: 'timeline_entries', proposer: 'timeline_reconcile', writer,
+ rows: [...held].map(([id, tier]) => ({ id, tier, change: 'removed' as const })) });
+ if (!orphans.length) return orphans;
await engine.executeRaw(
`DELETE FROM timeline_entries WHERE id IN (SELECT jsonb_array_elements_text($1::text::jsonb)::int)`,
[JSON.stringify(orphans.map(row => row.id))]);
diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.ts
index e05c7e7091..48944b8573 100644
--- a/src/core/trust/backfill.ts
+++ b/src/core/trust/backfill.ts
@@ -41,6 +41,7 @@ import { FACTS_BACKSTOP_SOURCES } from '../facts/capture-sources.ts';
import { opError } from '../ops/contract.ts';
import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
import { withCoordinatedWrite, withTrustBackfill } from '../persistence/context.ts';
+import { propagateTierLowering } from './propagation.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
import { readManagedMode } from '../persistence/managed-mode.ts';
import { EXTRACT_ATOMS_EXTRACTOR_PREFIX, frontmatterTrustCapsSql } from './channel.ts';
@@ -389,6 +390,7 @@ export async function relowerClaimedRows(engine: BrainEngine, opts: { dryRun?: b
const managedBrain = opts.dryRun ? false : await readManagedMode(engine);
const attribution = opts.dryRun ? null : await maintenanceAttribution(engine);
const origin = JSON.stringify({ channel: 'trust_relower' });
+ const lowered: Array<{ table: TrustTable; id: number }> = [];
for (const table of BACKFILL_ORDER) {
if (!cols.table(table) || !cols.has(table, 'write_origin')) continue;
const { from, rule, src } = forTable(table);
@@ -412,11 +414,15 @@ export async function relowerClaimedRows(engine: BrainEngine, opts: { dryRun?: b
if (opts.dryRun || rows.length === 0) continue;
const ids = rows.map(r => Number(r.id));
const sources = [...new Set(rows.map(r => r.source_id))];
- const apply = (tx: BrainEngine) => withTrustBackfill(tx, () => tx.executeRaw(
+ const apply = async (tx: BrainEngine) => (await withTrustBackfill(tx, () => tx.executeRaw<{ id: number }>(
`WITH b AS (${candidates} AND x.id = ANY($2::bigint[]))
- UPDATE ${table} t SET trust_tier = b.to_tier, write_origin = $3::text::jsonb FROM b WHERE t.id = b.id`, [claimed, ids, origin]));
- await engine.transaction(tx => managedBrain ? withCoordinatedWrite(tx, sources, () => apply(tx), attribution!) : apply(tx));
+ UPDATE ${table} t SET trust_tier = b.to_tier, write_origin = $3::text::jsonb FROM b WHERE t.id = b.id RETURNING t.id`, [claimed, ids, origin])))
+ .map(row => ({ table, id: Number(row.id) }));
+ lowered.push(...await engine.transaction(tx => managedBrain ? withCoordinatedWrite(tx, sources, () => apply(tx), attribution!) : apply(tx)));
}
+ // W1 #6783 §12 (b): after every table is relowered (the dry run reports exactly these rows), what was derived from them follows.
+ if (lowered.length) await engine.transaction(tx => managedBrain
+ ? withCoordinatedWrite(tx, claimed, () => propagateTierLowering(tx, lowered), attribution!) : propagateTierLowering(tx, lowered));
return report;
}
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index ae85bd9873..28a4c37fbd 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -14,6 +14,11 @@
* - Row gate (ENG-1): every new fence row is gated like other fact writers at
* the writer's tier; a held row is not inserted (the hold keeps it), a
* flagged row records its receipt after insert.
+ * - Held removals (W1 #6783 §12 (a)): the same rule for a page's takes and
+ * timeline rows. A row more trusted than the writer is never deleted,
+ * replaced or deactivated by it; it stays as it is and a `forget` proposal
+ * asks the owner, whose accept applies the page's text to that row
+ * (trust/held-removals.ts).
*/
import type { BrainEngine, NewFact } from '../engine.ts';
import { currentWriteTrust } from '../persistence/context.ts';
@@ -22,7 +27,7 @@ import { decideFactWrite, recordFlaggedRow, recordWriteGateHold, type GatedRowDe
import { gateInput } from './gate-outcomes.ts';
import { insertTrustProposal } from './proposals.ts';
import { recordContestedFact } from './supersede-handlers.ts';
-import { compareTrust, storedTrustTier, trustRankSql, type WriteTrust } from './tier.ts';
+import { compareTrust, storedTrustTier, trustRankSql, type TrustTier, type WriteTrust } from './tier.ts';
type FenceFact = NewFact & { row_num: number };
const WRITER_RANK = trustRankSql(`COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown')`);
@@ -114,3 +119,74 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
},
};
}
+
+/** The page's live fence facts more trusted than the writer: the rows its field rewrite could lower. */
+export async function factsAboveWriter(tx: BrainEngine, sourceId: string, slug: string): Promise<Array<{ id: number; tier: TrustTier }>> {
+ return (await tx.executeRaw<{ id: number; trust_tier: string }>(`SELECT id, trust_tier FROM facts WHERE source_id = $1 AND source_markdown_slug = $2
+ AND row_num IS NOT NULL AND expired_at IS NULL AND ${trustRankSql('trust_tier')} > ${WRITER_RANK}`, [sourceId, slug]))
+ .map(r => ({ id: Number(r.id), tier: storedTrustTier(r.trust_tier) }));
+}
+
+/** What a lower-tier write would have done to a held take or timeline row. */
+export type HeldChange = 'removed' | 'replaced' | 'deactivated' | 'detail_changed';
+export type HeldTable = 'takes' | 'timeline_entries';
+export interface HeldRow { id: number; tier: TrustTier; change: HeldChange }
+
+const OPEN_CONTEST = (table: HeldTable) => `EXISTS (SELECT 1 FROM trust_proposals tp WHERE tp.status = 'pending' AND tp.action = 'forget'
+ AND tp.target_table = '${table}' AND tp.target_id = x.id)`;
+
+/**
+ * Of `ids`, the rows a write may not delete or overwrite, locked: rows more trusted than `writer` (the transaction's
+ * declared tier when omitted) and, with `pending`, rows an open contest already holds. A reconcile that restates the
+ * page text passes `pending`: the held row is absent from that text by design.
+ */
+export async function heldRows(tx: BrainEngine, table: HeldTable, ids: readonly number[], opts: { writer?: TrustTier; pending?: boolean } = {}): Promise<Map<number, TrustTier>> {
+ if (!ids.length) return new Map();
+ const writer = opts.writer ? trustRankSql('$2::text') : WRITER_RANK;
+ const rows = await tx.executeRaw<{ id: number; trust_tier: string }>(`SELECT x.id, x.trust_tier FROM ${table} x WHERE x.id = ANY($1::bigint[])
+ AND (${trustRankSql('x.trust_tier')} > ${writer}${opts.pending ? ` OR ${OPEN_CONTEST(table)}` : ''}) ORDER BY x.id FOR UPDATE`,
+ opts.writer ? [[...ids], opts.writer] : [[...ids]]);
+ return new Map(rows.map(r => [Number(r.id), storedTrustTier(r.trust_tier)]));
+}
+
+/**
+ * The page's takes a fence re-projection would delete (`gone` row numbers), replace (claim, kind or holder differ at the
+ * same row number) or deactivate, that are more trusted than the writer, locked before any of those statements run.
+ */
+export async function guardFenceTakes(tx: BrainEngine, pageId: number, incoming: ReadonlyArray<{ rowNum: number; claim: string; kind: string; holder: string; active: boolean }>,
+ gone: readonly number[], opts: { pending?: boolean } = {}): Promise<Array<HeldRow & { page_id: number; row_num: number }>> {
+ return guardTakeRows(tx, incoming.map(t => ({ page_id: pageId, row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder, active: t.active })),
+ gone.map(rowNum => ({ page_id: pageId, row_num: rowNum })), opts);
+}
+
+/** guardFenceTakes over several pages' rows at once (a reconcile batch); `pending` also holds rows an open contest holds. */
+export async function guardTakeRows(tx: BrainEngine, incoming: ReadonlyArray<{ page_id: number; row_num: number; claim: string; kind: string; holder: string; active: boolean }>,
+ gone: ReadonlyArray<{ page_id: number; row_num: number }>, opts: { pending?: boolean } = {}): Promise<Array<HeldRow & { page_id: number; row_num: number }>> {
+ if (!incoming.length && !gone.length) return [];
+ const rows = await tx.executeRaw<{ id: number; page_id: number; row_num: number; trust_tier: string; change: HeldChange }>(`SELECT x.id, x.page_id, x.row_num, x.trust_tier,
+ CASE WHEN n.row_num IS NULL THEN 'removed' WHEN (x.claim, x.kind, x.holder) IS DISTINCT FROM (n.claim, n.kind, n.holder) THEN 'replaced'
+ ELSE 'deactivated' END AS change
+ FROM takes x
+ LEFT JOIN jsonb_to_recordset($1::text::jsonb) AS n(page_id integer, row_num integer, claim text, kind text, holder text, active boolean)
+ ON n.page_id = x.page_id AND n.row_num = x.row_num
+ LEFT JOIN jsonb_to_recordset($2::text::jsonb) AS g(page_id integer, row_num integer) ON g.page_id = x.page_id AND g.row_num = x.row_num
+ WHERE x.page_id = ANY($3::integer[]) AND (${trustRankSql('x.trust_tier')} > ${WRITER_RANK}${opts.pending ? ` OR ${OPEN_CONTEST('takes')}` : ''})
+ AND (g.row_num IS NOT NULL OR (n.row_num IS NOT NULL
+ AND ((x.claim, x.kind, x.holder) IS DISTINCT FROM (n.claim, n.kind, n.holder) OR (x.active AND NOT n.active))))
+ ORDER BY x.page_id, x.row_num FOR UPDATE OF x`,
+ [JSON.stringify(incoming), JSON.stringify(gone), [...new Set([...incoming, ...gone].map(r => r.page_id))]]);
+ return rows.map(r => ({ id: Number(r.id), page_id: Number(r.page_id), row_num: Number(r.row_num), tier: storedTrustTier(r.trust_tier), change: r.change }));
+}
+
+/** Files the owner's `forget` proposal for each held row (an open one is reused); returns their tp refs. */
+export async function contestHeldRows(tx: BrainEngine, input: { sourceId: string; slug: string; table: HeldTable; proposer: string; writer?: TrustTier; rows: readonly HeldRow[] }): Promise<string[]> {
+ if (!input.rows.length) return [];
+ const writer = input.writer ?? (await currentWriteTrust(tx))?.tier ?? 'unknown';
+ const refs: string[] = [];
+ for (const row of input.rows) {
+ const { id } = await insertTrustProposal(tx, { action: 'forget', sourceId: input.sourceId, target: { table: input.table, id: row.id }, proposer: input.proposer,
+ before: { guard: input.proposer, change: row.change, row: { id: row.id, tier: row.tier }, writer_tier: writer, slug: input.slug } });
+ refs.push(`tp${id}`);
+ }
+ return refs;
+}
diff --git a/src/core/trust/held-removals.ts b/src/core/trust/held-removals.ts
new file mode 100644
index 0000000000..2892359489
--- /dev/null
+++ b/src/core/trust/held-removals.ts
@@ -0,0 +1,90 @@
+/**
+ * The owner's decision on a held take or timeline row (W1 #6783 §12 (a)).
+ *
+ * A lower-tier write never deletes, replaces or deactivates a take or timeline
+ * row more trusted than it (trust/fence-guard.ts): the row stays and a `forget`
+ * proposal targets it. Accepting applies what the write asked for:
+ * - a take the page's fence still carries with the same claim (a refused
+ * `takes_remove`) is removed by an owner `takes_remove` bound to the
+ * proposal by a one-time nonce, so the fence and the index change together;
+ * - otherwise the page's current text rules that row: the fence row at its
+ * number (or the timeline entry with its date, source and summary) replaces
+ * it at the writer's tier, and when the page no longer carries one the row
+ * is deleted.
+ * Dismissing keeps the row (the default reject).
+ */
+import type { BrainEngine } from '../engine.ts';
+import { parseTakesFence } from '../takes-fence.ts';
+import { takesPreparation } from '../takes-write.ts';
+import { maintenanceAttribution, principalAttribution } from '../persistence/attribution.ts';
+import { withCoordinatedWrite, withWriteAttribution, withWriteTrust } from '../persistence/context.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { queuePageProjection } from '../page-state/projections.ts';
+import { reprojectTimelineRow } from '../persistence/canonical-projections.ts';
+import { decisionResult, getTrustProposal, transitionTrustProposal, type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
+import { storedTrustTier } from './tier.ts';
+
+interface HeldPageRow { id: number; page_id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }
+
+async function heldRow(engine: BrainEngine, table: string, id: number): Promise<(HeldPageRow & Record<string, unknown>) | undefined> {
+ const columns = table === 'takes' ? 'x.row_num, x.claim' : 'x.date::text AS date, x.source, x.summary';
+ const [row] = await engine.executeRaw<HeldPageRow & Record<string, unknown>>(`SELECT x.id, x.page_id, ${columns}, p.source_id, p.slug, p.compiled_truth, p.timeline
+ FROM ${table === 'takes' ? 'takes' : 'timeline_entries'} x JOIN pages p ON p.id = x.page_id WHERE x.id = $1`, [id]);
+ return row;
+}
+
+/** A refused `takes_remove` the owner accepted: its intent carries the proposal id and the nonce stored on it. */
+export async function ownerAcceptedRemoval(engine: BrainEngine, row: { authority: { remote: boolean }; intent: Record<string, unknown> | null }, takeId: number): Promise<number | null> {
+ const id = Number(row.intent?.trust_accept);
+ const nonce = row.intent?.trust_accept_nonce;
+ if (row.authority.remote !== false || !Number.isSafeInteger(id) || typeof nonce !== 'string') return null;
+ const proposal = await getTrustProposal(engine, id);
+ return proposal && proposal.status === 'pending' && proposal.action === 'forget' && proposal.target_table === 'takes'
+ && proposal.target_id === takeId && proposal.after_state.accept_nonce === nonce ? id : null;
+}
+
+export async function acceptHeldRemoval(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult> {
+ const table = proposal.target_table;
+ const row = await heldRow(engine, table, proposal.target_id);
+ if (!row) {
+ await transitionTrustProposal(engine, proposal.id, 'pending', 'superseded', { decidedBy: ctx.decidedBy });
+ return decisionResult(proposal, 'accept', 'superseded', { reason: 'row_missing' });
+ }
+ const body = { compiled_truth: row.compiled_truth, timeline: row.timeline ?? '' };
+ const fenceRow = table === 'takes' ? parseTakesFence(`${row.compiled_truth}\n${row.timeline ?? ''}`).takes.find(t => t.rowNum === Number(row.row_num)) : undefined;
+ if (fenceRow && fenceRow.claim === row.claim) {
+ const nonce = crypto.randomUUID();
+ await engine.executeRaw(`UPDATE trust_proposals SET after_state = after_state || jsonb_build_object('accept_nonce', $2::text) WHERE id = $1 AND status = 'pending'`, [proposal.id, nonce]);
+ const { submitPageMutation } = await import('../persistence/page-mutations.ts');
+ const local = { engine, sourceId: row.source_id, remote: false as const, dryRun: false,
+ config: ctx.config ?? ({ engine: engine.kind } as never), logger: { info() {}, warn() {}, error() {} } };
+ await submitPageMutation(local as never, { operation: 'takes_remove', params: { slug: row.slug, source_id: row.source_id, row_num: Number(row.row_num),
+ trust_accept: proposal.id, trust_accept_nonce: nonce, request_id: crypto.randomUUID() } });
+ const after = await getTrustProposal(engine, proposal.id);
+ return after?.status === 'accepted' ? decisionResult(proposal, 'accept', 'accepted')
+ : decisionResult(proposal, 'accept', 'refused', { reason: after?.status ?? 'not_found' });
+ }
+ const writer = { tier: storedTrustTier(proposal.before_state.writer_tier), origin: { channel: `trust_accept:${proposal.proposer}` } };
+ const attribution = ctx.decidedBy ? principalAttribution(ctx.decidedBy) : await maintenanceAttribution(engine);
+ const managed = await managedPersistenceEnabled(engine);
+ const applied = await engine.transaction(async tx => {
+ const run = async () => {
+ await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);
+ if (!await transitionTrustProposal(tx, proposal.id, 'pending', 'accepted', { decidedBy: ctx.decidedBy })) return false;
+ await withWriteTrust(tx, writer, async () => {
+ if (table === 'takes') {
+ if (fenceRow) await tx.addTakesBatch([takesPreparation.toCanonicalBatchInput(row.page_id, fenceRow)]);
+ else await tx.executeRaw('DELETE FROM takes WHERE id = $1', [row.id]);
+ } else {
+ await tx.executeRaw('DELETE FROM timeline_entries WHERE id = $1', [row.id]);
+ await reprojectTimelineRow(tx, row.page_id, body, row.slug, { date: String(row.date), source: row.source as string | null, summary: String(row.summary) });
+ }
+ });
+ await queuePageProjection(tx, row.source_id, row.slug, 'trust_tier_changed');
+ return true;
+ };
+ return managed ? withCoordinatedWrite(tx, [row.source_id], run, attribution) : withWriteAttribution(tx, attribution, run);
+ });
+ return applied ? decisionResult(proposal, 'accept', 'accepted', { detail: { [table === 'takes' ? 'take_id' : 'timeline_entry_id']: String(row.id) } })
+ : decisionResult(proposal, 'accept', 'refused', { reason: (await getTrustProposal(engine, proposal.id))?.status ?? 'not_found' });
+}
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index 69c5279e8b..bd5838d1c9 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -42,7 +42,8 @@ import {
decisionResult, registerTrustProposalHandler, transitionTrustProposal, type TrustProposalAction,
type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow,
} from './proposals.ts';
-import { effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
+import { compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
+import { propagateTierLowering } from './propagation.ts';
/** The journaled operation that publishes an owner page action on a managed brain. */
export const TRUST_OWNER_PAGE_OPERATION = 'trust_owner_page';
@@ -130,6 +131,7 @@ export async function setRowTier(engine: BrainEngine, input: {
return engine.transaction(async tx => {
const run = async () => {
if (input.expect && !(await input.expect(tx))) return false;
+ const [prior] = await tx.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM ${input.table} WHERE id = $1`, [input.id]);
const update = () => tx.executeRaw<{ id: number }>(
`UPDATE ${input.table} SET trust_tier = $2,
write_origin = COALESCE(write_origin, '{}'::jsonb) || jsonb_build_object('owner_decision', $3::text::jsonb)
@@ -137,6 +139,8 @@ export async function setRowTier(engine: BrainEngine, input: {
const rows = input.ceiling ? await withTrustPromotion(tx, input.ceiling, update) : await update();
if (rows.length !== 1) return false;
await queueTierProjection(tx, input.table, input.id);
+ // W1 #6783 §12 (b): a lowering reaches what was derived from the row; a raise never does.
+ if (prior && compareTrust(input.tier, storedTrustTier(prior.trust_tier)) < 0) await propagateTierLowering(tx, [{ table: input.table, id: input.id }]);
await input.also?.(tx);
return true;
};
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index 8bf40fb58b..c8c72b6660 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -24,6 +24,7 @@ import type { WriteRequest } from '../persistence/model.ts';
import { frontmatterTrustCaps, requestChannelTrust, stampTrustMarker } from './channel.ts';
import { declaredWriteTrust, readDerivationDeclaration } from './taint.ts';
import { insertTrustProposal, updatePendingTrustProposalAfter } from './proposals.ts';
+import { propagateTierLowering } from './propagation.ts';
import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
/** Page writes that only edit a gbrain-managed fence (or strike a row) and keep the page's tier. */
@@ -95,6 +96,8 @@ export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRe
await updatePendingTrustProposalAfter(tx, Number(pending.id), after);
return { proposal_ref: `tp${pending.id}` };
}
+ // W1 #6783 §12 (b): rows derived from the page follow it down.
+ await propagateTierLowering(tx, [{ table: 'pages', id: pageId }]);
const [version] = await tx.executeRaw<{ id: number }>(
'SELECT id FROM page_versions WHERE page_id = $1 AND trust_tier = $2 ORDER BY id DESC LIMIT 1', [pageId, prior.tier]);
const proposal = await insertTrustProposal(tx, {
diff --git a/src/core/trust/propagation.ts b/src/core/trust/propagation.ts
new file mode 100644
index 0000000000..57158319d9
--- /dev/null
+++ b/src/core/trust/propagation.ts
@@ -0,0 +1,84 @@
+/**
+ * Derived-tier propagation (W1 #6783 §12 (b)). A derived row is stamped at
+ * derivation time with the least trusted of its inputs, capped
+ * (trust/taint.ts derivedWriteTrust). When an input is later lowered, each
+ * row derived from it, transitively through `derivation_inputs`, is lowered to
+ * the least trusted of its current inputs when that is below its own tier.
+ * A raise never propagates: promoting a derivative needs its own
+ * recomputation under the owner-promotion policy. Recorded tiers stay as they
+ * were (page_versions snapshots, trust proposals); the lowered row's
+ * `write_origin.input_lowered` names the tier it had.
+ *
+ * The walk has purge's bound (derivedRowsFrom: 1,000 rows, eight hops). On a
+ * managed brain the lowering writes only rows of sources the enclosing
+ * coordinated write holds; a dependent in another source is marked
+ * `needs_rederive` (reason `input_lowered`) instead.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { derivedRowsFrom, type DerivationRef } from '../facts/derivation-inputs.ts';
+import { compareTrust, storedTrustTier, trustRankSql, trustTierFromRankSql, type TrustTier } from './tier.ts';
+
+const TIERED = ['facts', 'takes', 'pages', 'timeline_entries'] as const;
+type Tiered = typeof TIERED[number];
+export interface LoweredRow { table: Tiered; id: number; from: TrustTier; to: TrustTier }
+
+const numericId = (column: string) => `(CASE WHEN ${column} ~ '^[0-9]+$' THEN ${column}::bigint END)`;
+const sourceOf = (table: Tiered) => table === 'facts' || table === 'pages' ? 'x.source_id' : '(SELECT p.source_id FROM pages p WHERE p.id = x.page_id)';
+const WRITABLE = (source: string) => `(NOT EXISTS (SELECT 1 FROM persistence_brain WHERE singleton = 1 AND enabled)
+ OR COALESCE(NULLIF(current_setting('gbrain.write_sources', true), ''), '[]')::jsonb ? ${source})`;
+const INPUT_TIER = 'COALESCE(f.trust_tier, k.trust_tier, p.trust_tier, t.trust_tier)';
+
+/** Each derived row of `table` among `ids` whose current inputs are less trusted than it: the tier it lowers to. */
+async function lowerable(tx: BrainEngine, table: Tiered, ids: readonly string[]) {
+ return tx.executeRaw<{ id: number; source_id: string | null; from_tier: string; to_tier: string; writable: boolean }>(`WITH low AS (
+ SELECT di.derived_id, min(${trustRankSql(INPUT_TIER)}) AS r FROM derivation_inputs di
+ LEFT JOIN facts f ON di.input_table = 'facts' AND f.id = ${numericId('di.input_id')}
+ LEFT JOIN takes k ON di.input_table = 'takes' AND k.id = ${numericId('di.input_id')}
+ LEFT JOIN pages p ON di.input_table = 'pages' AND p.id = ${numericId('di.input_id')}
+ LEFT JOIN timeline_entries t ON di.input_table = 'timeline_entries' AND t.id = ${numericId('di.input_id')}
+ WHERE di.derived_table = $1 AND di.derived_id = ANY($2::text[]) AND ${INPUT_TIER} IS NOT NULL
+ GROUP BY di.derived_id)
+ SELECT x.id, ${sourceOf(table)} AS source_id, x.trust_tier AS from_tier, ${trustTierFromRankSql('low.r')} AS to_tier, ${WRITABLE(sourceOf(table))} AS writable
+ FROM low JOIN ${table} x ON x.id = ${numericId('low.derived_id')} WHERE low.r < ${trustRankSql('x.trust_tier')}
+ ORDER BY x.id FOR UPDATE OF x`, [table, [...ids]]);
+}
+
+/** Of `before` (fact ids and their tiers before a write), the facts the write lowered, propagated. */
+export async function propagateFactLowering(tx: BrainEngine, before: ReadonlyArray<{ id: number; tier: TrustTier }>): Promise<LoweredRow[]> {
+ const prior = new Map(before.map(f => [f.id, f.tier]));
+ const now = await tx.executeRaw<{ id: number; trust_tier: string }>('SELECT id, trust_tier FROM facts WHERE id = ANY($1::bigint[])', [[...prior.keys()]]);
+ const lowered = now.filter(f => compareTrust(storedTrustTier(f.trust_tier), prior.get(Number(f.id)) ?? 'unknown') < 0);
+ return propagateTierLowering(tx, lowered.map(f => ({ table: 'facts', id: Number(f.id) })));
+}
+
+/** Lowers every row derived from `inputs` (already lowered) that is now more trusted than its least trusted input. */
+export async function propagateTierLowering(tx: BrainEngine, inputs: readonly DerivationRef[]): Promise<LoweredRow[]> {
+ if (!inputs.length) return [];
+ const { rows } = await derivedRowsFrom(tx, inputs);
+ const lowered: LoweredRow[] = [];
+ const deferred: Array<{ table: string; id: string; source_id: string | null }> = [];
+ for (const depth of [...new Set(rows.map(r => r.depth))].sort((a, b) => a - b)) {
+ for (const table of TIERED) {
+ const ids = rows.filter(r => r.depth === depth && r.table === table).map(r => r.id);
+ if (!ids.length) continue;
+ const candidates = await lowerable(tx, table, ids);
+ const writable = candidates.filter(c => c.writable);
+ deferred.push(...candidates.filter(c => !c.writable).map(c => ({ table, id: String(c.id), source_id: c.source_id })));
+ if (!writable.length) continue;
+ await tx.executeRaw(`UPDATE ${table} x SET trust_tier = c.to_tier,
+ write_origin = COALESCE(x.write_origin, '{}'::jsonb) || jsonb_build_object('input_lowered', jsonb_build_object('from', c.from_tier, 'at', now()::text))
+ FROM jsonb_to_recordset($1::text::jsonb) AS c(id bigint, from_tier text, to_tier text) WHERE x.id = c.id`,
+ [JSON.stringify(writable.map(c => ({ id: Number(c.id), from_tier: c.from_tier, to_tier: c.to_tier })))]);
+ lowered.push(...writable.map(c => ({ table, id: Number(c.id), from: storedTrustTier(c.from_tier), to: storedTrustTier(c.to_tier) })));
+ }
+ }
+ if (deferred.length) {
+ await tx.executeRaw(`INSERT INTO needs_rederive(derived_table, derived_id, source_id, reason)
+ SELECT d.derived_table, d.derived_id, d.source_id, 'input_lowered' FROM jsonb_to_recordset($1::text::jsonb) AS d(derived_table text, derived_id text, source_id text)
+ ON CONFLICT (derived_table, derived_id) DO UPDATE SET reason = EXCLUDED.reason, marked_at = now()`,
+ [JSON.stringify(deferred.map(d => ({ derived_table: d.table, derived_id: d.id, source_id: d.source_id })))]);
+ }
+ const { queueTierProjection } = await import('./page-write.ts');
+ for (const row of lowered) if (row.table !== 'timeline_entries') await queueTierProjection(tx, row.table, row.id);
+ return lowered;
+}
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index 18bf6573db..486111b9ff 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -25,6 +25,7 @@ import {
} from './proposals.ts';
import { tierRaiseFix } from './confirm.ts';
import { queueTierProjection } from './page-write.ts';
+import { propagateTierLowering } from './propagation.ts';
import { compareTrust, effectiveWriteTrust, storedTrustTier, trustRankSql, type TrustTier, type WriteTrust } from './tier.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
@@ -189,6 +190,8 @@ export const TRUST_PAIR_STORE: PairProposalStore = {
const prior = storedTrustTier((row?.before_state.new as { tier?: unknown } | undefined)?.tier);
await tx.executeRaw(`UPDATE facts SET trust_tier = $3 WHERE id = $1 AND source_id = $2`, [proposal.new_fact_id, proposal.source_id, prior]);
for (const id of [proposal.old_fact_id, proposal.new_fact_id]) await queueTierProjection(tx, 'facts', id);
+ // W1 #6783 §12 (b): what was derived from the confirmed row while it was confirmed follows it back down.
+ await propagateTierLowering(tx, [{ table: 'facts', id: proposal.new_fact_id }]);
},
};
@@ -285,9 +288,13 @@ registerTrustProposalHandler('supersede_take', {
},
});
-/** The owner applies the forget a remote caller asked for, as a trusted local forget. */
+/** The owner applies the forget a remote caller asked for, as a trusted local forget; a held take or timeline row takes the page's text (trust/held-removals.ts). */
registerTrustProposalHandler('forget', {
async accept(engine, proposal, ctx: TrustDecisionContext) {
+ if (proposal.target_table !== 'facts') {
+ const { acceptHeldRemoval } = await import('./held-removals.ts');
+ return acceptHeldRemoval(engine, proposal, ctx);
+ }
const { submitForgetMutation } = await import('../persistence/memory-mutations.ts');
const local = { engine, sourceId: proposal.source_id, remote: false as const, dryRun: false,
config: ctx.config ?? ({ engine: engine.kind } as never), logger: { info() {}, warn() {}, error() {} } };
diff --git a/src/core/trust/taint.ts b/src/core/trust/taint.ts
index 391df55070..0f0abcc85f 100644
--- a/src/core/trust/taint.ts
+++ b/src/core/trust/taint.ts
@@ -22,6 +22,7 @@ import {
} from './tier.ts';
import { frontmatterTrustCaps } from './channel.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { propagateTierLowering } from './propagation.ts';
/** A row placed in a model's context: by id, or a page by its (source, slug) coordinate. */
export type TaintRef = { table: TaintTable; id: number } | { table: 'pages'; sourceId: string; slug: string };
@@ -126,7 +127,10 @@ export async function lowerToDerivedTier(tx: Sql, table: TaintTable, ids: readon
`UPDATE ${table} SET trust_tier=$2,write_origin=$3::text::jsonb
WHERE id=ANY($1::bigint[]) AND ${trustRankSql('trust_tier')}>${trustRankSql('$2::text')} RETURNING id`,
[[...ids], trust.tier, trust.origin ? JSON.stringify(trust.origin) : null]);
- return rows.map(row => Number(row.id));
+ const lowered = rows.map(row => Number(row.id));
+ // W1 #6783 §12 (b): what was derived from a lowered row follows it down.
+ if (lowered.length) await propagateTierLowering(tx as BrainEngine, lowered.map(id => ({ table, id })));
+ return lowered;
}
/** A row a derivation wrote, for the lowering and edge pass. */
diff --git a/test/canonical-projection-history.test.ts b/test/canonical-projection-history.test.ts
index c27fb1e1e5..e1ec78a810 100644
--- a/test/canonical-projection-history.test.ts
+++ b/test/canonical-projection-history.test.ts
@@ -10,6 +10,8 @@ import { parseMarkdown } from '../src/core/markdown.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+/** A publication declares its writer's tier (the coordinator does); the timeline rows these put_page fixtures project are agent_written. */
+const AGENT_PUBLICATION = { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'agent_written' as const, origin: null } };
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
@@ -182,7 +184,7 @@ describe('#5567 coordinated writes keep database-only timeline history', () => {
await f.legacyTimeline(slug, legacy);
const snapshot = await f.engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true });
const project = await prepareCanonicalProjections(f.engine, parseMarkdown(page(`Next for ${writer}.`), slug), slug, f.sourceId, snapshot, writer);
- await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), TEST_WRITE_ATTRIBUTION));
+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), AGENT_PUBLICATION));
expect(await f.timeline(slug)).toEqual([legacy]);
await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(
'DELETE FROM timeline_entries WHERE page_id=$1', [snapshot!.page.id]), TEST_WRITE_ATTRIBUTION));
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 453df02aff..b056923c74 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -182,6 +182,7 @@ test/takes-vector-lifecycle-5885.serial.test.ts
test/terminal-failures-6650.test.ts
test/trust-channel-writes.test.ts
test/trust-guarded-supersession.test.ts
+test/trust-held-removals.test.ts
test/trust-owner-actions.test.ts
test/unbound-source-6536.test.ts
test/withdrawal-overlay-concurrency.test.ts
diff --git a/test/takes-reservation-callers.test.ts b/test/takes-reservation-callers.test.ts
index d5f0167b10..e74382ab35 100644
--- a/test/takes-reservation-callers.test.ts
+++ b/test/takes-reservation-callers.test.ts
@@ -24,6 +24,7 @@ const REVIEWED: Record<string, string> = {
'src/core/repair/connector-fences.ts': 'moves fence blocks verbatim, reservations included',
'src/core/repair/take-supersession.ts': 're-renders through replaceFence, which keeps the reservations of the body it replaces',
'src/core/shared-skills/migration-projection.ts': 'compares stored takes with fence takes; neither holds a reservation',
+ 'src/core/trust/held-removals.ts': 'looks up the live fence row at a held take\'s number; a reserved number has no take, so the accept deletes the held row',
'src/core/takes-write.ts': 'replaceFence, upsertTakeRow and supersedeRow keep reservations; round-trip checks count takes only',
};
diff --git a/test/timeline-materialize.test.ts b/test/timeline-materialize.test.ts
index b6dcdb96fc..b350e27e60 100644
--- a/test/timeline-materialize.test.ts
+++ b/test/timeline-materialize.test.ts
@@ -15,6 +15,8 @@ import { importFromContent } from '../src/core/import-file.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+/** A publication declares its writer's tier (the coordinator does); the timeline rows these put_page fixtures project are agent_written. */
+const AGENT_PUBLICATION = { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'agent_written' as const, origin: null } };
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { materializeTimeline, prepareCanonicalProjections, renderMaterializedBullet, type ProjectionWriter } from '../src/core/persistence/canonical-projections.ts';
@@ -273,7 +275,7 @@ describe('#5567 per-writer classes for marked rows', () => {
const carried = await materializeTimeline(f.engine, next, slug, prior, writer);
expect(carried.materialized).toBe(renders ? 1 : 0);
const project = await prepareCanonicalProjections(f.engine, { ...next, timeline: carried.timeline }, slug, f.sourceId, prior, writer);
- await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), TEST_WRITE_ATTRIBUTION));
+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx), AGENT_PUBLICATION));
expect(await f.timeline(slug)).toEqual(keeps ? [normalized] : []);
});
});
diff --git a/test/timeline-regenerated-writers.test.ts b/test/timeline-regenerated-writers.test.ts
index 8543fd2ac6..19116da4c8 100644
--- a/test/timeline-regenerated-writers.test.ts
+++ b/test/timeline-regenerated-writers.test.ts
@@ -57,8 +57,14 @@ for (const writer of writers) {
const after = (await engine.readPageSnapshot(writer.slug, { sourceId }))!;
expect(after.page.compiled_truth).toContain('Generated body v2');
const rows = await engine.getTimeline(writer.slug, { sourceId });
- expect(rows.some(row => row.summary === 'User note added by hand')).toBe(writer.regenerated);
expect(after.page.timeline.includes('User note added by hand')).toBe(writer.regenerated);
+ // W1 #6783 §12 (a): on an ordinary page the republish (stamped `unknown`, no derivation declared) drops the bullet from
+ // the text, but it may not delete the more trusted agent-written row: the row is held for the owner's decision.
+ expect(rows.some(row => row.summary === 'User note added by hand')).toBe(true);
+ const held = await engine.executeRaw<{ change: string }>(`SELECT tp.before_state->>'change' AS change FROM trust_proposals tp
+ JOIN timeline_entries t ON tp.target_table = 'timeline_entries' AND tp.target_id = t.id JOIN pages p ON p.id = t.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 AND tp.status = 'pending' AND tp.action = 'forget'`, [sourceId, writer.slug]);
+ expect(held.map(h => h.change)).toEqual(writer.regenerated ? [] : ['removed']);
}), 60_000);
}
diff --git a/test/trust-held-removals.test.ts b/test/trust-held-removals.test.ts
new file mode 100644
index 0000000000..696a8bc8e7
--- /dev/null
+++ b/test/trust-held-removals.test.ts
@@ -0,0 +1,232 @@
+/**
+ * W1 prerequisites (#6783 §12 (a) and (b)), on PGLite and, with DATABASE_URL,
+ * on Postgres.
+ *
+ * (a) A lower-tier write never deletes, replaces or deactivates a take or
+ * timeline row more trusted than it: a remote put_page that drops or rewrites
+ * a confirmed take, or drops a confirmed timeline row, keeps the row and files
+ * a `forget` proposal; a remote takes_remove of a confirmed take is
+ * forget_requires_owner; the takes reconcile never prunes a held row. The
+ * owner's accept applies the write.
+ *
+ * (b) Lowering an input lowers what was derived from it (an agent page edit,
+ * an owner tier change); raising it never promotes the derivative.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import type { Principal } from '../src/core/persistence/model.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withCoordinatedWrite, withTrustBackfill, withTrustPromotion } from '../src/core/persistence/context.ts';
+import { listTrustProposals } from '../src/core/trust/proposals.ts';
+import { decideTrustProposal } from '../src/core/trust/decide.ts';
+import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';
+import { setRowTier } from '../src/core/trust/page-handlers.ts';
+import { extractTakesFromDb } from '../src/core/cycle/extract-takes.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const engines: BrainEngine[] = [];
+const home = mkdtempSync(join(tmpdir(), 'gbrain-held-removals-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const quiet = { info() {}, warn() {}, error() {} };
+const owner = { confirmation: { via: 'tty' as const } };
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}), 120_000);
+afterAll(async () => {
+ resetGateway();
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+interface Brain { engine: BrainEngine; sourceId: string; remote: OperationContext; local: OperationContext }
+async function brain(engine: BrainEngine): Promise<Brain> {
+ const sourceId = `held-${randomUUID().slice(0, 8)}`;
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };
+ await readLocalWriter(engine, 'cli');
+ return {
+ engine, sourceId,
+ remote: { ...base, remote: true, transport: 'http', takesHoldersAllowList: ['world'],
+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id } as Principal, sourceId, allowedSources: [sourceId], scopes: ['read', 'write'] } },
+ local: { ...base, remote: false },
+ } as Brain;
+}
+const run = (ctx: OperationContext, op: string, params: Record<string, unknown>) =>
+ operationsByName[op].handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, any>>;
+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;
+const coordinated = (b: Brain, fn: (tx: BrainEngine) => Promise<unknown>) =>
+ b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+/** The owner confirms a row (CEO-9), through the promotion seam. */
+const confirm = (b: Brain, table: 'takes' | 'timeline_entries' | 'facts', id: number) =>
+ coordinated(b, tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(`UPDATE ${table} SET trust_tier='user_confirmed' WHERE id=$1`, [id])));
+/** A row classified operator_curated through the deterministic backfill seam (CEO-10). */
+const curate = (b: Brain, table: 'pages' | 'facts', id: number) => coordinated(b, async tx => {
+ await tx.executeRaw(`UPDATE ${table} SET trust_tier='unknown' WHERE id=$1`, [id]);
+ await withTrustBackfill(tx, () => tx.executeRaw(`UPDATE ${table} SET trust_tier='operator_curated' WHERE id=$1`, [id]));
+});
+const pageId = async (b: Brain, slug: string) => Number((await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]))[0]!.id);
+const takesOf = async (b: Brain, slug: string) => b.engine.executeRaw<{ id: number; row_num: number; claim: string; active: boolean; trust_tier: string }>(
+ 'SELECT id::int AS id, row_num, claim, active, trust_tier FROM takes WHERE page_id=$1 ORDER BY row_num', [await pageId(b, slug)]);
+const remoteContent = async (b: Brain, slug: string) => operationsByName.get_page.handler(b.remote, { slug, include_content: true }) as Promise<Record<string, any>>;
+/** A local agent's read: remote readers never see the takes fence (and a remote put_page merges it back), so a fence rewrite is a local agent write. */
+const localContent = async (b: Brain, slug: string) => operationsByName.get_page.handler(b.local, { slug, include_content: true }) as Promise<Record<string, any>>;
+const proposalsFor = async (b: Brain, table: string, id: number) => (await listTrustProposals(b.engine, { sourceId: b.sourceId }))
+ .filter(p => p.target_table === table && p.target_id === id);
+
+describe('held removals (W1 #6783 §12 (a))', () => {
+ test('an agent put_page that drops or rewrites a confirmed take keeps it with a forget proposal; the owner accept applies the page', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ const slug = 'people/gina-example';
+ await run(b.local, 'put_page', { slug, content: page('Gina', 'Gina.') });
+ for (const claim of ['Gina will join acme-example', 'Gina moves to Lisbon', 'Gina ships the beta']) {
+ await run(b.local, 'takes_add', { slug, claim, kind: 'bet', holder: 'world', weight: 0.6 });
+ }
+ const before = await takesOf(b, slug);
+ for (const take of before.slice(0, 2)) await confirm(b, 'takes', take.id);
+ const current = await localContent(b, slug);
+ // Row 1 removed, row 2's claim rewritten in place, row 3 (agent_written, like the writer) removed.
+ const edited = String(current.content).split('\n').filter(line => !line.includes('Gina will join acme-example') && !line.includes('Gina ships the beta'))
+ .join('\n').replace('Gina moves to Lisbon', 'Gina moves to Porto');
+ const put = await run(b.local, 'put_page', { slug, content: edited, expected_revision: current.revision });
+ expect(put.contested?.proposal_refs).toHaveLength(2);
+ const after = await takesOf(b, slug);
+ expect(after.find(t => t.id === before[0]!.id)).toMatchObject({ claim: 'Gina will join acme-example', active: true, trust_tier: 'user_confirmed' });
+ expect(after.find(t => t.id === before[1]!.id)).toMatchObject({ claim: 'Gina moves to Lisbon', active: true, trust_tier: 'user_confirmed' });
+ expect(after.some(t => t.id === before[2]!.id)).toBe(false);
+ const [removed] = await proposalsFor(b, 'takes', before[0]!.id);
+ const [replaced] = await proposalsFor(b, 'takes', before[1]!.id);
+ expect(removed).toMatchObject({ action: 'forget', status: 'pending', proposer: 'fence_projection' });
+ expect(removed!.before_state).toMatchObject({ change: 'removed', writer_tier: 'agent_written', row: { tier: 'user_confirmed' } });
+ expect(replaced!.before_state).toMatchObject({ change: 'replaced' });
+ // A republish of the same text files nothing new.
+ const again = await localContent(b, slug);
+ await run(b.local, 'put_page', { slug, content: `${String(again.content)}\nMore.`, expected_revision: again.revision });
+ expect((await listTrustProposals(engine, { sourceId: b.sourceId })).length).toBe(2);
+ expect((await decideTrustProposal(engine, removed!.id, 'accept', owner)).status).toBe('accepted');
+ expect((await decideTrustProposal(engine, replaced!.id, 'accept', owner)).status).toBe('accepted');
+ const settled = await takesOf(b, slug);
+ expect(settled.some(t => t.claim === 'Gina will join acme-example')).toBe(false);
+ expect(settled.find(t => t.row_num === before[1]!.row_num)).toMatchObject({ claim: 'Gina moves to Porto', trust_tier: 'agent_written' });
+ }
+ }), 120_000);
+
+ test('a remote put_page that drops a confirmed timeline row keeps it with a forget proposal; the owner accept deletes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ const slug = 'people/hana-example';
+ await run(b.local, 'put_page', { slug, content: page('Hana', 'Hana.\n\n## Timeline\n\n- **2026-01-05** | note — Hana joined acme-example\n- **2026-02-07** | note — Hana moved to Kyoto') });
+ const rows = await engine.executeRaw<{ id: number; summary: string }>('SELECT id::int AS id, summary FROM timeline_entries WHERE page_id=$1 ORDER BY date', [await pageId(b, slug)]);
+ expect(rows).toHaveLength(2);
+ await confirm(b, 'timeline_entries', rows[0]!.id);
+ const current = await remoteContent(b, slug);
+ const edited = String(current.content).split('\n').filter(line => !line.includes('Hana joined') && !line.includes('Hana moved')).join('\n');
+ const put = await run(b.remote, 'put_page', { slug, content: edited, expected_revision: current.revision });
+ expect(put.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ const kept = await engine.executeRaw<{ id: number; trust_tier: string }>('SELECT id::int AS id, trust_tier FROM timeline_entries WHERE page_id=$1', [await pageId(b, slug)]);
+ expect(kept).toEqual([{ id: rows[0]!.id, trust_tier: 'user_confirmed' }]);
+ const [proposal] = await proposalsFor(b, 'timeline_entries', rows[0]!.id);
+ expect(proposal).toMatchObject({ action: 'forget', status: 'pending' });
+ expect(proposal!.before_state).toMatchObject({ change: 'removed', writer_tier: 'agent_written' });
+ expect((await decideTrustProposal(engine, proposal!.id, 'accept', owner)).status).toBe('accepted');
+ expect(await engine.executeRaw('SELECT id FROM timeline_entries WHERE page_id=$1', [await pageId(b, slug)])).toHaveLength(0);
+ }
+ }), 120_000);
+
+ test('a remote takes_remove of a confirmed take is forget_requires_owner with one proposal; the owner accept removes it from the fence and index', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ const slug = 'people/ivan-example';
+ await run(b.local, 'put_page', { slug, content: page('Ivan', 'Ivan.') });
+ const added = await run(b.local, 'takes_add', { slug, claim: 'Ivan will run the marathon', kind: 'bet', holder: 'world', weight: 0.5 });
+ const [take] = await takesOf(b, slug);
+ await confirm(b, 'takes', take!.id);
+ let refused: any;
+ for (let i = 0; i < 2; i++) {
+ refused = await run(b.remote, 'takes_remove', { slug, row_num: added.row_num }).then(() => null, (error: unknown) => error);
+ expect(refused?.code).toBe('forget_requires_owner');
+ }
+ expect((await takesOf(b, slug))[0]).toMatchObject({ id: take!.id, active: true });
+ const proposals = await proposalsFor(b, 'takes', take!.id);
+ expect(proposals).toHaveLength(1);
+ expect(proposals[0]).toMatchObject({ action: 'forget', proposer: 'takes_remove' });
+ expect((await decideTrustProposal(engine, proposals[0]!.id, 'accept', owner)).status).toBe('accepted');
+ expect(await takesOf(b, slug)).toHaveLength(0);
+ expect(String((await remoteContent(b, slug)).content)).not.toContain('Ivan will run the marathon');
+ }
+ }), 120_000);
+
+ test('the takes reconcile never prunes or overwrites a held take', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ const slug = 'people/jun-example';
+ await run(b.local, 'put_page', { slug, content: page('Jun', 'Jun.') });
+ await run(b.local, 'takes_add', { slug, claim: 'Jun will found a company', kind: 'bet', holder: 'world', weight: 0.5 });
+ await run(b.local, 'takes_add', { slug, claim: 'Jun prefers Go', kind: 'take', holder: 'world', weight: 0.5 });
+ const before = await takesOf(b, slug);
+ for (const take of before) await confirm(b, 'takes', take.id);
+ const current = await localContent(b, slug);
+ const edited = String(current.content).split('\n').filter(line => !line.includes('Jun will found a company')).join('\n').replace('Jun prefers Go', 'Jun prefers Rust');
+ await run(b.local, 'put_page', { slug, content: edited, expected_revision: current.revision });
+ await extractTakesFromDb(engine, { slugs: [slug], sourceId: b.sourceId, rebuild: true });
+ const after = await takesOf(b, slug);
+ expect(after.map(t => [t.id, t.claim, t.trust_tier])).toEqual(before.map(t => [t.id, t.claim, 'user_confirmed']));
+ expect((await listTrustProposals(engine, { sourceId: b.sourceId })).filter(p => p.status === 'pending')).toHaveLength(2);
+ }
+ }), 120_000);
+});
+
+describe('derived-tier propagation (W1 #6783 §12 (b))', () => {
+ test('an agent edit that lowers a page lowers the fact derived from it; an owner raise never promotes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ const slug = 'notes/kiko-example';
+ await run(b.local, 'put_page', { slug, content: page('Kiko', 'Kiko runs the lab.') });
+ const input = await pageId(b, slug);
+ await curate(b, 'pages', input);
+ const fact = await run(b.local, 'remember', { fact: 'Kiko runs the lab', provenance: 'notes', entity: 'people/kiko-example' });
+ const derived = Number(fact.id);
+ await curate(b, 'facts', derived);
+ await coordinated(b, tx => recordDerivationInputs(tx, { table: 'facts', id: derived, sourceId: b.sourceId }, [{ table: 'pages', id: input }]));
+ const tier = async (table: string, id: number) => (await engine.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM ${table} WHERE id=$1`, [id]))[0]!.trust_tier;
+ expect(await tier('facts', derived)).toBe('operator_curated');
+ const current = await remoteContent(b, slug);
+ await run(b.remote, 'put_page', { slug, content: String(current.content).replace('runs the lab', 'runs the lab and the press'), expected_revision: current.revision });
+ expect(await tier('pages', input)).toBe('agent_written');
+ expect(await tier('facts', derived)).toBe('agent_written');
+ // The owner lowers the input further: the derivative follows. Raising it back never promotes the derivative.
+ expect(await setRowTier(engine, { table: 'pages', id: input, sourceId: b.sourceId, tier: 'external_untrusted' })).toBe(true);
+ expect(await tier('facts', derived)).toBe('external_untrusted');
+ expect(await setRowTier(engine, { table: 'pages', id: input, sourceId: b.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed' })).toBe(true);
+ expect(await tier('pages', input)).toBe('user_confirmed');
+ expect(await tier('facts', derived)).toBe('external_untrusted');
+ const [row] = await engine.executeRaw<{ write_origin: Record<string, any> }>('SELECT write_origin FROM facts WHERE id=$1', [derived]);
+ expect(row!.write_origin.input_lowered).toMatchObject({ from: 'agent_written' });
+ }
+ }), 120_000);
+});