Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/capy/memory-trust (L1b reads) into capy/memory-trust-writes; gbrain trust explain shows per-surface decisions

garrytan47f796b31e92
diff --cc docs/architecture/key-files/core-utilities-2.md
index 43965044c1,8f25dd72a0..1fd46f82d0
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@@ -42,7 -42,9 +42,9 @@@ Current behavior and load-bearing invar
- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
-- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`.
+- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`. Write side (lane L1a): `channel.ts` computes the tier once per write from the channel (`requestChannelTrust`: agent verbs agent_written, `content_origin: tool_output` external_untrusted, connector jobs external_untrusted; owner sync/import `ownerImportTrust`: operator_curated or the `sources set-trust` default, lowered by frontmatter markers `frontmatterTrustCaps`) and `stampTrustMarker` (the lower-only `trust_tier` marker, CEO-21); `page-write.ts` wires it into page-prepare (marker stamp, fence edits keep the page tier via `withTrustKeep`, `lower_page` proposals on agent rewrites, the page gate tier); `proposals.ts` is the `trust_proposals` store and handler dispatch (`decide.ts` loads every handler); `supersede-handlers.ts` is guarded supersession (`supersessionGuarded`, contested fact/take/ontology proposals, remote `forget_requires_owner`, the trust store for the checked decide_proposals supersede); `fence-guard.ts` guards the facts-fence re-projection and gates new fence rows; `gate-outcomes.ts` is the DX-1 `gate` field and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15). `owner-actions.ts`: `previewOwnerAction` / `applyOwnerAction` for confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and a `binding` of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with `preview_changed` and a raising action without a confirmation with `confirmation_required` (`ownerActionFix` is the DX-3 `tell_user_to_run` fix). Fact and take confirms are tier-only updates under `withTrustPromotion` (inside `withCoordinatedWrite` on a managed brain); the hold store is an isolated adapter over `write_gate_holds` (`__setHoldStoreForTests`, `TODO(L2a-merge)`); `disable --all` writes `write_gate.external_mode=off`, `write_gate.agent_mode=off`, `trust.agent_activation=allow` with the `trust.kill_switch` receipt that `--undo` restores from. `page-handlers.ts`: `confirmPage` (removes the CEO-21 `trust_tier` marker through a journaled `trust_owner_page` mutation on a managed brain, `importFromContent` otherwise; tier only when no marker), `revertPageToVersion` (the version's content and its snapshot tier, `unknown` for legacy versions), the coordinator preparer `prepareTrustOwnerPageMutation` (dispatched from `persistence/service.ts`; re-checks the approved revision and refuses a remote request without `memory_confirm`), and the `lower_page` handler (accept = confirm, reject = dismiss, `revertLoweredPage` = restore the prior owner version). `refs.ts`: typed refs `f<id>`, `t<id>`, `h<id>`, `tp<id>`, `a<id>`, `p:<source>/<slug>`, bare slugs resolved by `--source` or a single source (ambiguity refuses). `review.ts`: `buildTrustReview` (pending proposals, lowered pages, unconfirmed standing preferences, holds, allow rules, kill-switch state, grouped by day and page, complete argv) and `explainTrust`. `allow-rules.ts`: the `trust_allow_rules` table (migration v233, receipted, removal keeps the row) and the pure `matchTrustAllowRule` over server-stamped fields. `owner-ipc.ts`: the `trust_read` / `trust_preview` / `trust_apply` administration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests: `test/trust-owner-actions.test.ts` (PGLite and Postgres), `test/trust-owner-ipc.test.ts`, `test/trust-cli.test.ts`.
+ - `src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts` — the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14). `policy.ts`: `resolveReadEligibility` returns the effective floor (the strictest of `AuthInfo.minTrust`, the caller's `min_trust` and `trust.read_policy=filter`'s own `unknown` floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, `suppressFlagged` unless `trust.agent_activation=allow`. `sql.ts`: vetted predicates over a caller alias (closed vocabularies only): `trustFloorSql`, `pageEligibleSql` (spliced by `buildVisibilityClause` and `pageReadFilter`, so every search arm filters before LIMIT; a chunk's tier is its page's), `projectionEligibleSql` (facts, takes and timeline reads: a quarantined page's projections and `needs_rederive` rows are hidden, never expired) and `activationSuppressedSql` (tier at or below `agent_written` plus an instruction-family `write_gate_receipts` flag). `labels.ts`: `trust_tier` + a short server-stamped `origin`; compact per-item text labels with the fixed words, `unknown` as a short origin line, and the `<external-data>` envelope only below `unknown`. `registry.ts`: `OP_READ_TRUST` classifies every read-scope op `filtered | labeled | text_free` (the dispatcher refuses a `labeled` op for a floored token) and `PROACTIVE_SURFACES` lists the injecting surfaces, each calling `proactiveEligibility(ctx, id)`; drift-tested by `test/eligibility-registry.test.ts`. `stamp.ts` labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows `unconfirmed`. `activation.ts` partitions proactive candidates (`partitionForActivation`, `pageActivationVerdicts`) and builds the `memory_suppressed` notice (count + `gbrain trust review`, never content). `scan.ts` (`gbrain trust scan`, doctor `trust_scan`) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans). `explain.ts` is the `gbrain trust explain` data API: tier, origin, receipts and the per-surface decision for a typed ref. Tests: `test/eligibility-{policy,registry,reads}.test.ts`.
+ - `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.
diff --cc scripts/module-size-limits.tsv
index 4f80f54ed6,2af6980a10..41d4de9e14
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -16,10 -16,10 +16,10 @@@ src/commands/sync.ts 512 ratchet refact
src/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts)
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/engine.ts 2728 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; +7 #5575 (L1b): FactListOpts/TakesListOpts eligibility, FactRow/Take trust fields, searchTakes/listSupersessions eligibility in the interface
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/cli/commands/trust.ts
index 0b5bae0f0c,920bd0e1ce..f10e1c9db7
--- a/src/cli/commands/trust.ts
+++ b/src/cli/commands/trust.ts
@@@ -1,28 -1,36 +1,35 @@@
/**
* `gbrain trust`: the memory-trust noun (#5575, DX-7). This module dispatches
- * `backfill` (A8, DX-5) and hands the owner subcommands (review, confirm,
- * `backfill` (A8, DX-5); the other subcommands (review, confirm, release,
- * drop, revert, explain, allow, disable) join the same record. The record is
- * startup: 'observational', so `backfill --dry-run` runs on a probe-only
- * engine with no migrations and no writes; applying completes startup first.
++ * `backfill` (A8, DX-5) and `scan` (DX-6), and hands the owner subcommands (review, confirm,
+ * release, drop, revert, explain, allow, disable) to src/commands/trust.ts.
+ * The record is startup: 'observational', so `backfill --dry-run` runs on a
+ * probe-only engine with no migrations and no writes; every other subcommand
+ * completes startup first. While a resident serve holds a PGLite brain,
+ * src/cli.ts routes the owner subcommands to it before any engine opens.
*/
import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { TRUST_TIERS, trustLabel } from '../../core/trust/tier.ts';
import { runTrustBackfill, type TrustBackfillReport } from '../../core/trust/backfill.ts';
+ import { runTrustScan } from '../../core/eligibility/scan.ts';
+ import { explainTrust } from '../../core/eligibility/explain.ts';
import type { CliDispatchContext } from '../command-table.ts';
+import { TRUST_OWNER_USAGE, isTrustOwnerSubcommand, localTrustBackend, runTrustOwnerCommand } from '../../commands/trust.ts';
-export const TRUST_USAGE = [
+export const TRUST_BACKFILL_USAGE = [
'Usage: gbrain trust backfill [--dry-run] [--resume] [--batch-size N] [--json]',
' Classifies rows written before trust tiers (facts, takes, timeline entries, pages) from deterministic signals:',
' connector sources, page source_kind, transcript/extraction/dream provenance, facts and takes source tags, and',
' the journaled request that wrote the row. Rows with no signal stay "unverified origin"; nothing becomes',
' "confirmed by you". --dry-run is read-only (no migrations, no writes) and works before the trust migration;',
' it reports the projected count per table and tier. --resume continues an interrupted run.',
+ '',
+ 'Usage: gbrain trust scan [--batch-size N] [--json]',
+ ' Runs the write gate\'s deterministic detector over agent-written and lower rows written before the gate,',
+ ' recording a receipt for each instruction-like row so proactive surfaces stop injecting it until you confirm',
+ ' it (gbrain trust review). Changes no row; resumable (rerun to continue); a detector upgrade rescans.',
- '',
- 'Usage: gbrain trust explain <ref> [--json]',
- ' Why a memory is or is not used: its trust tier and origin, the write gate\'s verdict and receipts, and whether',
- ' each proactive surface (hook, context engine, context pack, volunteer, reflex, core, hot memory) and explicit',
- ' reads use it. Refs: f<id> fact, t<id> take, e<id> timeline entry, h<id> hold, p:<source>/<slug> page. Read-only.',
].join('\n');
+export const TRUST_USAGE = `${TRUST_OWNER_USAGE}\n\n${TRUST_BACKFILL_USAGE}`;
function render(report: TrustBackfillReport): string {
const lines = [`Trust backfill (${report.mode === 'dry_run' ? 'dry run, nothing written' : 'applied'}; schema: ${report.schema}):`];
@@@ -37,17 -45,12 +44,21 @@@
export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
const [sub, ...rest] = args;
- const known = sub === 'backfill' || isTrustOwnerSubcommand(sub);
- const known = sub === 'backfill' || sub === 'scan' || sub === 'explain';
++ const known = sub === 'backfill' || sub === 'scan' || isTrustOwnerSubcommand(sub);
if (!sub || args.includes('--help') || args.includes('-h') || !known) {
- console.log(sub === 'backfill' ? TRUST_BACKFILL_USAGE : TRUST_USAGE);
- console.log(TRUST_USAGE);
++ console.log(sub === 'backfill' || sub === 'scan' ? TRUST_BACKFILL_USAGE : TRUST_USAGE);
if (sub && !known && !args.includes('--help') && !args.includes('-h')) setCliExitVerdict(2);
return;
}
- if (sub !== 'backfill') {
++ if (sub !== 'backfill' && sub !== 'scan') {
+ await ctx.completeStartup?.(engine);
+ await runTrustOwnerCommand(localTrustBackend(engine, ctx.SELECTED_CONFIG_BY_ENGINE.get(engine)), sub, rest);
++ // `explain` also shows each proactive surface's decision for a typed ref (eligibility/explain.ts).
++ const ref = sub === 'explain' && !jsonRequested(args) ? rest.find(a => !a.startsWith('--')) : undefined;
++ const why = ref ? await explainTrust(engine, ref).catch(() => null) : null;
++ if (why?.found) console.log(['Per surface:', ...Object.entries(why.activation).map(([surface, decision]) => ` ${surface}: ${decision}`)].join('\n'));
+ return;
+ }
const dryRun = rest.includes('--dry-run');
const sizeAt = rest.indexOf('--batch-size');
const batchSize = sizeAt >= 0 ? Number(rest[sizeAt + 1]) : undefined;
@@@ -56,6 -59,27 +67,15 @@@
setCliExitVerdict(2);
return;
}
- if (sub === 'explain') {
- const ref = rest.find(a => !a.startsWith('--'));
- if (!ref) { console.error('Usage: gbrain trust explain <ref> [--json]'); setCliExitVerdict(2); return; }
- const why = await explainTrust(engine, ref);
- if (!why.found) setCliExitVerdict(1);
- if (jsonRequested(args)) { await writeStdoutFinal(`${JSON.stringify(why, null, 2)}\n`); return; }
- if (!why.found) { console.log(`${ref}: no fact, take, timeline entry, hold or page has this ref.`); return; }
- console.log([`${ref}: ${why.label} (${why.trust_tier}), origin ${why.origin}; gate verdict ${why.verdict}${why.unconfirmed ? ', unconfirmed' : ''}`,
- ...Object.entries(why.activation).map(([surface, decision]) => ` ${surface}: ${decision}`),
- ...(why.next ? [` Review: ${why.next.join(' ')}`] : [])].join('\n'));
- return;
- }
+ if (sub === 'scan') {
+ await ctx.completeStartup?.(engine);
+ const scan = await runTrustScan(engine, batchSize ? { batchSize } : {});
+ if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(scan, null, 2)}\n`);
+ else console.log([`Trust scan (detector v${scan.detector_version}):`,
+ ...scan.tables.map(t => ` ${t.table}: ${t.scanned} row(s) scanned, ${t.flagged} flagged${t.done ? '' : ' (more to scan)'}`),
+ scan.complete ? ' Complete. Flagged rows are withheld from proactive context until confirmed (gbrain trust review).' : ` Continue with: ${scan.resume_command}`].join('\n'));
+ return;
+ }
if (!dryRun) await ctx.completeStartup?.(engine);
const report = await runTrustBackfill(engine, { dryRun, resume: rest.includes('--resume'), ...(batchSize ? { batchSize } : {}) });
if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(report, null, 2)}\n`);
diff --cc src/commands/trust.ts
index 4a7f626f94,0000000000..283f6f7443
mode 100644,000000..100644
--- a/src/commands/trust.ts
+++ b/src/commands/trust.ts
@@@ -1,265 -1,0 +1,265 @@@
+/**
+ * `gbrain trust` owner subcommands (#5575: CEO-2, CEO-9, DX-2, DX-3, DX-7,
+ * DX-10, DX-13, DX-14, DX-15, ENG-15): review, confirm, release, drop,
+ * revert, explain, allow, disable. `backfill` lives in the dispatch module
+ * (src/cli/commands/trust.ts).
+ *
+ * Every action previews the target, asks the owner to type its token on an
+ * interactive terminal when the action raises trust (trust/confirm.ts; piped
+ * input, agents and --yes never confirm), then applies it bound to the
+ * previewed state. The backend is the local engine, or, while a resident
+ * `gbrain serve` holds a PGLite brain, that owner's 0600 administration
+ * socket (trust/owner-ipc.ts): the prompt still happens here, in the
+ * invoking terminal, and the owner re-validates the binding.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../core/engine.ts';
+import type { GBrainConfig } from '../core/config.ts';
+import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { OperationError, opError, type OperationContext } from '../core/ops/contract.ts';
+import type { Principal } from '../core/persistence/model.ts';
+import { maintenanceAttribution } from '../core/persistence/attribution.ts';
+import { requireOwnerConfirmation } from '../core/trust/confirm.ts';
+import {
+ applyOwnerAction, previewOwnerAction, type OwnerActionInput, type OwnerActionPreview, type OwnerActionResult,
+} from '../core/trust/owner-actions.ts';
+import {
+ buildTrustReview, explainTrust, parseTrustReviewKind, parseTrustSince, renderTrustExplanation, renderTrustReview,
+ type TrustExplanation, type TrustReview, type TrustReviewFilter,
+} from '../core/trust/review.ts';
+import { trustLabel } from '../core/trust/tier.ts';
+import { reportPersistenceCliError } from './persistence-delegate.ts';
+import { writeCliError } from '../cli/cli-error.ts';
+
+export const TRUST_OWNER_USAGE = [
- 'Usage: gbrain trust <review|confirm|release|drop|revert|explain|allow|disable|backfill> [options]',
++ 'Usage: gbrain trust <review|confirm|release|drop|revert|explain|allow|disable|backfill|scan> [options]',
+ ' review [--from <source>] [--kind <kind>] [--since <7d|date>] [--json]',
+ ' Everything waiting for you: trust proposals (tp<id>), pages an agent edit lowered, unconfirmed standing',
+ ' preferences (f<id>), held writes (h<id>) and your allow rules (a<id>), grouped by day and page, each with',
+ ' its exact commands.',
+ ' review --accept-all (--from <source> | --kind <kind> | --since <when>)...',
+ ' Accept every listed item matching the filters (at least one filter) after one typed confirmation.',
+ ' confirm <f<id>|t<id>|p:<source>/<slug>|tp<id>|h<id>> [--source <id>]',
+ ' Mark it "confirmed by you" (accepts a proposal; releases a held write). Asks you to type its token.',
+ ' release <h<id>> Release a held write into memory as "confirmed by you" (asks for its token).',
+ ' drop <tp<id>|h<id>> Dismiss a proposal, or drop a held write. Nothing gains trust.',
+ ' revert <tp<id>|p:<source>/<slug>> [--version <id>] [--source <id>]',
+ ' Restore the page version before an agent edit (or the version you name) with its own tier.',
+ ' explain <ref|phrase> [--source <id>]',
+ ' Tier, origin (including what a derived row came from), write-gate receipts, pending decisions and where',
+ ' the row is used.',
+ ' allow --source <id> [--uri-prefix <prefix>] [--reason-family <family>] [--reason <text>]',
+ ' allow --remove <a<id>>',
+ ' Stop holding instruction-like content from a source (matches the server-stamped source URI, never',
+ ' frontmatter). Listed in review; adding one asks for its token.',
+ ' disable --all [--undo]',
+ ' Kill switch: write_gate.external_mode=off, write_gate.agent_mode=off, trust.agent_activation=allow.',
+ ' --undo restores what disable replaced. Local only; asks for its token.',
+ ' Refs: f<id> fact, t<id> take, h<id> held write, tp<id> trust proposal, a<id> allow rule, p:<source>/<slug> page',
+ ' (a bare slug works when it lives in one source, or with --source). --yes never confirms; these commands need',
+ ' you at a terminal on the brain host.',
+].join('\n');
+
+/** Where the owner actions run: this process's engine, or the resident owner over its local socket. */
+export interface TrustBackend {
+ review(filter: TrustReviewFilter): Promise<TrustReview>;
+ explain(query: string, source: string | null): Promise<TrustExplanation[]>;
+ preview(input: OwnerActionInput): Promise<OwnerActionPreview>;
+ apply(input: OwnerActionInput, binding: string, confirmed: boolean): Promise<OwnerActionResult>;
+}
+
+export function localTrustBackend(engine: BrainEngine, config?: GBrainConfig): TrustBackend {
+ let principal: Promise<Principal> | undefined;
+ const by = () => (principal ??= maintenanceAttribution(engine).then(a => a.principal));
+ return {
+ review: filter => buildTrustReview(engine, filter),
+ explain: (query, source) => explainTrust(engine, query, { source }),
+ preview: input => previewOwnerAction(engine, input),
+ apply: async (input, binding, confirmed) => applyOwnerAction(engine, input, {
+ binding, confirmation: confirmed ? { via: 'tty' } : null, by: await by(), ...(config ? { config } : {}),
+ }),
+ };
+}
+
+const OWNER_SUBCOMMANDS = ['review', 'confirm', 'release', 'drop', 'revert', 'explain', 'allow', 'disable'] as const;
+export const isTrustOwnerSubcommand = (sub: string | undefined): boolean => (OWNER_SUBCOMMANDS as readonly string[]).includes(sub ?? '');
+
+function flag(args: string[], name: string): string | undefined {
+ const at = args.indexOf(name);
+ if (at < 0) return undefined;
+ const value = args[at + 1];
+ if (value === undefined || value.startsWith('--')) throw opError('invalid_params', `${name} needs a value.`, `Pass ${name} <value>; gbrain trust --help shows the forms.`);
+ return value;
+}
+const VALUE_FLAGS = ['--from', '--kind', '--since', '--source', '--version', '--uri-prefix', '--reason-family', '--reason', '--remove'];
+function positionals(args: string[]): string[] {
+ const out: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ if (VALUE_FLAGS.includes(args[i]!)) { i++; continue; }
+ if (!args[i]!.startsWith('--')) out.push(args[i]!);
+ }
+ return out;
+}
+
+function reviewFilter(args: string[]): TrustReviewFilter {
+ const from = flag(args, '--from');
+ const kind = flag(args, '--kind');
+ const since = flag(args, '--since');
+ return { ...(from ? { sourceId: from } : {}), ...(kind ? { kind: parseTrustReviewKind(kind) } : {}), ...(since ? { since: parseTrustSince(since) } : {}) };
+}
+
+function actionInput(sub: string, args: string[]): OwnerActionInput {
+ const [ref] = positionals(args);
+ const source = flag(args, '--source') ?? null;
+ if (sub === 'allow') {
+ const remove = flag(args, '--remove');
+ if (remove) return { action: 'allow_remove', ref: remove };
+ return { action: 'allow', source, uri_prefix: flag(args, '--uri-prefix') ?? null, reason_family: flag(args, '--reason-family') ?? null, reason: flag(args, '--reason') ?? null };
+ }
+ if (sub === 'disable') {
+ if (!args.includes('--all')) throw opError('invalid_params', 'trust disable needs --all.', 'Run gbrain trust disable --all (or --all --undo to turn the protections back on).');
+ return { action: args.includes('--undo') ? 'enable' : 'disable' };
+ }
+ if (!ref) throw opError('invalid_params', `trust ${sub} needs a ref.`, 'Pass a ref such as f12, h4, tp7 or p:default/notes/alice-example; gbrain trust review lists them.');
+ const version = flag(args, '--version');
+ if (version !== undefined && !/^\d{1,18}$/.test(version)) throw opError('invalid_params', '--version takes a version id.', 'gbrain history with the page slug lists its version ids.');
+ return { action: sub as OwnerActionInput['action'], ref, source, ...(version ? { version: Number(version) } : {}) };
+}
+
+const LOCAL_CTX = { remote: false } as OperationContext;
+
+/** One owner action: preview, typed confirmation when it raises trust, then apply bound to the preview. */
+export async function runOwnerAction(backend: TrustBackend, input: OwnerActionInput): Promise<{ preview: OwnerActionPreview; result: OwnerActionResult }> {
+ const preview = await backend.preview(input);
+ if (preview.raises) await requireOwnerConfirmation(LOCAL_CTX, { ref: preview.ref, token: preview.token, summary: preview.summary, command: preview.command });
+ return { preview, result: await backend.apply(input, preview.binding, preview.raises) };
+}
+
+function resultLine(r: OwnerActionResult): string {
+ const tier = r.tier ? ` (now "${trustLabel(r.tier)}"${r.prior_tier && r.prior_tier !== r.tier ? `, was "${trustLabel(r.prior_tier)}"` : ''})` : '';
+ return `${r.ref}: ${r.status}${tier}`;
+}
+
+/** DX-15: accept every matching item after one typed confirmation. */
+async function acceptAll(backend: TrustBackend, args: string[], json: boolean): Promise<void> {
+ const filter = reviewFilter(args);
+ if (!filter.sourceId && !filter.kind && !filter.since) {
+ throw opError('invalid_params', 'review --accept-all needs at least one filter: --from <source>, --kind <kind> or --since <when>.',
+ 'Narrow it first, e.g. gbrain trust review --accept-all --from default --since 7d; run gbrain trust review to see what would match.');
+ }
+ const review = await backend.review(filter);
+ const inputs = review.items.map(item => ({ action: item.kind === 'hold' ? 'release' : 'confirm', ref: item.ref, source: item.source_id } as OwnerActionInput));
+ if (inputs.length === 0) {
+ if (json) await writeStdoutFinal(`${JSON.stringify({ accepted: [], skipped: [] }, null, 2)}\n`); else console.log('Nothing matches those filters.');
+ return;
+ }
+ const previews = await Promise.all(inputs.map(input => backend.preview(input)));
+ const command = ['gbrain', 'trust', 'review', '--accept-all', ...args.filter(a => a !== '--accept-all' && a !== '--json')];
+ const token = `all-${createHash('sha256').update(previews.map(p => `${p.ref}:${p.binding}`).join('\n')).digest('hex').slice(0, 8)}`;
+ const summary = [`Accept ${previews.length} item(s):`, ...previews.map(p => ` ${p.ref.padEnd(6)} ${p.summary}`)].join('\n');
+ await requireOwnerConfirmation(LOCAL_CTX, { ref: `${previews.length} items`, token, summary, command });
+ const accepted: OwnerActionResult[] = [];
+ const failed: Array<{ ref: string; error: unknown }> = [];
+ for (let i = 0; i < inputs.length; i++) {
+ try { accepted.push(await backend.apply(inputs[i]!, previews[i]!.binding, previews[i]!.raises)); }
+ catch (error) { failed.push({ ref: previews[i]!.ref, error: error instanceof OperationError ? error.toJSON() : String(error) }); }
+ }
+ if (json) await writeStdoutFinal(`${JSON.stringify({ accepted, failed }, null, 2)}\n`);
+ else {
+ for (const r of accepted) console.log(resultLine(r));
+ for (const f of failed) console.log(`${f.ref}: not applied (${(f.error as { message?: string }).message ?? String(f.error)})`);
+ }
+ if (failed.length) setCliExitVerdict(1);
+}
+
+/** Renders a refusal through the shared CLI envelope with its contract exit code (3 for consent refusals). */
+export async function reportTrustCliError(error: unknown, json: boolean): Promise<boolean> {
+ if (error instanceof OperationError && !error.writeRequest) {
+ setCliExitVerdict(writeCliError(error, 'trust', { json }));
+ return true;
+ }
+ return reportPersistenceCliError(error, json);
+}
+
+/** Runs one owner subcommand against `backend`. Errors render through the shared CLI error envelope. */
+export async function runTrustOwnerCommand(backend: TrustBackend, sub: string, args: string[]): Promise<void> {
+ const json = jsonRequested(args);
+ try {
+ if (sub === 'review') {
+ if (args.includes('--accept-all')) return await acceptAll(backend, args, json);
+ const review = await backend.review(reviewFilter(args));
+ if (json) await writeStdoutFinal(`${JSON.stringify(review, null, 2)}\n`); else console.log(renderTrustReview(review));
+ return;
+ }
+ if (sub === 'explain') {
+ const query = positionals(args).join(' ');
+ if (!query) throw opError('invalid_params', 'trust explain needs a ref or a phrase.', 'Pass a ref such as f12, t3, h4, tp7 or p:default/notes/alice-example, or words from a page title or fact.');
+ const items = await backend.explain(query, flag(args, '--source') ?? null);
+ if (json) await writeStdoutFinal(`${JSON.stringify({ items }, null, 2)}\n`); else console.log(renderTrustExplanation(items));
+ return;
+ }
+ const { preview, result } = await runOwnerAction(backend, actionInput(sub, args));
+ if (json) await writeStdoutFinal(`${JSON.stringify({ preview: { ...preview, binding: undefined }, result }, null, 2)}\n`);
+ else console.log(resultLine(result));
+ } catch (error) {
+ if (await reportTrustCliError(error, json)) return;
+ throw error;
+ }
+}
+
+/**
+ * DX-2: while a resident serve holds a PGLite brain, run the owner
+ * subcommand through its administration socket. False when no resident owner
+ * holds the brain (the caller connects normally).
+ */
+export async function maybeDelegateTrust(hostConfig: GBrainConfig | null, args: string[]): Promise<boolean> {
+ const [sub, ...rest] = args;
+ if (!isTrustOwnerSubcommand(sub) || args.includes('--help') || args.includes('-h')) return false;
+ const { resolveBrainId } = await import('../core/brain-resolver.ts');
+ const { getCliOptions } = await import('../core/cli-options.ts');
+ const { loadMounts } = await import('../core/brain-registry.ts');
+ const { maybeDelegateLocalAdministration, persistenceConfigForBrain } = await import('../core/persistence/local-client.ts');
+ const { inspectLockHolder } = await import('../core/pglite-lock.ts');
+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());
+ const config = persistenceConfigForBrain(hostConfig, brainId, brainId === 'host' ? [] : loadMounts());
+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;
+ const call = async (operation: 'trust_read' | 'trust_preview' | 'trust_apply', params: Record<string, unknown>): Promise<Record<string, unknown>> => {
+ const delegated = await maybeDelegateLocalAdministration(operation, params, config);
+ if (!delegated.handled) throw opError('owner_unavailable', 'The running serve stopped before the trust action; nothing was changed.', 'Run the same command again.');
+ return delegated.result as Record<string, unknown>;
+ };
+ const backend: TrustBackend = {
+ review: async filter => await call('trust_read', { view: 'review', filter: { source: filter.sourceId, kind: filter.kind, since: filter.since?.toISOString() } }) as unknown as TrustReview,
+ explain: async (query, source) => (await call('trust_read', { view: 'explain', query, source })).items as TrustExplanation[],
+ preview: async input => await call('trust_preview', { input }) as unknown as OwnerActionPreview,
+ apply: async (input, binding, confirmed) => await call('trust_apply', { input, binding, ...(confirmed ? { confirmed: 'tty' } : {}) }) as unknown as OwnerActionResult,
+ };
+ await runTrustOwnerCommand(backend, sub!, rest);
+ return true;
+}
+
+/**
+ * DX-7 / CEO-9 for `gbrain decide proposals accept`: an S9 proposal whose new
+ * fact is less trusted than the fact it supersedes raises trust over the old
+ * row, so accepting it needs the owner's typed confirmation (one prompt for a
+ * batch). Proposals that cross no tier return without a prompt and keep
+ * today's path. Throws `confirmation_required` (non-TTY) or `insufficient_scope`.
+ */
+export async function confirmTierCrossingAccepts(engine: BrainEngine, ids: readonly number[], command: string[]): Promise<number[]> {
+ if (ids.length === 0) return [];
+ const { compareTrust, storedTrustTier } = await import('../core/trust/tier.ts');
+ const rows = await engine.executeRaw<{ id: number; new_tier: string; old_tier: string }>(
+ `SELECT p.id, nf.trust_tier AS new_tier, xf.trust_tier AS old_tier FROM decide_proposals p
+ JOIN facts nf ON nf.id = p.new_fact_id JOIN facts xf ON xf.id = p.old_fact_id
+ WHERE p.id = ANY($1::bigint[]) AND p.status = 'pending' ORDER BY p.id`, [[...ids]]);
+ const crossing = rows.filter(r => compareTrust(storedTrustTier(r.new_tier), storedTrustTier(r.old_tier)) < 0);
+ if (crossing.length === 0) return [];
+ const refs = crossing.map(r => `#${Number(r.id)}`);
+ console.error(`[decide] accepting ${refs.join(', ')} lets a less trusted fact supersede a more trusted one; the same check as gbrain trust confirm applies (gbrain trust review lists every trust decision).`);
+ const token = crossing.length === 1 ? `s9-${Number(crossing[0]!.id)}` : `s9-${createHash('sha256').update(refs.join(',')).digest('hex').slice(0, 8)}`;
+ await requireOwnerConfirmation(LOCAL_CTX, {
+ ref: refs.join(', '), token, command: command.filter(a => a !== '--yes' && a !== '--json'),
+ summary: crossing.map(r => `Accept ${`#${Number(r.id)}`}: a "${trustLabel(storedTrustTier(r.new_tier))}" fact supersedes a "${trustLabel(storedTrustTier(r.old_tier))}" one`).join('\n'),
+ });
+ return crossing.map(r => Number(r.id));
+}
diff --cc src/core/facts/single-prepare.ts
index 5d15198863,9d4ae34443..8c4cfdf45c
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@@ -44,8 -44,8 +44,8 @@@ export async function decideSingleFact(
if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };
if (embedding && input.entity_slug) {
const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, embeddingModel, k: 5, attributedTo: input.attributed_to ?? null });
- const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null; trust_tier: string | null }>(
- const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null }>(
- 'SELECT id,source_markdown_slug,row_num FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
++ const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null; trust_tier: FactRow['trust_tier'] }>(
+ 'SELECT id,source_markdown_slug,row_num,trust_tier FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
[sourceId, candidates.map(c => c.id)]);
let candidate: FactCandidate | null = null;
let score = -1;
diff --cc src/core/persistence/memory-prepare.ts
index 9a381e1501,84bf8863fc..4107a0ea65
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@@ -16,13 -16,9 +16,15 @@@ import type { WriteRequest } from './mo
import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';
import { inferenceNote } from '../facts/subject-infer-write.ts';
import { normalizeTargetFences } from '../fence-repair/import-step.ts';
+import { requestChannelTrust } from '../trust/channel.ts';
+import { gateField, gateInput, heldOutcome, loadWriteGateConfig } from '../trust/gate-outcomes.ts';
+import { decideFactWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';
+import { writeGateRejectedError } from '../write-gate.ts';
+import { recordContestedFact, supersessionGuarded } from '../trust/supersede-handlers.ts';
+import { storedTrustTier } from '../trust/tier.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
+ import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';
+ import { withPageTierKept } from '../trust/fence-append.ts';
function receiptFix(row: WriteRequest): Action {
return row.principal_kind === 'local_cli'
diff --cc src/core/schema-migrations/registry.generated.ts
index 330c28ae5a,2aad413601..4b64f4a105
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -223,7 -223,7 +223,8 @@@ import { v219 } from './v219-pages-reco
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';
+ import { v234 } from './v234-trust-generation.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -445,5 -445,5 +446,6 @@@ export const MIGRATIONS: Migration[] =
v230,
v231,
v232,
+ v233,
+ v234,
];
diff --cc test/graduation-inventory.test.ts
index 80d8907031,3af20cd821..e2207be0f4
--- 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: 119, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });
- expect(counts).toEqual({ carry: 118, rebind: 2, rebuild: 2, discard: 6, schema_owned: 4 });
++ expect(counts).toEqual({ carry: 119, rebind: 2, rebuild: 2, discard: 6, schema_owned: 4 });
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 });