Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge l1a-owner (confirm_memory, owner IPC ops, gbrain trust CLI, lower_page handler, trust allow/disable, migration v233) into capy/memory-trust-writes; quarantine clear keeps the page tier

garrytana327aba5a72a
diff --cc scripts/module-size-limits.tsv
index 33e688a54a,025a41c002..8520013d93
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -17,9 -17,9 +17,9 @@@ src/core/cycle.ts 3283 ratchet +2 Syste
src/core/cycle/synthesize.ts 3227 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt
src/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract
-src/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
+src/core/import-file.ts 2046 ratchet -136 #5575 write gate: the content-sanity disposition block moved to import-screen.ts settleContentDisposition (one call, write gate joined there); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
- src/core/operations.ts 341 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; +1 #5575 purge: purgeOperations import (spread shares the facts line)
+ src/core/operations.ts 342 ratchet +1 #5575 L1a-owner: trustOperations import (confirm_memory, ops/trust.ts); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; +1 #5575 purge: purgeOperations import (spread shares the facts line)
src/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
src/core/postgres-engine.ts 2941 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
diff --cc src/core/persistence/graduation-inventory.ts
index 47c4c7cfd3,93c7e6cb8d..94ca2c0d7c
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@@ -160,10 -155,8 +160,11 @@@ export const GRADUATION_INVENTORY: Inve
carry('takes', 'user_data', 'Takes with attribution and supersession.'),
carry('think_ab_results', 'operational', 'Think A/B eval results.'),
carry('timeline_entries', 'user_data', 'Timeline entries with attribution.'),
+ carry('trust_proposals', 'user_data', 'Pending and decided trust decisions (#5575); dropping them would lose owner review state.'),
+ carry('trust_allow_rules', 'user_data', 'The owner\'s receipted write-gate allow rules (gbrain trust allow); dropping them would re-quarantine sources the owner allowed.'),
carry('wanted_links', 'user_data', 'Unresolved authored links (wanted pages); the edge appears when the target page is written, so they are not re-derived without a full re-extraction.'),
+ carry('write_gate_holds', 'user_data', 'Facts and takes the write gate held for the owner\'s review (#5575); dropping them would lose content awaiting release or drop.'),
+ carry('write_gate_receipts', 'user_data', 'Write-gate verdicts (flag/quarantine) per persisted row (#5575); dropping them would forget which agent-written instructions are unconfirmed.'),
entry('persistence_brain', 'rebind', 'user_data', 'Brain identity and flags carry (brain_id keeps every identity file valid); enabled is set on the target only at cutover.', {
transforms: [{ column: 'enabled', rule: 'false until cutover', expression: 'false' }],
diff --cc src/core/schema-migrations/registry.generated.ts
index 8b22b399d0,1a9676c8f9..330c28ae5a
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -221,8 -221,8 +221,9 @@@ import { v217 } from './v217-persistenc
import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';
import { v219 } from './v219-pages-reconcile-name-indexes.ts';
import { v230 } from './v230-trust-tiers.ts';
+import { v231 } from './v231-write-gate.ts';
import { v232 } from './v232-memory-purge.ts';
+ import { v233 } from './v233-trust-allow-rules.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -442,6 -442,6 +443,7 @@@ export const MIGRATIONS: Migration[] =
v218,
v219,
v230,
+ v231,
v232,
+ v233,
];
diff --cc src/core/trust/channel.ts
index e9a86e8e03,116faa8590..2de5504d64
--- a/src/core/trust/channel.ts
+++ b/src/core/trust/channel.ts
@@@ -36,8 -35,8 +36,11 @@@ export const AGENT_WRITE_OPERATIONS: re
'takes_remove', 'loops_close', 'relink_facts', 'decide_proposal',
];
--/** Intent kinds whose preparer computes the tier from the page (owner-source sync and import paths). */
--const OWNER_SOURCE_KINDS = ['canonical_reconcile', 'managed_file_import', 'managed_file_repair', 'managed_grandfather'];
++/**
++ * Intent kinds whose preparer computes the tier from the page (owner-source sync and import paths), and
++ * the owner's `quarantine clear`, which only removes a gate-owned marker and keeps the page's tier.
++ */
++const OWNER_SOURCE_KINDS = ['canonical_reconcile', 'managed_file_import', 'managed_file_repair', 'managed_grandfather', 'managed_quarantine_clear'];
/** Page frontmatter `source_kind` / `ingested_via` / `captured_via` values written by an ingestion capture (external). */
export const EXTERNAL_CAPTURE_KINDS: readonly string[] = ['webhook', 'file-watcher', 'inbox-folder', 'cron-scheduler', 'ingest_capture'];
diff --cc src/core/trust/page-handlers.ts
index 0e55fb4fd0,75aba10bc1..efce52b07b
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@@ -1,8 -1,378 +1,381 @@@
/**
- * Checked handler for `lower_page` trust proposals (#5575 CEO-12): accept
- * keeps the agent edit at its lowered tier; revert restores the prior owner
- * version's content and tier through the CEO-9 rule.
+ * Owner page actions and the checked handler for `lower_page` trust proposals
+ * (#5575: CEO-9, CEO-12, CEO-21, ENG-10, ENG-22).
+ *
+ * - Confirm a page: raise it to user_confirmed. When the page carries the
+ * lower-only `trust_tier` frontmatter marker (CEO-21), the marker is removed
+ * through the canonical page write path (a journaled `trust_owner_page`
+ * mutation on a managed brain, `importFromContent` otherwise) written at
+ * user_confirmed under the promotion capability; otherwise only the tier
+ * column changes.
+ * - Revert a page to a version: restore that version's content and its
+ * snapshotted tier (page_versions.trust_tier; legacy versions read as
+ * `unknown`), bound to the page revision the owner approved.
+ * - lower_page proposals (inserted by the CEO-12 guard when an agent write
+ * replaced a higher-tier page): accept = the owner endorses the edited page
+ * (confirm it); reject = dismiss, the page stays lowered; revert
+ * (`revertLoweredPage`) = restore the prior owner version's content and tier.
+ *
+ * Every function here runs after the caller established the owner's
+ * confirmation (trust/confirm.ts); each re-checks the page revision it was
+ * approved for and refuses with `preview_changed` when the page moved on.
+ * Fence rows (facts, takes, timeline) keep their own tiers on these rewrites.
*/
- import type { TrustProposalAction } from './proposals.ts';
+ import { randomUUID } from 'node:crypto';
+ import type { BrainEngine } from '../engine.ts';
+ import type { GBrainConfig } from '../config.ts';
+ import type { OperationContext } from '../ops/contract.ts';
+ import { opError } from '../ops/contract.ts';
+ import type { PreparedMutation } from '../persistence/coordinator.ts';
+ import type { Principal, WriteRequest } from '../persistence/model.ts';
+ import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';
+ import type { PageType } from '../types.ts';
+ import type { PageSnapshot } from '../page-state/types.ts';
+ import type { PageVersion } from '../page-state/version-types.ts';
+ import { maintenanceAttribution, principalAttribution, withWriteAttribution } from '../persistence/attribution.ts';
+ import { withCoordinatedWrite, withTrustKeep, withTrustPromotion } from '../persistence/context.ts';
+ import type { OwnerConfirmation } from './confirm.ts';
+ import { MEMORY_CONFIRM_SCOPE } from './confirm.ts';
+ import { pageRef } from './refs.ts';
+ import {
- decisionResult, registerTrustProposalHandler, transitionTrustProposal,
++ decisionResult, registerTrustProposalHandler, transitionTrustProposal, type TrustProposalAction,
+ type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow,
+ } from './proposals.ts';
+ import { effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
- export const PAGE_HANDLER_ACTIONS: readonly TrustProposalAction[] = [];
+ /** The journaled operation that publishes an owner page action on a managed brain. */
+ export const TRUST_OWNER_PAGE_OPERATION = 'trust_owner_page';
+ /** Fence projections keep their own tiers when an owner action rewrites the page around them. */
+ const FENCE_TABLES = ['facts', 'takes', 'timeline_entries'] as const;
+
+ export interface PageTrustState {
+ pageId: number;
+ sourceId: string;
+ slug: string;
+ tier: TrustTier;
+ revision: string;
+ hasMarker: boolean;
+ snapshot: PageSnapshot;
+ }
+
+ /** The page as an owner action sees it: tier, revision and whether the CEO-21 marker is present. Null when absent or deleted. */
+ export async function readPageTrustState(engine: BrainEngine, sourceId: string, slug: string): Promise<PageTrustState | null> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot || snapshot.page.deleted_at) return null;
+ const [row] = await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id = $1', [snapshot.page.id]);
+ return {
+ pageId: snapshot.page.id, sourceId, slug, tier: storedTrustTier(row?.trust_tier), revision: snapshot.revision,
+ hasMarker: Object.hasOwn(snapshot.page.frontmatter ?? {}, 'trust_tier'), snapshot,
+ };
+ }
+
+ function changedSincePreview(ref: string, what: string): Error {
+ return opError('preview_changed', `${ref} changed after you approved ${what}; nothing was changed.`,
+ 'Run the command again: it shows the page as it is now and asks for a new confirmation.');
+ }
+
+ /** The page with the CEO-21 marker removed, as canonical markdown. */
+ function markdownWithoutMarker(snapshot: PageSnapshot): string {
+ const { trust_tier: _marker, ...frontmatter } = (snapshot.page.frontmatter ?? {}) as Record<string, unknown>;
+ return serializeMarkdown(frontmatter, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {
+ type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,
+ });
+ }
+
+ /** One version's canonical markdown, the way revert_version restores it (page-prepare.ts). */
+ function versionMarkdown(snapshot: PageSnapshot, version: PageVersion): string {
+ const page = { ...snapshot.page, compiled_truth: version.compiled_truth, frontmatter: version.frontmatter,
+ ...(version.timeline != null ? { timeline: version.timeline } : {}),
+ ...(version.title != null ? { title: version.title } : {}),
+ ...(version.type != null ? { type: version.type as PageType } : {}) };
+ return serializePageToMarkdown(page, version.tags ?? snapshot.tags);
+ }
+
+ export async function readPageVersion(engine: BrainEngine, pageId: number, versionId: number): Promise<(PageVersion & { trust_tier: string | null }) | null> {
+ const [version] = await engine.executeRaw<PageVersion & { trust_tier: string | null }>(
+ 'SELECT * FROM page_versions WHERE id = $1 AND page_id = $2', [versionId, pageId]);
+ return version ?? null;
+ }
+
+ /** The most recent version of a page (the content just before its latest archived write). */
+ export async function latestPageVersionId(engine: BrainEngine, pageId: number): Promise<number | null> {
+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM page_versions WHERE page_id = $1 ORDER BY id DESC LIMIT 1', [pageId]);
+ return row ? Number(row.id) : null;
+ }
+
+ const ownerTrust = (tier: TrustTier, channel: string, via: OwnerConfirmation['via']): WriteTrust =>
+ effectiveWriteTrust({ channel: tier, origin: { channel: `owner:${channel}`, connector: via } });
+
+ async function managed(engine: BrainEngine): Promise<boolean> {
+ const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');
+ return managedPersistenceEnabled(engine);
+ }
+
+ async function attributionFor(engine: BrainEngine, by: Principal | null | undefined) {
+ return by ? principalAttribution(by) : maintenanceAttribution(engine);
+ }
+
+ /**
+ * A tier-only change of one row (no content column changes), inside the
+ * coordinator capability on a managed brain. Raising needs `ceiling`.
+ */
+ export async function setRowTier(engine: BrainEngine, input: {
+ table: 'facts' | 'takes' | 'pages'; id: number; sourceId: string; tier: TrustTier; ceiling?: TrustTier;
+ expect?: (tx: BrainEngine) => Promise<boolean>; by?: Principal | null; note?: Record<string, unknown>;
+ also?: (tx: BrainEngine) => Promise<void>;
+ }): Promise<boolean> {
+ const attribution = await attributionFor(engine, input.by);
+ const enabled = await managed(engine);
+ return engine.transaction(async tx => {
+ const run = async () => {
+ if (input.expect && !(await input.expect(tx))) return false;
+ 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)
+ WHERE id = $1 RETURNING id`, [input.id, input.tier, JSON.stringify({ tier: input.tier, at: new Date().toISOString(), ...input.note })]);
+ const rows = input.ceiling ? await withTrustPromotion(tx, input.ceiling, update) : await update();
+ if (rows.length !== 1) return false;
+ await input.also?.(tx);
+ return true;
+ };
+ return enabled ? withCoordinatedWrite(tx, [input.sourceId], run, attribution) : withWriteAttribution(tx, attribution, run);
+ });
+ }
+
+ export interface PageActionInput {
+ sourceId: string;
+ slug: string;
+ /** The page revision the owner approved. */
+ expectedRevision: string;
+ confirmation: OwnerConfirmation;
+ by?: Principal | null;
+ config?: GBrainConfig;
+ /** A lower_page proposal this action decides, closed in the same transaction. */
+ proposal?: { id: number; to: 'accepted' | 'rejected'; after: Record<string, unknown> };
+ /** The remote context of a memory_confirm caller (managed admission authority); local CLI otherwise. */
+ ctx?: OperationContext;
+ }
+
+ export interface PageActionResult {
+ status: 'confirmed' | 'reverted' | 'unchanged';
+ ref: string;
+ tier: TrustTier;
+ prior_tier: TrustTier;
+ marker_removed?: boolean;
+ version_id?: number;
+ }
+
+ type OwnerPageIntent = {
+ mode: 'confirm' | 'revert';
+ expected_revision: string;
+ version_id?: number;
+ via: OwnerConfirmation['via'];
+ proposal?: PageActionInput['proposal'];
+ };
+
+ /** Closes a decided proposal inside the publication transaction, or refuses (it was decided meanwhile). */
+ async function closeProposal(tx: BrainEngine, proposal: PageActionInput['proposal'], by: Principal | null | undefined): Promise<void> {
+ if (!proposal) return;
+ if (!(await transitionTrustProposal(tx, proposal.id, 'pending', proposal.to, { after: proposal.after, decidedBy: by ?? null }))) {
+ throw opError('preview_changed', `Trust proposal tp${proposal.id} was decided by someone else meanwhile; nothing was changed.`,
+ 'Run gbrain trust review to see its current state.');
+ }
+ }
+
+ /** Raises a page to user_confirmed (removing the CEO-21 marker when present). */
+ export async function confirmPage(engine: BrainEngine, input: PageActionInput): Promise<PageActionResult> {
+ const ref = pageRef(input.sourceId, input.slug);
+ const state = await readPageTrustState(engine, input.sourceId, input.slug);
+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Check the ref; gbrain trust review lists pages waiting for you.');
+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, 'its confirmation');
+ if (state.tier === 'user_confirmed' && !state.hasMarker) {
+ await engine.transaction(tx => closeProposal(tx, input.proposal, input.by));
+ return { status: 'unchanged', ref, tier: state.tier, prior_tier: state.tier };
+ }
+ if (!state.hasMarker) {
+ const ok = await setRowTier(engine, {
+ table: 'pages', id: state.pageId, sourceId: input.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by: input.by,
+ note: { via: input.confirmation.via, action: 'confirm' },
+ expect: async tx => (await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision === input.expectedRevision,
+ also: tx => closeProposal(tx, input.proposal, input.by),
+ });
+ if (!ok) throw changedSincePreview(ref, 'its confirmation');
+ return { status: 'confirmed', ref, tier: 'user_confirmed', prior_tier: state.tier, marker_removed: false };
+ }
+ await publishOwnerPage(engine, input, { mode: 'confirm', expected_revision: input.expectedRevision, via: input.confirmation.via, proposal: input.proposal },
+ markdownWithoutMarker(state.snapshot), 'user_confirmed');
+ return { status: 'confirmed', ref, tier: 'user_confirmed', prior_tier: state.tier, marker_removed: true };
+ }
+
+ /** The tier a version restores: its snapshot tier, `unknown` for legacy versions. */
+ export const versionTier = (version: { trust_tier?: string | null }): TrustTier => storedTrustTier(version.trust_tier);
+
+ /** Restores a version's content and its snapshotted tier. */
+ export async function revertPageToVersion(engine: BrainEngine, input: PageActionInput & { versionId: number }): Promise<PageActionResult> {
+ const ref = pageRef(input.sourceId, input.slug);
+ const state = await readPageTrustState(engine, input.sourceId, input.slug);
+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, `Check the ref; gbrain history ${input.slug} lists its versions.`);
+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, 'the revert');
+ const version = await readPageVersion(engine, state.pageId, input.versionId);
+ if (!version) throw opError('not_found', `Version ${input.versionId} is not in the history of ${ref}.`, `List the page's versions with gbrain history ${input.slug} and pass one of their ids to --version.`);
+ const tier = versionTier(version);
+ await publishOwnerPage(engine, input, { mode: 'revert', expected_revision: input.expectedRevision, version_id: input.versionId, via: input.confirmation.via, proposal: input.proposal },
+ versionMarkdown(state.snapshot, version), tier);
+ return { status: 'reverted', ref, tier, prior_tier: state.tier, version_id: input.versionId };
+ }
+
+ /**
+ * Publishes an owner page write at `tier`. A content rewrite by an owner-tier
+ * writer restamps the page (CEO-12); user_confirmed needs the promotion
+ * ceiling, and a lower restored tier lowers it (min with the prior tier).
+ */
+ async function publishOwnerPage(engine: BrainEngine, input: PageActionInput, intent: OwnerPageIntent, markdown: string, tier: TrustTier): Promise<void> {
+ if (await managed(engine)) {
+ await submitOwnerPage(engine, input, intent);
+ return;
+ }
+ const { importFromContent } = await import('../import-file.ts');
+ const attribution = await attributionFor(engine, input.by);
+ const trust = ownerTrust(tier, intent.mode, intent.via);
+ await engine.transaction(tx => withWriteAttribution(tx, { ...attribution, trust }, () => withTrustPromotion(tx, tier, () =>
+ withTrustKeep(tx, FENCE_TABLES, async () => {
+ if ((await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision !== input.expectedRevision) {
+ throw changedSincePreview(pageRef(input.sourceId, input.slug), intent.mode === 'confirm' ? 'its confirmation' : 'the revert');
+ }
+ await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, preserveGateMarkers: intent.mode === 'confirm', forceRechunk: intent.mode === 'revert', allowEmptyOverwrite: intent.mode === 'revert' });
+ await closeProposal(tx, intent.proposal, input.by);
+ }))));
+ }
+
+ /** Admits the journaled owner page mutation and waits for its publication (the decide_proposal precedent). */
+ async function submitOwnerPage(engine: BrainEngine, input: PageActionInput, intent: OwnerPageIntent): Promise<void> {
+ const { initializeLocalPersistence, requestPrincipalForContext } = await import('../persistence/page-mutations.ts');
+ const { submissionAuthority } = await import('../persistence/authority.ts');
+ const { admitWrite } = await import('../persistence/journal.ts');
+ const { assertPersistenceAccepting, waitForWrite, writeResponse } = await import('../persistence/service.ts');
+ const { getWorktreeBinding } = await import('../persistence/ownership.ts');
+ const config = input.config ?? ({ engine: engine.kind } as GBrainConfig);
+ const ctx = input.ctx ?? ({ engine, sourceId: input.sourceId, remote: false, config, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext);
+ assertPersistenceAccepting(engine);
+ await initializeLocalPersistence(ctx);
+ const principal = await requestPrincipalForContext(ctx);
+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation, archived FROM sources WHERE id = $1', [input.sourceId]);
+ if (!source || source.archived) throw opError('source_changed', `Source ${input.sourceId} is archived or missing; nothing was changed.`, 'Restore the source first (the user\'s call).');
+ const authority = await submissionAuthority(ctx, TRUST_OWNER_PAGE_OPERATION, input.sourceId, source.incarnation, input.slug);
+ const snapshot = await engine.readPageSnapshot(input.slug, { sourceId: input.sourceId });
+ const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
+ const binding = snapshot && writeThrough ? await getWorktreeBinding(engine, input.sourceId) : null;
+ if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';
+ const row = await admitWrite(engine, {
+ principal, operation: TRUST_OWNER_PAGE_OPERATION, sourceId: input.sourceId, sourceIncarnation: source.incarnation, slug: input.slug,
+ pageId: snapshot?.page.id ?? null, requestId: randomUUID(), callerIntent: intent, intent, authority,
+ worktreeId: binding?.worktree_id ?? null, topologyGeneration: binding?.topology_generation ?? null,
+ });
+ writeResponse(await waitForWrite(engine, row, config, 30_000));
+ }
+
+ /**
+ * The coordinator preparer for `trust_owner_page` (persistence/service.ts).
+ * The resident owner re-validates here: a remote request needs a recorded
+ * memory_confirm scope; the page must still be at the approved revision.
+ */
+ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
+ const intent = row.intent as unknown as OwnerPageIntent | null;
+ if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || (intent.mode !== 'confirm' && intent.mode !== 'revert') || typeof intent.expected_revision !== 'string'
+ || (row.authority.remote && !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE))) {
+ throw opError('confirmation_required', 'This owner page action is not confirmed by the owner; nothing was changed.',
+ 'Run the gbrain trust command on the brain host in an interactive terminal.');
+ }
+ const ref = pageRef(row.source_id, row.slug);
+ const state = await readPageTrustState(engine, row.source_id, row.slug);
+ if (!state || state.revision !== intent.expected_revision) throw changedSincePreview(ref, intent.mode === 'confirm' ? 'its confirmation' : 'the revert');
+ let content: string;
+ let tags: string[] | undefined;
+ let tier: TrustTier = 'user_confirmed';
+ if (intent.mode === 'revert') {
+ const version = Number.isSafeInteger(intent.version_id) ? await readPageVersion(engine, state.pageId, intent.version_id!) : null;
+ if (!version) throw opError('not_found', `Version ${String(intent.version_id)} is not in the history of ${ref}.`, `List versions with gbrain history ${row.slug}.`);
+ content = versionMarkdown(state.snapshot, version);
+ tags = version.tags ?? undefined;
+ tier = versionTier(version);
+ } else content = markdownWithoutMarker(state.snapshot);
+ // The request keeps its own operation, so page-prepare stamps no CEO-21 marker and files no lower_page item for it.
+ const { preparePageMutation } = await import('../persistence/page-prepare.ts');
+ const page = await preparePageMutation(engine, row, config, { content, expectedRevision: intent.expected_revision, ...(tags ? { tags } : {}) });
+ const apply = page.apply;
+ page.trust = ownerTrust(tier, intent.mode, intent.via);
+ page.apply = (tx, preimage) => withTrustPromotion(tx, tier, () => withTrustKeep(tx, FENCE_TABLES, async () => {
+ const outcome = await apply(tx, preimage);
+ await closeProposal(tx, intent.proposal, { kind: row.principal_kind as Principal['kind'], id: row.principal_id });
+ return { ...outcome, trust_action: intent.mode, trust_tier: tier };
+ }));
+ return page;
+ }
+
+ // ---------------------------------------------------------------------------
+ // lower_page proposals (CEO-12)
+ // ---------------------------------------------------------------------------
+
+ export interface LowerPageState {
+ slug: string;
+ prior_tier: TrustTier;
+ prior_revision: string | null;
+ version_id: number | null;
+ /** The latest agent edit (after_state). */
+ edited_revision: string | null;
+ edited_tier: TrustTier;
+ }
+
+ export function lowerPageState(proposal: TrustProposalRow): LowerPageState {
+ const b = proposal.before_state;
+ const a = proposal.after_state;
+ return {
+ slug: String(b.slug ?? ''), prior_tier: storedTrustTier(b.prior_tier),
+ prior_revision: typeof b.prior_revision === 'string' ? b.prior_revision : null,
+ version_id: b.version_id === null || b.version_id === undefined ? null : Number(b.version_id),
+ edited_revision: typeof a.revision === 'string' ? a.revision : null, edited_tier: storedTrustTier(a.tier),
+ };
+ }
+
+ async function staleUnlessAt(engine: BrainEngine, proposal: TrustProposalRow, state: LowerPageState): Promise<PageTrustState | TrustDecisionResult> {
+ const page = state.slug ? await readPageTrustState(engine, proposal.source_id, state.slug) : null;
+ if (!page || page.pageId !== proposal.target_id) return decisionResult(proposal, 'accept', 'stale', { reason: 'page_missing' });
+ if (state.edited_revision && page.revision !== state.edited_revision) return decisionResult(proposal, 'accept', 'stale', { reason: 'page_changed_since' });
+ return page;
+ }
+
+ /** Revert decision of a lower_page proposal: restore the prior owner version's content and tier. */
+ export async function revertLoweredPage(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult> {
+ const state = lowerPageState(proposal);
+ if (state.version_id === null) return decisionResult(proposal, 'reject', 'refused', { reason: 'no_prior_version' });
+ const page = await staleUnlessAt(engine, proposal, state);
+ if (!('pageId' in page)) return { ...page, decision: 'reject' };
+ const result = await revertPageToVersion(engine, {
+ sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, versionId: state.version_id,
+ confirmation: ctx.confirmation, by: ctx.decidedBy, config: ctx.config,
+ proposal: { id: proposal.id, to: 'rejected', after: { ...proposal.after_state, resolution: 'reverted', restored_tier: state.prior_tier } },
+ });
+ return decisionResult(proposal, 'reject', 'rejected', { reason: 'reverted', detail: { ...result } });
+ }
+
++/** The actions this module registers handlers for (trust/decide.ts loads every handler module through these). */
++export const PAGE_HANDLER_ACTIONS: readonly TrustProposalAction[] = ['lower_page'];
++
+ registerTrustProposalHandler('lower_page', {
+ async accept(engine, proposal, ctx) {
+ const state = lowerPageState(proposal);
+ const page = await staleUnlessAt(engine, proposal, state);
+ if (!('pageId' in page)) return page;
+ const result = await confirmPage(engine, {
+ sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation,
+ by: ctx.decidedBy, config: ctx.config,
+ proposal: { id: proposal.id, to: 'accepted', after: { ...proposal.after_state, resolution: 'confirmed' } },
+ });
+ return decisionResult(proposal, 'accept', 'accepted', { detail: { ...result } });
+ },
+ async reject(engine, proposal, ctx) {
+ return await transitionTrustProposal(engine, proposal.id, 'pending', 'rejected', { after: { ...proposal.after_state, resolution: 'dismissed' }, decidedBy: ctx.decidedBy })
+ ? decisionResult(proposal, 'reject', 'rejected', { reason: 'dismissed' })
+ : decisionResult(proposal, 'reject', 'refused', { reason: 'not_pending' });
+ },
+ });
diff --cc test/fixtures/goldens/catalog/pglite-engine-init-default.json
index a637718650,5ae74562d9..2a5ba2350d
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@@ -1271,10 -1264,9 +1282,11 @@@
"takes_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=takes.id",
"think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",
"timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",
+ "trust_allow_rules_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_allow_rules.id",
"trust_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_proposals.id",
- "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"
+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id",
+ "write_gate_holds_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_holds.id",
+ "write_gate_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_receipts.id"
},
"tables": {
"access_tokens": {
diff --cc test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index d54c59d95a,c8be810846..e07bf00956
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@@ -1271,10 -1264,9 +1282,11 @@@
"takes_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=takes.id",
"think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",
"timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",
+ "trust_allow_rules_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_allow_rules.id",
"trust_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_proposals.id",
- "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"
+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id",
+ "write_gate_holds_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_holds.id",
+ "write_gate_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_receipts.id"
},
"tables": {
"access_tokens": {
diff --cc test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index b3c861998d,cd92b55c03..b167ffcbde
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@@ -1267,10 -1260,9 +1278,11 @@@
"takes_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=takes.id",
"think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",
"timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",
+ "trust_allow_rules_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_allow_rules.id",
"trust_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_proposals.id",
- "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"
+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id",
+ "write_gate_holds_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_holds.id",
+ "write_gate_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_receipts.id"
},
"tables": {
"access_tokens": {
diff --cc test/graduation-inventory.test.ts
index ea0824e615,39efdf2713..80d8907031
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@@ -60,7 -60,7 +60,7 @@@ describe('graduation inventory', () =>
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 118, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });
- expect(counts).toEqual({ carry: 111, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });
++ expect(counts).toEqual({ carry: 119, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --cc test/trust-channel-writes.test.ts
index 5e8accc448,79c1be0206..36b5487397
--- a/test/trust-channel-writes.test.ts
+++ b/test/trust-channel-writes.test.ts
@@@ -109,6 -104,6 +109,8 @@@ describe('channel tier rules (pure)', (
expect(requestChannelTrust(row('submit_job', false, { kind: 'connector_v2_google' }))?.tier).toBe('external_untrusted');
expect(requestChannelTrust(row('submit_job', false, { kind: 'managed_sync_batch' }))).toBeUndefined();
expect(requestChannelTrust(row('put_page', false, { kind: 'managed_file_import' }))).toBeUndefined();
++ // The owner's quarantine clear only removes a gate-owned marker: it declares no tier, stamps no marker, keeps the page tier.
++ expect(requestChannelTrust(row('put_page', false, { kind: 'managed_quarantine_clear' }))).toBeUndefined();
expect(requestChannelTrust(row('put_page', true))?.origin?.channel).toBe('mcp:put_page');
});
test('frontmatter markers only lower; sources set-trust never exceeds operator_curated; connector sources are external', () => {