Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(find-contradictions): bare local CLI reads the latest run; user-selected sources still refused (N2-2)

garrytane833e93d0949
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index 79658b766d..c92077aedc 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`.
-- `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,fixture-redact}.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. MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only). 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,fixture-redact}.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-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/contradictions.md b/docs/contradictions.md
index b6d3b355f5..a02386cd00 100644
--- a/docs/contradictions.md
+++ b/docs/contradictions.md
@@ -148,7 +148,10 @@ pay near-zero on re-runs (until you bump PROMPT_VERSION).
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. Remote or source-scoped callers receive
+ 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.
- Build-fixture script is local-only. The redactor + `isCleanForCommit`
@@ -161,7 +164,10 @@ The judge distinguishes real contradictions from legitimate change-over-time.
The verdict enum has six members (`no_contradiction | contradiction |
temporal_supersession | temporal_regression | temporal_evolution |
negation_artifact`), and `pages.effective_date` is threaded into the judge
-prompt so the probe doesn't cry wolf on facts that simply changed.
+prompt so the probe doesn't cry wolf on facts that simply changed. Only
+content dates (frontmatter or filename) count; a page whose date is the
+recorded-time `fallback` reaches the judge as `(date unknown)` and leaves
+the text-date pre-filter in charge.
The trajectory substrate builds on the same signal:
`gbrain eval trajectory <entity>` shows the chronological typed-claim
diff --git a/src/cli.ts b/src/cli.ts
index 0189e60a75..731bbb0a32 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1432,6 +1432,7 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un
// trusted local boundary) and consumed by federatedSearchScope in
// operations.ts, which additionally gates on ctx.remote === false.
let localFederated: string[] | undefined;
+ let sourceImplicit = true;
// params.source is set when a CLI flag was parsed for the op (rare; most
// CLI ops don't take --source). Falls through to env/dotfile/path-match.
const explicit = (params.source as string | undefined) ?? null;
@@ -1439,6 +1440,7 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un
try {
const resolved = await resolveSourceWithTier(engine, explicit);
sourceId = resolved.source_id;
+ sourceImplicit = resolved.tier !== 'flag' && resolved.tier !== 'env' && resolved.tier !== 'dotfile';
localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
} catch (err) {
// #1712: an EXPLICIT --source that fails to resolve (invalid id, or a
@@ -1520,6 +1522,7 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un
// brain (that would be an untrusted-caller cross-brain hole over MCP).
brainId: activeBrainId,
...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
+ ...(sourceImplicit ? { localSourceImplicit: true } : {}),
// T15/FOV-1: capture the retrieval meta for formatResult's empty-result
// render (the local-engine twin of the MCP _meta.retrieval channel).
emitResponseMeta: captureRetrievalMeta,
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 791729e2e2..e6fb3333aa 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -465,6 +465,15 @@ export interface OperationContext {
* wins, and a context without this field never widens.
*/
localFederatedSourceIds?: string[];
+ /**
+ * N2-2 — true when the trusted local CLI (src/cli.ts makeContext) resolved
+ * `sourceId` from a non-explicit tier (local_path / brain_default /
+ * sole_non_default / seed_default, or the pre-init 'default' fallback), i.e.
+ * the operator did not select a source. Lets ops whose data has no source
+ * axis (find_contradictions' brain-wide stored reports) answer the bare
+ * command. Ignored unless `remote === false`; a grant always wins.
+ */
+ localSourceImplicit?: boolean;
/**
* #5081 — explicit-read admission for a stdio connection bound by an
* explicit tier (`GBRAIN_SOURCE` or a `.gbrain-source` pin). Set ONLY by
diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.ts
index ced82a3837..d13ee088a2 100644
--- a/src/core/ops/insights.ts
+++ b/src/core/ops/insights.ts
@@ -198,7 +198,11 @@ const find_contradictions: Operation = {
},
handler: async (ctx, p) => {
const scope = sourceScopeOpts(ctx);
- if (ctx.remote !== false || scope.sourceId !== undefined || scope.sourceIds !== undefined) {
+ // N2-2: the local CLI always carries a sourceId; one the operator did not
+ // 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.' };
}
diff --git a/test/find-contradictions-cli-source.test.ts b/test/find-contradictions-cli-source.test.ts
new file mode 100644
index 0000000000..bfa1b5c7cc
--- /dev/null
+++ b/test/find-contradictions-cli-source.test.ts
@@ -0,0 +1,85 @@
+/**
+ * N2-2 — bare `gbrain find-contradictions` reads the latest run.
+ *
+ * skills/correction-pipeline/SKILL.md documents the bare command as reading
+ * the latest probe run. makeContext always populates ctx.sourceId (falling
+ * 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.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { makeContext } from '../src/cli.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+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 () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('alpha', 'alpha')`);
+ await engine.writeContradictionsRun({
+ run_id: 'cli-run-1', judge_model: 'test', prompt_version: 'v1',
+ queries_evaluated: 1, queries_with_contradiction: 1, total_contradictions_flagged: 1,
+ 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: [{
+ contradictions: [{
+ kind: 'cross_slug_chunks', severity: 'medium', axis: 'headcount', confidence: 0.9,
+ a: { slug: 'notes/a', chunk_id: 1, take_id: null },
+ b: { slug: 'notes/b', chunk_id: 2, take_id: null },
+ resolution_kind: 'manual_review', resolution_command: '# manual review',
+ }],
+ }],
+ },
+ });
+});
+
+const findContradictions = (params: Record<string, unknown>) =>
+ withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ const ctx = await makeContext(engine, params);
+ return operationsByName['find_contradictions'].handler(ctx, {}) as Promise<{
+ run_id?: string; contradictions: unknown[]; note?: string;
+ }>;
+ });
+
+describe('find-contradictions through the local CLI context', () => {
+ test('bare command (implicit default source) reads the latest run', async () => {
+ const res = await findContradictions({});
+ expect(res.note).toBeUndefined();
+ expect(res.run_id).toBe('cli-run-1');
+ expect(res.contradictions).toHaveLength(1);
+ });
+
+ test('--source <id> is a filter the report cannot honor: unavailable note', async () => {
+ const res = await findContradictions({ source: 'alpha' });
+ expect(res).toEqual({ contradictions: [], note: UNAVAILABLE });
+ });
+
+ test('--source __all__ still spans the brain', async () => {
+ const res = await findContradictions({ source: '__all__' });
+ expect(res.run_id).toBe('cli-run-1');
+ });
+
+ test('GBRAIN_SOURCE is user-selected scope: unavailable note', 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 });
+ });
+});
diff --git a/test/salience-source-scope.test.ts b/test/salience-source-scope.test.ts
index e0a0bebb3c..440f649f36 100644
--- a/test/salience-source-scope.test.ts
+++ b/test/salience-source-scope.test.ts
@@ -180,6 +180,10 @@ describe('find_contradictions source scoping', () => {
['local federated', { remote: false, auth: { allowedSources: ['alpha'] } }],
['remote empty grant with scalar floor', { sourceId: 'alpha', auth: { allowedSources: [] } }],
['local empty grant with scalar floor', { remote: false, sourceId: 'alpha', auth: { allowedSources: [] } }],
+ // N2-2: the implicit-source marker only relaxes the TRUSTED local CLI.
+ ['remote scalar marked implicit', { sourceId: 'default', localSourceImplicit: true }],
+ ['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;
@@ -210,6 +214,14 @@ describe('find_contradictions source scoping', () => {
expect(res.total_in_run).toBe(4);
});
+ test('N2-2: trusted local CLI with an implicit (non-user-selected) source reads the full report', async () => {
+ const res = await find_contradictions.handler(ctxOf({ remote: false, sourceId: 'default', localSourceImplicit: true }), {}) as {
+ contradictions: Array<{ a: { slug: string }; b: { slug: string } }>; total_in_run: number;
+ };
+ expect(res.contradictions).toHaveLength(4);
+ expect(res.total_in_run).toBe(4);
+ });
+
test('an empty grant without a scalar remains a legitimate unscoped local context', async () => {
const res = await find_contradictions.handler(ctxOf({ remote: false, auth: { allowedSources: [] } as any }), {}) as {
contradictions: unknown[];