Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(find_contradictions): scoped readers get findings re-read live (D9)
garrytane8e7db441adc
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 73a62000a5..704fd9f613 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -88,7 +88,7 @@ Every non-localOnly operation on the MCP surface: 151 tools across 25 areas. **S| Tool | Description | Scope | Starter | Gate ||---|---|---|---|---|| `find_anomalies` | Anomalies in recent page activity, grouped by cohort (tag or type) against a baseline. | read | yes | |-| `find_contradictions` | Stored contradiction reports are temporarily available only to trusted local callers without a source filter. | read | | |+| `find_contradictions` | Return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. | read | | || `find_experts` | Answers 'who in my brain knows about <topic>'. | read | | || `find_trajectory` | Return the chronological claim trajectory for an entity (typed metric values over time, plus auto-detected regressions and narrative drift). | read | | || `get_calibration_profile` | Read the active calibration profile for a holder. | read | | |diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex df3c60b2d6..5e5e050aa9 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval-replay.ts` — contributor-facing replay tool. Reads NDJSON from `gbrain eval export`, re-runs each captured `query` / `search` op against the current brain, computes set-Jaccard@k between captured + current `retrieved_slugs`, top-1 stability rate, and latency Δ. Stable JSON shape (`schema_version: 1`) for CI gating; human mode prints a regression table. Pure Bun, zero new deps. The dev-loop half of BrainBench-Real. See `docs/eval-bench.md`. `parseNdjson` skips lines where `_kind === 'baseline_metadata'` so `gbrain bench publish` baselines parse cleanly without the metadata header polluting row counts. Exports `replayCore(engine, opts): Promise<{summary, results}>` + `ReplaySummary` type so `gbrain eval gate` calls replay in-process (NOT subprocess — avoids gbrain-version-drift for source-tree CI). CLI `runEvalReplay` wraps `replayCore`. D2: under the `--json` guard the result is one compact NDJSON line (`writeJsonLine`; unguarded callers keep the pretty document) and failures end with a `{status:'error'}` envelope line (`invalid_params` exit 2, `not_found`, `parse_error`). `eval gate` follows the same contract; a breached gate is the result line then a `gate_failed` error line (exit 1).-- `src/commands/eval-suspected-contradictions.ts` + `src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession}.ts` — `gbrain eval suspected-contradictions [run|trend|review]`. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on `(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)` (prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage with `small_sample_note` when n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes to `eval_contradictions_runs`, source-tier breakdown reuses `DEFAULT_SOURCE_BOOSTS` prefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic via `judgeFn` + `searchFn` DI in the runner; never touches the real gateway in tests. Engine surface: `BrainEngine.listActiveTakesForPages` (batched), `writeContradictionsRun` + `loadContradictionsTrend`, `getContradictionCacheEntry` + `putContradictionCacheEntry` + `sweepContradictionCache`. Schema migrations v51 + v52. Pair members carry only content effective dates; a `fallback` date becomes null (`(date unknown)`). MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only; stored reports answer only trusted local callers without a user-selected source, keyed on `ctx.localSourceImplicit` from `makeContext`). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them into `buildSynthesisPrompt` as an informational block. Architecture doc: `docs/contradictions.md`.+- `src/commands/eval-suspected-contradictions.ts` + `src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession,scoped-read}.ts` — `gbrain eval suspected-contradictions [run|trend|review]`. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on `(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)` (prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage with `small_sample_note` when n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes to `eval_contradictions_runs`, source-tier breakdown reuses `DEFAULT_SOURCE_BOOSTS` prefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic via `judgeFn` + `searchFn` DI in the runner; never touches the real gateway in tests. Engine surface: `BrainEngine.listActiveTakesForPages` (batched), `writeContradictionsRun` + `loadContradictionsTrend`, `getContradictionCacheEntry` + `putContradictionCacheEntry` + `sweepContradictionCache`. Schema migrations v51 + v52. Pair members carry only content effective dates; a `fallback` date becomes null (`(date unknown)`). MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only; the stored report as written answers only trusted local callers without a user-selected source or trust floor, keyed on `ctx.localSourceImplicit` from `makeContext`; every other caller goes through `scoped-read.ts` `resolveScopedFindings`, which re-reads each side by chunk or take id under `pageReadFilter(live)`, current text projection, safe chunks, holder allow-list and floor, drops a finding unless both sides are visible and unchanged, rebuilds the resolution command from live rows and withholds a supersede of a higher-trust take). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them into `buildSynthesisPrompt` as an informational block. Architecture doc: `docs/contradictions.md`.- `src/commands/eval-trajectory.ts` + `src/commands/founder-scorecard.ts` + `src/core/trajectory.ts` — temporal trajectory + founder scorecard. `gbrain eval trajectory <entity>` shows the chronological typed-claim history (mrr/arr/team_size/etc) with regressions auto-flagged inline; `gbrain founder scorecard <entity>` rolls up claim_accuracy / consistency / growth_trajectory / red_flags into one JSON. Pure-function math in `trajectory.ts`: `detectRegressions(points, threshold)` walks consecutive metric-value pairs per metric (10% drop default, env override `GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD`); `computeDriftScore(points)` returns `1 - mean(cosine(emb[i], emb[i-1]))` over existing embeddings (null when <3 embedded points). Backed by `BrainEngine.findTrajectory(opts)` — both Postgres and PGLite, single SQL query that selects the NEWEST `limit` points (`ORDER BY valid_from DESC, id DESC`) and returns them chronologically, so a capped series keeps its latest value. Source-scoped via the `sourceId` scalar / `sourceIds` array dual pattern; visibility-filtered for remote callers. MCP op `find_trajectory` (read scope, NOT localOnly) registered after `find_experts`. Migration v67 adds optional typed-claim columns (`claim_metric`, `claim_value`, `claim_unit`, `claim_period`) + a partial index on `(entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL`. Fence widens from 10 to 14 cells when any row has typed data; renderer stays at 10 cells when none do (no churn diff on existing fences). Metric labels normalize to lowercase snake_case via `normalizeMetricLabel` (15-entry seed map). The `consolidate` cycle phase does semantic upsert keyed on `(page_id, claim, since_date)` (so re-running the cycle after `extract_facts` clears `consolidated_at` cannot append duplicates via `MAX(row_num)+1`) and writes chronological `valid_until` on each cluster's older facts. The `extract_facts` cycle phase batch-embeds via `gateway.embed()` before insert AND threads `pages.effective_date` as the `pageEffectiveDate` fallback for `valid_from` (precedence: fence-row > pageEffectiveDate > now()). The contradiction probe MUST NOT write `valid_until` — grep guard at `test/eval-contradictions/no-valid-until-write.test.ts`. Haiku extraction lives in `src/core/facts/extract.ts` (not the `extract-facts.ts` cycle phase); its output cap is config `facts.extraction_max_tokens` (default 4000), a `stopReason: 'length'` response retries once at 2× the cap, and persistent truncation warns loudly on stderr instead of silently extracting zero facts. Mixed extractor arrays salvage valid candidates and warn with the dropped malformed count; all-malformed output still fails retryably, while an explicitly empty facts array remains a successful empty result. `pageEffectiveDate` is OPTIONAL because `fence-write.ts` callers have no Page object. Migration v89 adds a nullable `event_type TEXT` column on `facts` so the substrate carries event-shaped rows (`event_type='meeting'` / `'job_change'` / `'location_change'`) alongside metric rows. `TrajectoryPoint.event_type: string | null` projected by both engines. `TrajectoryOpts.kind?: 'metric' | 'event' | 'all'` filter (default `'all'`); `founder-scorecard` + `eval-trajectory` pass `kind: 'metric'` explicitly. Back-compat pinned by `test/regressions/v0_40_2_0-trajectory-backcompat.test.ts` (byte-identical `computeFounderScorecard` + `computeTrajectoryStats` with and without event rows); engine parity in `test/engine-parity-event-type.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 4582fccc17..09c5b15ce4 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -37,7 +37,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`). `enforceSubagentSlugFence` stays fail-closed on a missing `subagentId`; its one exception (#5994) is a failed-writes replay whose `replayAuthority` is restricted and whose allow-list equals the stored non-empty `delegatedPrefixes` exactly, and the slug must still match it. `isOpPageSlug` is the `validatePageSlug` grammar as a predicate; page-prepare's `prepareFileTarget` returns no file for a slug outside it, so an admitted legacy row publishes database-only and never removes a file its stale `source_uri`/`source_path` names (#6212).-- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.+- `src/core/ops/insights.ts` — `find_contradictions` (`filtered`, takes `min_trust`) returns the stored report as written only to explicitly trusted, unscoped, unfloored local callers. Remote, source-scoped and floored callers get `eval-contradictions/scoped-read.ts` findings (both sides re-read live, `total_visible` instead of the run total); a remote context with no source scope gets an empty list and a note. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.diff --git a/docs/contradictions.md b/docs/contradictions.mdindex 500550f287..95edb4524a 100644--- a/docs/contradictions.md+++ b/docs/contradictions.md@@ -149,13 +149,21 @@ pay near-zero on re-runs (until you bump PROMPT_VERSION).- Probe never mutates the brain. Runs only read pages/takes/chunks.Writes go only to `eval_contradictions_runs` and `eval_contradictions_cache`.- `find_contradictions` is read-scope and is not in the subagent allowlist.- Stored reports are temporarily available only to trusted local callers- without a source filter. The bare local `gbrain find-contradictions` reads- the latest run: a source the CLI resolved by default (no `--source`,- `GBRAIN_SOURCE` or `.gbrain-source`) is not a filter. Remote or- source-scoped callers receive- `{ contradictions: [], note }` with an availability note; their requests- do not load the stored report.+ The bare local `gbrain find-contradictions` reads the latest run as stored:+ a source the CLI resolved by default (no `--source`, `GBRAIN_SOURCE` or+ `.gbrain-source`) is not a filter.+- A stored report has no source column and copies both sides' text, private+ takes included. So a remote, source-scoped or `min_trust` caller never gets+ stored text: each side is re-read live by its chunk or take id under the+ caller's policy (source scope, page visibility, live page and source,+ quarantine, current text, safe chunks for remote callers, the takes holder+ allow-list and the trust floor). A finding is returned only when both sides+ are readable and still read exactly as judged, so its axis never describes+ text the caller cannot see. Each side carries `source_id`, `trust_tier` and+ `origin`, the resolution command is rebuilt from the live rows, and the+ response carries `total_visible` instead of the run total. A supersede+ proposal that would let a lower-trust side replace a higher-trust take is+ returned as a manual review with `supersede_withheld: "higher_trust_target"`.- Build-fixture script is local-only. The redactor + `isCleanForCommit`gate makes accidental private-data commits hard, but the operator MUSTinspect every redaction before commit.diff --git a/docs/integrations/qm-harness.md b/docs/integrations/qm-harness.mdindex 37c76835fd..aad0200c56 100644--- a/docs/integrations/qm-harness.md+++ b/docs/integrations/qm-harness.md@@ -87,10 +87,10 @@ boundary, and it does not make every side effect prefix-clean:page content. Unreachable in the layout above (the `agents` source ispath-less and holds no code pages); it applies only if you point employeewrites at a code-synced source.-- **Stored contradiction reports are temporarily local-only.**- `find_contradictions` returns stored findings only to trusted local callers- without a source filter. Harness clients receive `{ contradictions: [], note }`- with an availability note. Other brain-wide read ops (`get_recent_salience`,+- **Stored contradiction findings are filtered per caller.**+ `find_contradictions` returns a harness client only the findings whose two+ sides it can read in its grant, re-read live with `source_id` and+ `trust_tier`; stored report text never leaves. Other brain-wide read ops (`get_recent_salience`,`find_anomalies`, and `sources_list`/`sources_status`) honor the federatedgrant; `sources_status` answers `not_found` for an out-of-grant ID.- **Reads touch `last_retrieved_at`** (in `page_retrievals`) on the pages they return, includingdiff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.mdindex ce5dd776b8..b15bf54189 100644--- a/docs/operations/mcp-surface-runbook.md+++ b/docs/operations/mcp-surface-runbook.md@@ -242,9 +242,10 @@ than take-driven salience touches.Semantic result caching is temporarily disabled even when configuration enablesit. Searches run fresh, so repeated requests may cost more and take longer.-Stored rows and cache maintenance remain available. Stored contradiction reports-are temporarily available only to trusted local callers without a source filter;-other callers receive an empty list and an availability note.+Stored rows and cache maintenance remain available. Remote callers of+`find_contradictions` get only findings whose two sides they can read now, each+side re-read live with its source and trust tier; stored report text never+leaves (docs/contradictions.md, "Trust posture").## Served instruction settingsdiff --git a/src/core/eligibility/registry.ts b/src/core/eligibility/registry.tsindex 540a577a4d..4c2430d5d7 100644--- a/src/core/eligibility/registry.ts+++ b/src/core/eligibility/registry.ts@@ -37,7 +37,7 @@ export const OP_READ_TRUST: Readonly<Record<string, ReadTrustHandling>> = {wanted_pages: 'labeled', get_tags: 'labeled', get_ingest_log: 'labeled',chronicle_day: 'labeled', chronicle_on_this_day: 'labeled', chronicle_since: 'labeled', chronicle_last_seen: 'labeled',ontology_get: 'labeled', ontology_dimensions: 'labeled', ontology_conflicts: 'labeled', volunteer_chronicle: 'labeled',- extraction_pending: 'labeled', entity_identity_list: 'labeled', find_contradictions: 'labeled',+ extraction_pending: 'labeled', entity_identity_list: 'labeled', find_contradictions: 'filtered',find_experts: 'labeled', find_trajectory: 'labeled', takes_scorecard: 'labeled', takes_calibration: 'labeled',open_loops: 'labeled', schema_review_orphans: 'labeled',questions_list: 'labeled', questions_status: 'labeled',diff --git a/src/core/eval-contradictions/scoped-read.ts b/src/core/eval-contradictions/scoped-read.tsnew file mode 100644index 0000000000..8f274ef007--- /dev/null+++ b/src/core/eval-contradictions/scoped-read.ts@@ -0,0 +1,158 @@+/**+ * D9: stored contradiction findings for a scoped reader (remote, source-scoped+ * or under a trust floor).+ *+ * A stored probe report carries no source identity and copies both sides'+ * text verbatim, private takes and sealed fence rows included, and its+ * resolution commands can quote a take claim. None of that is returned here.+ * Each side is re-read live by its global id (chunk or take) under the+ * caller's read policy: source scope, page visibility, live and unarchived+ * source, quarantine, current text projection, safe chunks for untrusted+ * callers, the takes holder allow-list and the trust floor. A finding survives+ * only when both sides are visible and both still read exactly as judged, so+ * its axis never describes text the caller cannot see. Text, source identity,+ * trust labels and the resolution command all come from the live rows.+ */+import type { BrainEngine } from '../engine.ts';+import { parseDateLoose } from '../effective-date.ts';+import { projectionEligibleSql } from '../eligibility/sql.ts';+import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';+import type { Contested } from '../eligibility/labels.ts';+import { pageReadFilter } from '../search/read-policy-sql.ts';+import { currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';+import { admitsTrust, compareTrust, storedTrustTier, type TrustTier } from '../trust/tier.ts';+import type { PageReadPolicy } from '../types.ts';+import { renderResolutionCommand } from './auto-supersession.ts';+import type { ContradictionFinding, PairMember } from './types.ts';++export interface ScopedMember extends PairMember {+ source_id: string;+ trust_tier: TrustTier;+ origin: string;+ unconfirmed?: true;+ contested?: Contested;+}++export interface ScopedFinding extends Omit<ContradictionFinding, 'a' | 'b' | 'combined_score'> {+ a: ScopedMember;+ b: ScopedMember;+ /** Set when the stored proposal would let the lower-trust side supersede a higher-trust take; the command is then a manual review. */+ supersede_withheld?: 'higher_trust_target';+}++interface Labels { trust_tier: TrustTier; origin: string; unconfirmed?: true; contested?: Contested }+interface LiveChunk { id: number; page_id: number; slug: string; source_id: string; chunk_text: string }+interface LiveTake { id: number; page_id: number; slug: string; source_id: string; row_num: number; claim: string; holder: string }+type LabeledChunk = LiveChunk & Labels & { judged_text: string };+type LabeledTake = LiveTake & Labels;++const finiteIds = (values: Array<number | null | undefined>) =>+ [...new Set(values.map(Number).filter(n => Number.isSafeInteger(n) && n > 0))];++async function loadChunks(engine: Pick<BrainEngine, 'executeRaw'>, ids: number[], policy: PageReadPolicy, floor: TrustTier | undefined) {+ if (!ids.length) return new Map<number, LabeledChunk>();+ const params: unknown[] = [ids];+ const pageSql = pageReadFilter('p', { ...policy, ...(floor ? { minTrust: floor } : {}) }, params, true);+ const safe = requiresSafeChunks(policy) ? ` AND ${safeChunksFilter('p')}` : '';+ const rows = await engine.executeRaw<LiveChunk>(+ `SELECT cc.id, cc.page_id, cc.chunk_text, p.slug, p.source_id+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.id = ANY($1::int[]) AND ${pageSql} AND ${currentTextProjectionFilter('p')}${safe}`, params);+ const live = rows.map(r => ({ ...r, id: Number(r.id), page_id: Number(r.page_id), judged_text: r.chunk_text } as LiveChunk & { judged_text: string; trust_tier?: string; origin?: string; unconfirmed?: true; contested?: Contested }));+ const stamped = await stampPageTrust(engine, live, floor);+ return new Map(stamped.map((r): [number, LabeledChunk] => [r.id, { ...r, trust_tier: storedTrustTier(r.trust_tier), origin: r.origin ?? 'unrecorded' }]));+}++async function loadTakes(engine: Pick<BrainEngine, 'executeRaw'>, ids: number[], policy: PageReadPolicy, floor: TrustTier | undefined) {+ if (!ids.length) return new Map<number, LabeledTake>();+ const params: unknown[] = [ids];+ const pageSql = pageReadFilter('p', policy, params, true);+ let holderSql = '';+ if (policy.takesHoldersAllowList !== undefined) {+ params.push(policy.takesHoldersAllowList);+ holderSql = ` AND t.holder = ANY($${params.length}::text[])`;+ }+ const rows = await engine.executeRaw<LiveTake>(+ `SELECT t.id, t.page_id, t.row_num, t.claim, t.holder, p.slug, p.source_id+ FROM takes t JOIN pages p ON p.id = t.page_id+ WHERE t.id = ANY($1::bigint[]) AND t.active AND ${pageSql}${holderSql}+ AND ${projectionEligibleSql('takes', 't', floor ? { floor } : undefined)}`, params);+ const stamped = await stampRowTrust(engine, 'takes', rows.map(r => ({ ...r, id: Number(r.id), page_id: Number(r.page_id), row_num: Number(r.row_num) })), r => r.id);+ return new Map(stamped+ .map((r): LabeledTake => ({ ...r, trust_tier: storedTrustTier(r.trust_tier) }))+ .filter(r => !floor || admitsTrust(r.trust_tier, floor))+ .map((r): [number, LabeledTake] => [r.id, r]));+}++/**+ * The side a supersede proposal would replace, and the side whose content+ * would replace it; null when the command supersedes nothing.+ */+function supersedeSides(f: ScopedFinding): { target: ScopedMember; winner: ScopedMember } | null {+ if (f.resolution_kind === 'takes_supersede') {+ const target = f.b.take_id !== null ? f.b : f.a.take_id !== null ? f.a : null;+ return target ? { target, winner: target === f.a ? f.b : f.a } : null;+ }+ if (f.resolution_kind !== 'temporal_supersede') return null;+ const aMs = parseDateLoose(f.a.effective_date)?.getTime();+ const bMs = parseDateLoose(f.b.effective_date)?.getTime();+ if (aMs === undefined || bMs === undefined || aMs === bMs) return null;+ const [older, newer] = aMs < bMs ? [f.a, f.b] : [f.b, f.a];+ return older.take_id !== null ? { target: older, winner: newer } : null;+}++/** Resolve stored findings for a scoped reader; findings with a hidden, missing or changed side are dropped. */+export async function resolveScopedFindings(+ engine: Pick<BrainEngine, 'executeRaw'>,+ findings: ContradictionFinding[],+ policy: PageReadPolicy,+ floor: TrustTier | undefined,+): Promise<ScopedFinding[]> {+ const members = findings.flatMap(f => [f.a, f.b]);+ const [chunks, takes] = await Promise.all([+ loadChunks(engine, finiteIds(members.filter(m => m?.take_id == null).map(m => m?.chunk_id)), policy, floor),+ loadTakes(engine, finiteIds(members.map(m => m?.take_id)), policy, floor),+ ]);++ const live = (m: PairMember | undefined): ScopedMember | null => {+ if (!m) return null;+ const labels = (r: Labels) => ({+ trust_tier: r.trust_tier, origin: r.origin,+ ...(r.unconfirmed ? { unconfirmed: true as const } : {}),+ ...(r.contested ? { contested: r.contested } : {}),+ });+ if (m.take_id != null) {+ const t = takes.get(Number(m.take_id));+ if (!t || t.slug !== m.slug || t.claim !== m.text || (m.take_row_num != null && t.row_num !== Number(m.take_row_num))) return null;+ return {+ ...m, slug: t.slug, source_id: t.source_id, chunk_id: null, take_id: t.id, take_row_num: t.row_num,+ holder: t.holder, text: t.claim, ...labels(t),+ };+ }+ const c = m.chunk_id != null ? chunks.get(Number(m.chunk_id)) : undefined;+ if (!c || c.slug !== m.slug || c.judged_text !== m.text) return null;+ return {+ ...m, slug: c.slug, source_id: c.source_id, chunk_id: c.id, take_id: null, take_row_num: null,+ holder: null, text: c.chunk_text, ...labels(c),+ };+ };++ const out: ScopedFinding[] = [];+ for (const f of findings) {+ const a = live(f.a);+ const b = live(f.b);+ if (!a || !b) continue;+ const scoped: ScopedFinding = {+ kind: f.kind, verdict: f.verdict, severity: f.severity, axis: f.axis, confidence: f.confidence,+ resolution_kind: f.resolution_kind, resolution_command: '', a, b,+ };+ const sides = supersedeSides(scoped);+ if (sides && compareTrust(sides.target.trust_tier, sides.winner.trust_tier) > 0) {+ scoped.resolution_kind = 'manual_review';+ scoped.supersede_withheld = 'higher_trust_target';+ }+ scoped.resolution_command = renderResolutionCommand({ kind: f.kind, a, b, combined_score: 0 }, scoped.resolution_kind);+ out.push(scoped);+ }+ return out;+}diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex cd9261ca40..cce35425f8 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -5416,7 +5416,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["mutating": false,"idempotent": true,"outputRedaction": "retrieval",- "description": "Stored contradiction reports are temporarily available only to trusted local callers without a source filter. Remote or source-scoped callers receive {contradictions: [], note} with an availability note. For eligible local callers, return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. An eligible read loads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.",+ "description": "Return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. Remote, source-scoped or min_trust callers get only findings whose two sides they can read now (each side re-read live, with source_id, trust_tier and origin) and total_visible instead of the run total. Reads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.","scope": "read","params": {"slug": {@@ -5435,6 +5435,19 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["limit": {"type": "number","description": "Max findings to return. Default 20."+ },+ "min_trust": {+ "type": "string",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "fullSurfaceOnly": true}},"cliHints": {diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 926fdc11c0..9c96426544 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -62,15 +62,15 @@ export const SEARCH_MATCH_DESCRIPTION = 'keyword: every match, paged.';// ──────────────────────────────────────────────────────────────────────────────export const FIND_CONTRADICTIONS_DESCRIPTION =- "Stored contradiction reports are temporarily available only to trusted local callers without a source filter. " +- "Remote or source-scoped callers receive {contradictions: [], note} with an availability note. " +- "For eligible local callers, return suspected-contradiction findings from the most recent " ++ "Return suspected-contradiction findings from the most recent " +"`gbrain eval suspected-contradictions` probe run, optionally filtered by slug " +"and/or severity. Use this when the user asks 'what's inconsistent in my " +"brain', 'show me contradictions about Acme', 'high-severity issues only', or " +"wants to act on the probe's findings without re-running it. Returns " +"{contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. " +- "An eligible read loads the stored run without triggering a new probe; users run " ++ "Remote, source-scoped or min_trust callers get only findings whose two sides they can read now " ++ "(each side re-read live, with source_id, trust_tier and origin) and total_visible instead of the run total. " ++ "Reads the stored run without triggering a new probe; users run " +"`gbrain eval suspected-contradictions` for that.";export const FIND_TRAJECTORY_DESCRIPTION =diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex b5e65d697c..b7654e6f20 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -9,13 +9,15 @@* it). Never import from '../operations.ts' here (cycle).*/-import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';+import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';+import { resolveScopedFindings } from '../eval-contradictions/scoped-read.ts';+import type { ProbeReport } from '../eval-contradictions/types.ts';import { proactiveEligibility } from '../eligibility/registry.ts';import { activationSuppressionNotice, suppressionSummary } from '../eligibility/activation.ts';import type { Operation } from './contract.ts';import { opError } from './contract.ts';import { invalidParam, paramUse } from './op-fix.ts';-import { sourceScopeOpts, readPolicyOpts } from './context.ts';+import { federatedSearchScope, sourceScopeOpts, readPolicyOpts } from './context.ts';import {FIND_EXPERTS_DESCRIPTION,FIND_CONTRADICTIONS_DESCRIPTION,@@ -203,7 +205,8 @@ const find_contradictions: Operation = {scope: 'read',// Reads eval_contradictions_runs.report_json for the latest run, then// filters in-memory by slug and severity. No new probe is triggered;- // the agent surfaces what's already on disk.+ // the agent surfaces what's already on disk. Scoped readers (remote,+ // source-scoped or floored) get each side re-read live (D9, scoped-read.ts).params: {slug: {type: 'string',@@ -218,6 +221,7 @@ const find_contradictions: Operation = {type: 'number',description: 'Max findings to return. Default 20.',},+ min_trust: MIN_TRUST_PARAM,},handler: async (ctx, p) => {const scope = sourceScopeOpts(ctx);@@ -225,8 +229,11 @@ const find_contradictions: Operation = {// select is not a filter, so the bare command reads the latest run.const sourceFiltered = scope.sourceIds !== undefined|| (scope.sourceId !== undefined && ctx.localSourceImplicit !== true);- if (ctx.remote !== false || sourceFiltered) {- return { contradictions: [], note: 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.' };+ const { floor } = await resolveReadEligibility(ctx, { minTrust: p.min_trust });+ const scoped = ctx.remote !== false || sourceFiltered || floor !== undefined;+ const readScope = ctx.remote === false && !sourceFiltered ? {} : federatedSearchScope(ctx);+ if (scoped && ctx.remote !== false && readScope.sourceId === undefined && readScope.sourceIds === undefined) {+ return { contradictions: [], note: 'This connection names no readable source, so no stored contradiction findings are returned.' };}const limit = typeof p.limit === 'number' && p.limit > 0 ? Math.min(p.limit, 100) : 20;@@ -239,23 +246,9 @@ const find_contradictions: Operation = {return { contradictions: [], note: 'No probe runs in the last 30 days; run `gbrain eval suspected-contradictions` first.' };}const latest = rows[0];- const report = latest.report_json as Record<string, unknown> | null;- const perQuery = (report?.per_query as Array<{- contradictions: Array<{- kind: string;- severity: 'low' | 'medium' | 'high';- axis: string;- confidence: number;- a: { slug: string; chunk_id: number | null; take_id: number | null };- b: { slug: string; chunk_id: number | null; take_id: number | null };- resolution_kind: string;- resolution_command: string;- }>;- }> | undefined) ?? [];- const allFindings = perQuery.flatMap((q) => q.contradictions);- // This branch is trusted and unscoped. Apply the requested display- // filters before the limit; source-scoped reports are unavailable above.- const matching = allFindings.filter((f) => {+ const report = latest.report_json as Partial<ProbeReport> | null;+ const allFindings = (report?.per_query ?? []).flatMap((q) => q.contradictions ?? []);+ const matches = (f: { severity: string; a: { slug: string }; b: { slug: string } }) => {if (sevFilter && f.severity !== sevFilter) return false;if (slugFilter) {const sA = f.a.slug.toLowerCase();@@ -263,8 +256,21 @@ const find_contradictions: Operation = {if (!sA.includes(slugFilter) && !sB.includes(slugFilter)) return false;}return true;- });- const kept = matching.slice(0, limit);+ };+ if (scoped) {+ // D9: every side is re-read live under the caller's policy; stored text,+ // totals and commands never leave for a scoped reader.+ const visible = (await resolveScopedFindings(ctx.engine, allFindings, await readPolicyOpts(ctx, readScope), floor)).filter(matches);+ return {+ run_id: latest.run_id,+ ran_at: latest.ran_at,+ contradictions: visible.slice(0, limit),+ total_visible: visible.length,+ };+ }+ // This branch is trusted, unscoped and unfloored. Apply the requested+ // display filters before the limit.+ const kept = allFindings.filter(matches).slice(0, limit);return {run_id: latest.run_id,ran_at: latest.ran_at,diff --git a/test/corrective-containment.test.ts b/test/corrective-containment.test.tsindex 18aa71cb6b..2b3b890598 100644--- a/test/corrective-containment.test.ts+++ b/test/corrective-containment.test.ts@@ -16,10 +16,11 @@ function context(engine: Partial<BrainEngine>, opts: Partial<OperationContext> =};}-const REPORT_NOTE = 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.';const auth = (allowedSources: string[]): NonNullable<OperationContext['auth']> => ({ token: 'fixture', clientId: 'example-client', scopes: ['read'], allowedSources });describe('stored contradiction report containment', () => {+ // D9: scoped readers re-read each side live (find-contradictions-scoped.test.ts);+ // a stored finding with no resolvable side never leaves.const deniedContexts: Array<[string, Partial<OperationContext>]> = [['remote', { remote: true }],['unset trust', { remote: undefined as unknown as boolean }],@@ -30,11 +31,16 @@ describe('stored contradiction report containment', () => {['federated grant wins over trusted all-sources sentinel', { sourceId: '__all__', auth: auth(['default']) }],];for (const [label, opts] of deniedContexts) {- test(`${label} returns the availability note before reading any reports`, async () => {- const load = mock(async () => { throw new Error('protected report must not be loaded'); });- const result = await operationsByName.find_contradictions.handler(context({ loadContradictionsTrend: load }, opts), {});- expect(result).toEqual({ contradictions: [], note: REPORT_NOTE });- expect(load).not.toHaveBeenCalled();+ test(`${label} never receives stored report text, totals or unresolvable findings`, async () => {+ const finding = { a: { slug: 'page-a', chunk_id: null, take_id: null }, b: { slug: 'page-b', chunk_id: null, take_id: null }, severity: 'high', axis: 'SCOPED_REPORT_SECRET' };+ const load = mock(async () => [{+ run_id: 'scoped-run', ran_at: '2026-09-01T00:00:00Z', report_json: { per_query: [{ query: 'SCOPED_QUERY_SECRET', contradictions: [finding] }] },+ }]);+ const result = await operationsByName.find_contradictions.handler(context({ loadContradictionsTrend: load as never }, opts), {}) as Record<string, unknown>;+ expect(result.contradictions).toEqual([]);+ expect(result).not.toHaveProperty('total_in_run');+ expect(JSON.stringify(result)).not.toContain('SCOPED_REPORT_SECRET');+ expect(JSON.stringify(result)).not.toContain('SCOPED_QUERY_SECRET');});}diff --git a/test/find-contradictions-cli-source.test.ts b/test/find-contradictions-cli-source.test.tsindex 9262aeaf24..f052f425a1 100644--- a/test/find-contradictions-cli-source.test.ts+++ b/test/find-contradictions-cli-source.test.ts@@ -6,7 +6,8 @@* back to 'default'), so the op's source-filter refusal fired for every local* CLI call. Driven through the real CLI seam (makeContext) so the implicit* source marker and the op handler are tested together; user-selected- * sources (--source, GBRAIN_SOURCE) still get the unavailable note.+ * sources (--source, GBRAIN_SOURCE) get the scoped view (D9): each side is+ * re-read in that source, and this fixture's chunk ids name no row there.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { makeContext } from '../src/cli/main.ts';@@ -15,7 +16,6 @@ import { operationsByName } from '../src/core/operations.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';-const UNAVAILABLE = 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.';let engine: PGLiteEngine;beforeAll(async () => {@@ -65,9 +65,9 @@ describe('find-contradictions through the local CLI context', () => {expect(res.contradictions).toHaveLength(1);});- test('--source <id> is a filter the report cannot honor: unavailable note', async () => {+ test('--source <id> is a filter: the scoped view, without the run total', async () => {const res = await findContradictions({ source: 'alpha' });- expect(res).toEqual({ contradictions: [], note: UNAVAILABLE });+ expect(res).toEqual({ run_id: 'cli-run-1', ran_at: expect.anything(), contradictions: [], total_visible: 0 });});test('--source __all__ still spans the brain', async () => {@@ -75,11 +75,11 @@ describe('find-contradictions through the local CLI context', () => {expect(res.run_id).toBe('cli-run-1');});- test('GBRAIN_SOURCE is user-selected scope: unavailable note', async () => {+ test('GBRAIN_SOURCE is user-selected scope: the scoped view', async () => {const res = await withEnv({ GBRAIN_SOURCE: 'alpha' }, async () => {const ctx = await makeContext(engine, {});return operationsByName['find_contradictions'].handler(ctx, {});});- expect(res).toEqual({ contradictions: [], note: UNAVAILABLE });+ expect(res).toEqual({ run_id: 'cli-run-1', ran_at: expect.anything(), contradictions: [], total_visible: 0 });});});diff --git a/test/find-contradictions-scoped.test.ts b/test/find-contradictions-scoped.test.tsnew file mode 100644index 0000000000..6b743aca77--- /dev/null+++ b/test/find-contradictions-scoped.test.ts@@ -0,0 +1,306 @@+/**+ * Wave 5 D9 — remote `find_contradictions` (src/core/eval-contradictions/scoped-read.ts):+ * scoped readers get stored findings only when both sides are visible to them+ * now and still read as judged, with live text, source identity and trust+ * labels. The fixture report copies every protected marker verbatim (text,+ * axis and resolution command), so any leak of stored text shows up.+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';+import { withTrustPromotion } from '../src/core/persistence/context.ts';+import { renderResolutionCommand } from '../src/core/eval-contradictions/auto-supersession.ts';+import { runContradictionProbe } from '../src/core/eval-contradictions/runner.ts';+import { writeRunRow } from '../src/core/eval-contradictions/trends.ts';+import type { ContradictionFinding, PairMember, ResolutionKind } from '../src/core/eval-contradictions/types.ts';+import type { TrustTier } from '../src/core/trust/tier.ts';++let engine: PGLiteEngine;+const noop = { info: () => {}, warn: () => {}, error: () => {} };++/** Markers a remote caller scoped to `default` must never read. */+const PROTECTED = {+ privatePage: 'PRIVPAGEMARK',+ otherSource: 'OTHERSRCMARK',+ quarantined: 'QUARANTINEMARK',+ deleted: 'DELETEDMARK',+ archived: 'ARCHIVEDMARK',+ changedOld: 'CHANGEDOLDMARK',+ unsafe: 'UNSAFECHUNKMARK',+ privateTake: 'PRIVTAKEMARK',+ inactiveTake: 'INACTIVETAKEMARK',+ derived: 'DERIVEDATOMMARK',+ staleProjection: 'STALEPROJMARK',+} as const;+const PUBLIC = { a: 'PUBLICAMARK', b: 'PUBLICBMARK', take: 'WORLDTAKEMARK', low: 'LOWTRUSTMARK', lowTake: 'LOWTAKEMARK' } as const;++interface Member { marker: string; member: PairMember; visibleRemote: boolean; source: string }+const members: Member[] = [];+let findings: ContradictionFinding[] = [];++async function importPage(slug: string, marker: string, opts: { source?: string; frontmatter?: string; type?: string } = {}) {+ const md = `---\ntype: ${opts.type ?? 'note'}\ntitle: ${slug}\n${opts.frontmatter ?? ''}---\n\nAcme reported revenue figure ${marker} for the quarter.\n`;+ const r = await importFromContent(engine, slug, md, { noEmbed: true, sourceId: opts.source ?? 'default' });+ expect(r.status).toBe('imported');+ const [row] = await engine.executeRaw<{ id: number; page_id: number; chunk_text: string }>(+ `SELECT cc.id, cc.page_id, cc.chunk_text FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.slug = $1 AND p.source_id = $2 ORDER BY cc.chunk_index LIMIT 1`, [slug, opts.source ?? 'default']);+ expect(row!.chunk_text).toContain(marker);+ return { pageId: Number(row!.page_id), chunkId: Number(row!.id), text: row!.chunk_text };+}++const chunkMember = (slug: string, chunkId: number, text: string, date: string | null = null): PairMember => ({+ slug, chunk_id: chunkId, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text,+ effective_date: date, effective_date_source: date ? 'frontmatter' : null,+});++async function addTake(pageId: number, slug: string, rowNum: number, claim: string, holder: string, active = true): Promise<PairMember> {+ const [row] = await engine.executeRaw<{ id: number }>(+ `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, active) VALUES ($1, $2, $3, 'take', $4, 0.8, $5) RETURNING id`,+ [pageId, rowNum, claim, holder, active]);+ return { slug, chunk_id: null, take_id: Number(row!.id), take_row_num: rowNum, source_tier: 'curated', holder, text: claim, effective_date: '2026-01-01', effective_date_source: 'frontmatter' };+}++/** Each protected state is isolated: a frontmatter or deletion update advances the page revision, which alone would hide its chunks. */+const currentProjection = (pageId: number) =>+ engine.executeRaw(`UPDATE pages SET text_projection_revision = knowledge_revision WHERE id = $1`, [pageId]);++const setTier = (table: string, id: number, tier: TrustTier) => engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed',+ () => tx.executeRaw(`UPDATE ${table} SET trust_tier = $1 WHERE id = $2`, [tier, id])));++function finding(a: Member, b: Member, kind: ResolutionKind = 'temporal_supersede', severity: 'low' | 'medium' | 'high' = 'high'): ContradictionFinding {+ const pair = { kind: a.member.take_id !== null || b.member.take_id !== null ? 'intra_page_chunk_take' as const : 'cross_slug_chunks' as const, a: a.member, b: b.member, combined_score: 1 };+ return {+ ...pair, verdict: 'contradiction', severity, axis: `${a.marker} disagrees with ${b.marker}`, confidence: 0.9,+ resolution_kind: kind, resolution_command: renderResolutionCommand(pair, kind),+ };+}++async function writeReport(list: ContradictionFinding[], runId = 'd9-run') {+ await engine.writeContradictionsRun({+ run_id: runId, judge_model: 'fixture', prompt_version: 'fixture', queries_evaluated: 1,+ queries_with_contradiction: 1, total_contradictions_flagged: list.length, wilson_ci_lower: 0, wilson_ci_upper: 1,+ judge_errors_total: 0, cost_usd_total: 0, duration_ms: 1, source_tier_breakdown: {},+ report_json: { per_query: [{ query: 'PRIVATEQUERYMARK', contradictions: list }] },+ } as never);+}++async function remoteCall(params: Record<string, unknown>, opts: DispatchOpts = {}) {+ const res = await dispatchToolCall(engine as never, 'find_contradictions', params, { remote: true, transport: 'stdio', sourceId: 'default', ...opts });+ const text = res.content.map(c => (c as { text?: string }).text ?? '').join('\n');+ return { text, body: JSON.parse((res.content[0] as { text: string }).text) as {+ contradictions: Array<{ a: { slug: string; source_id: string; text: string; trust_tier: string }; b: { slug: string; source_id: string; text: string; trust_tier: string }; resolution_kind: string; resolution_command: string; supersede_withheld?: string; axis: string }>;+ total_visible?: number; total_in_run?: number; note?: string;+ }, isError: res.isError === true };+}++const localCtx = (o: Partial<OperationContext> = {}): OperationContext =>+ ({ engine, config: { engine: 'pglite' }, logger: noop, dryRun: false, remote: false, sourceId: '__all__', ...o }) as OperationContext;++/** Seeded PRNG (mulberry32) so a failing fuzz case replays exactly. */+function rng(seed: number) {+ return () => {+ seed |= 0; seed = (seed + 0x6D2B79F5) | 0;+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('aa-other', 'aa-other', '{}'::jsonb) ON CONFLICT (id) DO NOTHING`);+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('aa-archived', 'aa-archived', '{}'::jsonb) ON CONFLICT (id) DO NOTHING`);++ const a = await importPage('companies/acme', PUBLIC.a);+ const b = await importPage('companies/acme-two', PUBLIC.b);+ const low = await importPage('notes/low-trust', PUBLIC.low);+ await setTier('pages', low.pageId, 'external_untrusted');+ const priv = await importPage('notes/private', PROTECTED.privatePage, { frontmatter: 'visibility: private\n' });+ // Same slug as the public page, in a source the caller cannot read: the stored report has no source column.+ const other = await importPage('companies/acme', PROTECTED.otherSource, { source: 'aa-other' });+ const quar = await importPage('notes/quarantined', PROTECTED.quarantined);+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"quarantine":{"reason":"junk_pattern","detail":"test","assessed_at":"2026-10-07T00:00:00Z"}}'::jsonb WHERE id = $1`, [quar.pageId]);+ await currentProjection(quar.pageId);+ const del = await importPage('notes/deleted', PROTECTED.deleted);+ const arch = await importPage('notes/archived', PROTECTED.archived, { source: 'aa-archived' });+ const changed = await importPage('notes/changed', PROTECTED.changedOld);+ const unsafe = await importPage('notes/unsafe', PROTECTED.unsafe);+ const derived = await importPage('atoms/derived', PROTECTED.derived, { type: 'atom' });+ const stale = await importPage('notes/stale', PROTECTED.staleProjection);++ const worldTake = await addTake(a.pageId, 'companies/acme', 1, `Acme revenue ${PUBLIC.take}`, 'world');+ const privTake = await addTake(a.pageId, 'companies/acme', 2, `Acme revenue ${PROTECTED.privateTake}`, 'garry');+ const inactiveTake = await addTake(a.pageId, 'companies/acme', 3, `Acme revenue ${PROTECTED.inactiveTake}`, 'world', false);+ const lowTake = await addTake(b.pageId, 'companies/acme-two', 1, `Acme revenue ${PUBLIC.lowTake}`, 'world');+ await setTier('takes', lowTake.take_id!, 'external_untrusted');++ members.push(+ { marker: PUBLIC.a, member: chunkMember('companies/acme', a.chunkId, a.text, '2026-03-01'), visibleRemote: true, source: 'default' },+ { marker: PUBLIC.b, member: chunkMember('companies/acme-two', b.chunkId, b.text, '2026-02-01'), visibleRemote: true, source: 'default' },+ { marker: PUBLIC.take, member: worldTake, visibleRemote: true, source: 'default' },+ { marker: PUBLIC.low, member: chunkMember('notes/low-trust', low.chunkId, low.text, '2026-04-01'), visibleRemote: true, source: 'default' },+ { marker: PUBLIC.lowTake, member: lowTake, visibleRemote: true, source: 'default' },+ { marker: PROTECTED.privatePage, member: chunkMember('notes/private', priv.chunkId, priv.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.otherSource, member: chunkMember('companies/acme', other.chunkId, other.text), visibleRemote: false, source: 'aa-other' },+ { marker: PROTECTED.quarantined, member: chunkMember('notes/quarantined', quar.chunkId, quar.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.deleted, member: chunkMember('notes/deleted', del.chunkId, del.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.archived, member: chunkMember('notes/archived', arch.chunkId, arch.text), visibleRemote: false, source: 'aa-archived' },+ { marker: PROTECTED.changedOld, member: chunkMember('notes/changed', changed.chunkId, changed.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.unsafe, member: chunkMember('notes/unsafe', unsafe.chunkId, unsafe.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.derived, member: chunkMember('atoms/derived', derived.chunkId, derived.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.staleProjection, member: chunkMember('notes/stale', stale.chunkId, stale.text), visibleRemote: false, source: 'default' },+ { marker: PROTECTED.privateTake, member: privTake, visibleRemote: false, source: 'default' },+ { marker: PROTECTED.inactiveTake, member: inactiveTake, visibleRemote: false, source: 'default' },+ );+ for (let i = 0; i < members.length; i++) for (let j = i + 1; j < members.length; j++) findings.push(finding(members[i]!, members[j]!));+ await writeReport(findings);++ // State changes after the probe ran: the report still holds the old text.+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE id = $1`, [del.pageId]);+ await currentProjection(del.pageId);+ await engine.executeRaw(`UPDATE sources SET archived = true WHERE id = 'aa-archived'`);+ await engine.executeRaw(`UPDATE content_chunks SET chunk_text = 'Acme revenue was restated.' WHERE id = $1`, [changed.chunkId]);+ await engine.executeRaw(`UPDATE pages SET chunker_version = 0 WHERE id = $1`, [unsafe.pageId]);+ // An edited page whose chunks still hold the previous revision's text.+ await engine.executeRaw(`UPDATE pages SET text_projection_revision = NULL WHERE id = $1`, [stale.pageId]);+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++const protectedMarkers = Object.values(PROTECTED);++describe('find_contradictions for scoped readers (D9)', () => {+ test('control: the trusted unscoped local read returns the stored report, every protected marker included', async () => {+ const res = await operationsByName.find_contradictions.handler(localCtx(), { limit: 100 }) as { contradictions: unknown[]; total_in_run: number };+ const text = JSON.stringify(res);+ for (const m of protectedMarkers) expect(text).toContain(m);+ expect(res.total_in_run).toBe(findings.length);+ });++ test('a remote caller sees only fully visible findings, re-read live and labeled', async () => {+ const { text, body } = await remoteCall({ limit: 100 });+ for (const m of protectedMarkers) expect(text).not.toContain(m);+ expect(text).not.toContain('PRIVATEQUERYMARK');+ const visible = members.filter(m => m.visibleRemote);+ expect(body.contradictions).toHaveLength(visible.length * (visible.length - 1) / 2);+ expect(body.total_visible).toBe(body.contradictions.length);+ expect(body.total_in_run).toBeUndefined();+ for (const f of body.contradictions) {+ for (const side of [f.a, f.b]) {+ expect(side.source_id).toBe('default');+ expect(typeof side.trust_tier).toBe('string');+ }+ }+ expect(text).toContain(PUBLIC.take);+ });++ test('the same slug in another source never stands in for the caller\'s page', async () => {+ const { body } = await remoteCall({ slug: 'companies/acme', limit: 100 });+ expect(body.contradictions.length).toBeGreaterThan(0);+ expect(JSON.stringify(body)).not.toContain(PROTECTED.otherSource);+ });++ test('a grant on the other source reads that source, never the caller\'s private page', async () => {+ const { text } = await remoteCall({ limit: 100 }, { auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default', 'aa-other', 'aa-archived'] } as never });+ expect(text).toContain(PROTECTED.otherSource);+ for (const m of protectedMarkers.filter(m => m !== PROTECTED.otherSource)) expect(text).not.toContain(m);+ });++ test('min_trust and a token floor hide lower-tier sides instead of refusing', async () => {+ const open = (await remoteCall({ limit: 100 })).text;+ expect(open).toContain(PUBLIC.low);+ expect(open).toContain(PUBLIC.lowTake);+ const param = await remoteCall({ limit: 100, min_trust: 'unknown' });+ expect(param.text).not.toContain(PUBLIC.low);+ expect(param.text).not.toContain(PUBLIC.lowTake);+ expect(param.body.contradictions.length).toBeGreaterThan(0);+ const token = await remoteCall({ limit: 100 }, { auth: { token: 't', clientId: 'c', scopes: ['read'], sourceId: 'default', minTrust: 'unknown' } as never });+ expect(token.isError).toBe(false);+ expect(token.text).not.toContain(PUBLIC.low);+ expect(token.text).not.toContain(PUBLIC.lowTake);+ expect(token.body.contradictions.length).toBeGreaterThan(0);+ });++ test('a supersede proposal against a higher-trust take is withheld for manual review', async () => {+ const take = members.find(m => m.marker === PUBLIC.take)!;+ await setTier('takes', take.member.take_id!, 'user_confirmed');+ try {+ const { body } = await remoteCall({ limit: 100 });+ const pair = (x: string, y: string) => body.contradictions.find(f =>+ [f.a.text, f.b.text].some(t => t.includes(x)) && [f.a.text, f.b.text].some(t => t.includes(y)))!;+ // The newer low-trust chunk would replace the confirmed take.+ const withheld = pair(PUBLIC.take, PUBLIC.low);+ expect(withheld.resolution_kind).toBe('manual_review');+ expect(withheld.supersede_withheld).toBe('higher_trust_target');+ expect(withheld.resolution_command).not.toContain('takes supersede');+ } finally {+ await setTier('takes', take.member.take_id!, 'unknown');+ }+ const { body } = await remoteCall({ limit: 100 });+ const kept = body.contradictions.find(f => [f.a.text, f.b.text].some(t => t.includes(PUBLIC.take)) && [f.a.text, f.b.text].some(t => t.includes(PUBLIC.a)))!;+ expect(kept.resolution_kind).toBe('temporal_supersede');+ expect(kept.resolution_command).toContain('gbrain takes supersede');+ });++ test('a source-filtered local caller gets the same scoped view', async () => {+ const res = await operationsByName.find_contradictions.handler(localCtx({ sourceId: 'default' }), { limit: 100 });+ const text = JSON.stringify(res);+ for (const m of [PROTECTED.otherSource, PROTECTED.archived, PROTECTED.deleted, PROTECTED.changedOld, PROTECTED.quarantined]) expect(text).not.toContain(m);+ expect(text).toContain(PUBLIC.a);+ // The trusted local owner sees private pages and every holder's takes.+ expect(text).toContain(PROTECTED.privatePage);+ expect(text).toContain(PROTECTED.privateTake);+ });++ test('fuzz: random reports, callers and params never return a protected marker (seeded)', async () => {+ const callers: Array<{ name: string; opts: DispatchOpts; extra?: string[] }> = [+ { name: 'stdio default', opts: {} },+ { name: 'grant default', opts: { auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default'] } as never } },+ { name: 'holders world+garry', opts: { takesHoldersAllowList: ['world', 'garry'] }, extra: [PROTECTED.privateTake] },+ { name: 'unknown source', opts: { sourceId: 'aa-missing' } },+ { name: 'grant incl. archived', opts: { auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default', 'aa-archived'] } as never } },+ ];+ const slugs = [...new Set(members.map(m => m.member.slug)), 'acme', 'notes/', ''];+ for (let seed = 1; seed <= 60; seed++) {+ const r = rng(seed);+ const pick = findings.filter(() => r() < 0.5).sort(() => r() - 0.5)+ .map(f => ({ ...f, severity: (['low', 'medium', 'high'] as const)[Math.floor(r() * 3)]! }));+ await writeReport(pick, `fuzz-${seed}`);+ const caller = callers[Math.floor(r() * callers.length)]!;+ const params: Record<string, unknown> = { limit: 1 + Math.floor(r() * 120) };+ if (r() < 0.5) params.slug = slugs[Math.floor(r() * slugs.length)];+ if (r() < 0.3) params.severity = (['low', 'medium', 'high'] as const)[Math.floor(r() * 3)];+ if (r() < 0.3) params.min_trust = 'unknown';+ const { text, body } = await remoteCall(params, caller.opts);+ const allowed = new Set(caller.extra ?? []);+ for (const m of protectedMarkers) if (!allowed.has(m)) expect({ seed, caller: caller.name, leaked: text.includes(m) ? m : null }).toEqual({ seed, caller: caller.name, leaked: null });+ expect(text).not.toContain('PRIVATEQUERYMARK');+ if (caller.name === 'unknown source') expect(body.contradictions ?? []).toHaveLength(0);+ }+ await writeReport(findings, 'd9-run-restored');+ });+});++describe('the real probe path', () => {+ test('findings stored by runContradictionProbe resolve for a remote caller, private sides still hidden', async () => {+ const result = await runContradictionProbe({+ engine, queries: ['Acme reported revenue figure'], noCache: true, yesOverride: true, topK: 8,+ judgeFn: async () => ({ verdict: { verdict: 'contradiction', severity: 'high', axis: 'revenue figure', confidence: 0.9, resolution_kind: 'manual_review' }, usage: { inputTokens: 0, outputTokens: 0 } }),+ });+ expect(result.report.per_query[0]!.contradictions.length).toBeGreaterThan(0);+ await writeRunRow(engine, result.report, result.report.duration_ms);+ const local = JSON.stringify(await operationsByName.find_contradictions.handler(localCtx(), { limit: 100 }));+ expect(local).toContain(PROTECTED.privatePage);+ const { text, body } = await remoteCall({ limit: 100 });+ expect(body.contradictions.length).toBeGreaterThan(0);+ for (const m of protectedMarkers) expect(text).not.toContain(m);+ });+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 40ec7f5d88..70f5c970bf 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 238577,- "stdoutSha256": "acff0492f087336a874aaa738286b4cb0143681ea6d0303d886f180ef6a2de8d",+ "stdoutBytes": 238925,+ "stdoutSha256": "48e1395287f6d7cc7418aa35788642033780fadcdfc344e549c04be6740a6e47","toolNames": ["remember","entity",@@ -6361,13 +6361,14 @@"scope": "admin"},{- "description": "Stored contradiction reports are temporarily available only to trusted local callers without a source filter. Remote or source-scoped callers receive {contradictions: [], note} with an availability note. For eligible local callers, return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. An eligible read loads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.",+ "description": "Return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. Remote, source-scoped or min_trust callers get only findings whose two sides they can read now (each side re-read live, with source_id, trust_tier and origin) and total_visible instead of the run total. Reads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.","idempotent": true,"local_only": false,"mutating": false,"name": "find_contradictions","parameters": {"limit": "number?",+ "min_trust": "string?","severity": "string?","slug": "string?"},@@ -6378,6 +6379,18 @@"description": "Max findings to return. Default 20.","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"severity": {"description": "Optional severity filter.","enum": [diff --git a/test/remote-privacy-journeys.serial.test.ts b/test/remote-privacy-journeys.serial.test.tsindex 8074587788..d8566bd936 100644--- a/test/remote-privacy-journeys.serial.test.ts+++ b/test/remote-privacy-journeys.serial.test.ts@@ -34,7 +34,6 @@ const PRIVATE_FACT = 'PRIVATE_FACT_JOURNEY_CANARY';const PRIVATE_TAKE = 'PRIVATE_TAKE_JOURNEY_CANARY';const PRIVATE_REPORT = 'PRIVATE_QUERY_REPORT_JOURNEY_CANARY';const SHARED = 'notes/shared-privacy';-const REPORT_NOTE = 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.';function cli(env: Record<string, string>, args: string[]): string {const result = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], {@@ -256,9 +255,11 @@ for (const kind of ['stdio', 'http'] as const) {expect((result._meta?.retrieval as { cache?: string })?.cache).toBe('disabled');}expect((await call('cache_stats')).body.enabled).toBe(false);- const { body } = await call('find_contradictions');- expect(body).toEqual({ contradictions: [], note: REPORT_NOTE });- expect(JSON.stringify(body)).not.toContain(PRIVATE_REPORT);+ // D9: the stored finding names no live chunk or take, so nothing resolves.+ const { result, body } = await call('find_contradictions');+ expect(body.contradictions).toEqual([]);+ expect(body).not.toHaveProperty('total_in_run');+ expect(JSON.stringify(result)).not.toContain(PRIVATE_REPORT);}, 45_000);test('page-visibility opt-out leaves historical Facts/Takes and report boundaries active', async () => {@@ -270,7 +271,9 @@ for (const kind of ['stdio', 'http'] as const) {expect(JSON.stringify(body)).toContain(PUBLIC);expect(JSON.stringify(result)).not.toContain(PRIVATE_FACT);expect(JSON.stringify(result)).not.toContain(PRIVATE_TAKE);- expect((await call('find_contradictions')).body).toEqual({ contradictions: [], note: REPORT_NOTE });+ const report = await call('find_contradictions');+ expect(report.body.contradictions).toEqual([]);+ expect(JSON.stringify(report.result)).not.toContain(PRIVATE_REPORT);}, 60_000);});}diff --git a/test/salience-source-scope.test.ts b/test/salience-source-scope.test.tsindex 440f649f36..07da0c64e8 100644--- a/test/salience-source-scope.test.ts+++ b/test/salience-source-scope.test.ts@@ -168,9 +168,10 @@ describe('find_contradictions source scoping', () => {expect(touchesPrivate(res)).toBe(true);});- // Stored text has no trustworthy snapshot provenance. Current endpoint- // visibility cannot authorize old private content, so restricted readers- // must receive an explicit unavailable result BEFORE loading any report.+ // Stored text has no trustworthy snapshot provenance, so a scoped reader+ // gets only findings whose sides re-read live in its scope (D9,+ // find-contradictions-scoped.test.ts). These fixture findings carry no chunk+ // or take ids, so none resolves: no stored text and no run total leave.for (const [label, overrides] of [['remote scalar', { sourceId: 'alpha' }],['remote federated', { auth: { allowedSources: ['alpha'] } }],@@ -185,23 +186,13 @@ describe('find_contradictions source scoping', () => {['unset trust marked implicit', { remote: undefined, sourceId: 'default', localSourceImplicit: true }],['local federated marked implicit', { remote: false, sourceId: 'default', localSourceImplicit: true, auth: { allowedSources: ['alpha'] } }],] as const) {- test(`${label}: reports unavailable before any database load`, async () => {- const original = engine.loadContradictionsTrend;- let loads = 0;- engine.loadContradictionsTrend = async () => {- loads++;- throw new Error('Restricted callers must not load stored reports');- };- try {- const res = await find_contradictions.handler(ctxOf(overrides as Partial<OperationContext>), { limit: 1, severity: 'high', slug: 'alpha/one' });- expect(res).toEqual({- contradictions: [],- note: 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.',- });- expect(loads).toBe(0);- } finally {- engine.loadContradictionsTrend = original;- }+ test(`${label}: no stored finding, text or run total leaves`, async () => {+ const res = await find_contradictions.handler(ctxOf(overrides as Partial<OperationContext>), { limit: 1, severity: 'high', slug: 'alpha/one' }) as Record<string, unknown>;+ expect(res.contradictions).toEqual([]);+ expect(res).not.toHaveProperty('total_in_run');+ const text = JSON.stringify(res);+ expect(text).not.toContain('beta/secret');+ expect(text).not.toContain('alpha/private-note');});}