Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W7 slices 2-3: forecast journal, gbrain takes journal, takes_scorecard group_by (local only)

garrytan726d5f28d623
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index f98f13e0b5..7936657159 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3068,6 +3068,14 @@ More: [docs/architecture/schema-packs.md#oversized-pack](../../docs/architecture
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### scorecard_group_by_local_only
+
+<a id="scorecard_group_by_local_only"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An agent-facing caller asked takes_scorecard for group_by or min_n, which read the private forecast journal and run only from the trusted local CLI. | The request itself was wrong or no longer matches the brain; nothing was changed. | Omit group_by and min_n; the brain owner runs gbrain takes scorecard --group-by on the brain host. | agent | `repeat the read that failed` | 1 | no |
+
### search_cursor_requires_keyword
<a id="search_cursor_requires_keyword"></a>
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index ab2f07c78a..b73d33837d 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -46,6 +46,7 @@
"test/fact-fence-adoption-exits.test.ts": 26963,
"test/fact-purge-lookup-timeout-6511.test.ts": 8682,
"test/fence-repair-receipts.test.ts": 11974,
+ "test/forecast-journal.test.ts": 12000,
"test/frontmatter-reserved-keys-6454.test.ts": 9760,
"test/get-chunks-paging.test.ts": 6453,
"test/graduation-copy.test.ts": 92395,
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index 9b34ba389b..7bd956ae50 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -251,6 +251,12 @@ async function cmdScorecard(engine: BrainEngine, args: string[]): Promise<void>
const domainPrefix = flagValue(args, '--domain');
const since = flagValue(args, '--since');
const until = flagValue(args, '--until');
+ const groupBy = flagValue(args, '--group-by');
+ const minNRaw = flagValue(args, '--min-n');
+ const fail = (message: string): never => { process.stderr.write(`${message}\n`); process.exit(1); };
+ if (groupBy !== undefined && groupBy !== 'holder' && groupBy !== 'source') fail('--group-by holder|source groups the scorecard by holder or by source.');
+ const minN = minNRaw === undefined ? undefined : Number(minNRaw);
+ if (minN !== undefined && !(Number.isSafeInteger(minN) && minN >= 1)) fail('--min-n requires a positive integer, e.g. --min-n 10.');
const { PARTIAL_RATE_WARNING_THRESHOLD } = await import('../core/takes-resolution.ts');
const card = await engine.getScorecard(
@@ -258,6 +264,31 @@ async function cmdScorecard(engine: BrainEngine, args: string[]): Promise<void>
/* allowList */ undefined, // CLI is local + trusted; MCP path threads allowList from the caller
);
+ // W7: per-holder or per-source rows from the private forecast journal.
+ let printGroups = () => {};
+ if (groupBy) {
+ const { readForecastJournal, scorecardGroups, SCORECARD_DEFAULT_MIN_N } = await import('../core/forecast-journal.ts');
+ const sourceId = flagValue(args, '--source-id');
+ const query = { ...(sourceId ? { sourceId } : {}), ...(holder ? { holder } : {}), ...(domainPrefix ? { about: domainPrefix } : {}),
+ ...(since ? { since } : {}), ...(until ? { until } : {}) };
+ const groups = await scorecardGroups(engine, { ...query, groupBy: groupBy as 'holder' | 'source', ...(minN !== undefined ? { minN } : {}) });
+ const journal = (await readForecastJournal(engine, { ...query, limit: 0 })).totals;
+ if (json) {
+ console.log(JSON.stringify({ ...card, groups, journal }, null, 2));
+ return;
+ }
+ const f = (n: number | null, digits = 3) => n === null ? '—' : n.toFixed(digits);
+ printGroups = () => {
+ console.log('');
+ console.log(`## By ${groupBy} (min_n=${minN ?? SCORECARD_DEFAULT_MIN_N}; ${journal.predictions} predictions, ${journal.unresolved} unresolved)`);
+ for (const g of groups) {
+ const interval = g.accuracy_wilson95 ? `[${f(g.accuracy_wilson95[0])}, ${f(g.accuracy_wilson95[1])}]` : '—';
+ console.log(` ${g.key} n=${g.n} accuracy=${f(g.accuracy)} shrunk=${f(g.accuracy_shrunk)} wilson95=${interval} recent=${f(g.accuracy_recent)} ` +
+ `Brier=${f(g.brier, 4)} skill=${f(g.brier_skill)} citations=${g.citations} unresolved=${g.unresolved} (${g.overdue} overdue)${g.low_n ? ' low_n' : ''}`);
+ }
+ };
+ }
+
if (json) {
console.log(JSON.stringify(card, null, 2));
return;
@@ -270,6 +301,7 @@ async function cmdScorecard(engine: BrainEngine, args: string[]): Promise<void>
const unresolvableCount = card.unresolvable_count ?? 0;
if (card.resolved === 0 && unresolvableCount === 0) {
console.log(`No resolved bets yet${holder ? ` for ${holder}` : ''}.`);
+ printGroups();
return;
}
const fmt = (n: number | null | undefined, digits = 3) =>
@@ -306,6 +338,7 @@ async function cmdScorecard(engine: BrainEngine, args: string[]): Promise<void>
console.log('');
console.log(` Note: n=${card.resolved} is small. Brier is noisy below ~100 resolved bets.`);
}
+ printGroups();
}
/**
@@ -495,6 +528,11 @@ Subcommands:
takes propose --reject <id> Dismiss a proposal
takes scorecard [<holder>] [--domain <prefix>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--json]
Aggregate calibration scorecard (v0.30.0)
+ [--group-by holder|source] [--min-n N] [--source-id <id>]
+ Per-holder or per-source rows from the forecast journal (W7, private)
+ takes journal [--holder h] [--about <slug-prefix>] [--state resolved|overdue|open|undated]
+ [--since YYYY-MM] [--until YYYY-MM] [--limit N] [--source-id <id>] [--json]
+ Every prediction with its time, horizon, state and resolution (W7, private)
takes calibration [<holder>] [--bucket-size 0.1] [--json]
Calibration curve binned by stated weight (v0.30.0)
takes horizon scan [--apply] [--source-id <id>] [--json]
@@ -531,6 +569,7 @@ Common flags:
// "No takes on propose." — the LLM proposal queue had no drain surface.
case 'propose': return cmdPropose(engine, rest, await resolveTakesSourceId(engine));
case 'horizon': return cmdHorizon(engine, rest);
+ case 'journal': return cmdJournal(engine, rest);
case 'scorecard': return cmdScorecard(engine, rest);
case 'calibration': return cmdCalibration(engine, rest);
case 'revisit': return cmdRevisit(engine, rest);
@@ -785,3 +824,43 @@ async function cmdHorizon(engine: BrainEngine, args: string[]): Promise<void> {
}
console.log(await clearTakeHorizon(engine, takeId) ? `Cleared the horizon of ${slug}#${row}.` : `${slug}#${row} had no horizon.`);
}
+
+/**
+ * W7: the private forecast journal (src/core/forecast-journal.ts). Every
+ * prediction with its prediction time (certified or labelled uncertified),
+ * horizon, state and resolution; the totals keep the unresolved denominator
+ * whatever --state or --limit shows. Trusted local only: there is no MCP op,
+ * so a thin client refuses it.
+ */
+async function cmdJournal(engine: BrainEngine, args: string[]): Promise<void> {
+ const usage = 'Usage: gbrain takes journal [--holder h] [--about <slug-prefix>] [--state resolved|overdue|open|undated]\n' +
+ ' [--since YYYY-MM] [--until YYYY-MM] [--limit N] [--source-id <id>] [--json]';
+ const fail = (message: string): never => { process.stderr.write(`${message}\n`); process.exit(1); };
+ const { readForecastJournal } = await import('../core/forecast-journal.ts');
+ const state = flagValue(args, '--state');
+ if (state !== undefined && !['resolved', 'overdue', 'open', 'undated'].includes(state)) fail(usage);
+ const limitRaw = flagValue(args, '--limit');
+ const limit = limitRaw === undefined ? undefined : Number(limitRaw);
+ if (limit !== undefined && !(Number.isSafeInteger(limit) && limit >= 1)) fail(`--limit requires a positive integer, e.g. --limit 50.\n${usage}`);
+ const value = (flag: string) => flagValue(args, flag);
+ const journal = await readForecastJournal(engine, {
+ ...(value('--source-id') ? { sourceId: value('--source-id') } : {}), ...(value('--holder') ? { holder: value('--holder') } : {}),
+ ...(value('--about') ? { about: value('--about') } : {}), ...(value('--since') ? { since: value('--since') } : {}),
+ ...(value('--until') ? { until: value('--until') } : {}), ...(state ? { state: state as 'resolved' } : {}), ...(limit ? { limit } : {}),
+ });
+ if (flagPresent(args, '--json')) {
+ console.log(JSON.stringify(journal, null, 2));
+ return;
+ }
+ const t = journal.totals;
+ console.log(`${t.predictions} predictions: ${t.resolved} resolved, ${t.unresolved} unresolved (${t.overdue} overdue, ${t.open} open, ${t.undated} undated)`);
+ console.log(`Prediction times certified by the belief ledger: ${t.certified_prediction_times} of ${t.predictions}.`);
+ for (const e of journal.entries) {
+ const predicted = e.prediction.at ? `${e.prediction.at} (${e.prediction.basis}, ${e.prediction.certified ? 'certified' : 'uncertified'})` : 'unknown';
+ const horizon = e.horizon ? `${e.horizon.date} (${e.horizon.basis})` : 'none';
+ const weight = e.weight === null ? '' : ` w=${e.weight.toFixed(2)}`;
+ const resolution = e.resolution ? ` resolved ${e.resolution.quality}${e.resolution.resolved_at ? ` ${e.resolution.resolved_at.slice(0, 10)}` : ''}${e.resolution.resolved_by ? ` by ${e.resolution.resolved_by}` : ''}` : '';
+ console.log(`\n[${e.state}] ${e.page_slug}#${e.row_num} ${e.holder}${weight} predicted ${predicted} horizon ${horizon}${resolution}\n ${e.claim}`);
+ }
+ if (journal.entries.length < (state ? t[state as 'resolved'] : t.predictions)) console.log(`\nShowing ${journal.entries.length}; the totals count every match.`);
+}
diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.ts
index de9a9697e6..eee95bf867 100644
--- a/src/commands/thin-client-routing.ts
+++ b/src/commands/thin-client-routing.ts
@@ -118,6 +118,7 @@ export async function routeThinClientCommand(
return true;
}
case 'scorecard': {
+ if (rest.includes('--group-by') || rest.includes('--min-n')) return false; // W7: private journal groups, host-bound
const holder = rest[0] && !rest[0].startsWith('--') ? rest[0] : flagValue(rest, '--holder');
printJson(await call(cfg, 'takes_scorecard', { ...(holder ? { holder } : {}) }));
return true;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 29aa1c2d87..725810030a 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -24,13 +24,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
- 'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
+ 'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
- 'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
+ 'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
- 'capture': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
+ 'capture': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--brain', '--exit-code', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
@@ -50,12 +50,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
- 'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
- 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
+ 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
@@ -77,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--clear-never-installed', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -88,19 +88,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
'notices': ['--brain', '--help', '--json', '--source'],
- 'onboard': ['--access', '--add', '--allowed-operations', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
+ 'onboard': ['--access', '--add', '--allowed-operations', '--apply', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--source', '--state', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
- 'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
+ 'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
- 'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
+ 'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--brain', '--class', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--since', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
@@ -130,14 +130,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--timeout', '--wait'],
'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
- 'takes': ['--accept', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
+ 'takes': ['--about', '--accept', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
- 'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
};
// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index a7bea31325..794afaea2a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -504,6 +504,7 @@ export const CODES = {
scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },
search_cursor_requires_keyword: { class: 'caller', summary: "A search cursor was sent without match: \"keyword\"; cursors continue keyword listings only (hybrid rows are a ranked top-K with no next page).", suggestion: 'Send the next object from the previous search response unchanged; it carries match: "keyword".' },
search_mode_local_only: { class: 'caller', summary: "An agent-facing caller set search's mode, which only the brain's operator chooses.", suggestion: 'Omit mode; for keyword-only matching with a total and paging, pass match: "keyword".' },
+ scorecard_group_by_local_only: { class: 'caller', summary: "An agent-facing caller asked takes_scorecard for group_by or min_n, which read the private forecast journal and run only from the trusted local CLI.", suggestion: 'Omit group_by and min_n; the brain owner runs gbrain takes scorecard --group-by on the brain host.' },
search_offset_over_cap: { class: 'caller', summary: "A search offset was over the 10,000 limit.", suggestion: 'Page with match: "keyword" and the next object each response returns; a cursor has no depth limit.' },
serve_build_drift: { class: 'host_only', summary: "A live `serve` or resident worker on this host runs an older gbrain build than this checkout: its `persistence_consumers` heartbeat `version` is below this binary's VERSION.", why: "Upgrading or pulling the checkout does not restart the processes already running from it, so one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts`) run newer code against the older consumer until serve and its workers restart. A serve older than the heartbeat table writes no row; `consumers_without_heartbeat` names it.", docs: 'docs/guides/troubleshooting.md#serve-build-drift', suggestion: 'Restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker; nothing restarts automatically.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with each heartbeat row\'s kind, pid and gbrain version.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'serve_build_drift', '--json'] } } },
serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },
diff --git a/src/core/forecast-journal.ts b/src/core/forecast-journal.ts
new file mode 100644
index 0000000000..c54a8f348b
--- /dev/null
+++ b/src/core/forecast-journal.ts
@@ -0,0 +1,218 @@
+/**
+ * W7 (wave 4b): the private forecast journal. Every active take that is not
+ * a fact is a prediction; the journal gives each one its prediction time
+ * (certified or not), exact claim, horizon (src/core/takes-horizon.ts),
+ * state and resolution, and keeps the unresolved denominator. The grouped
+ * scorecard (`takes_scorecard {group_by}`) reads the same predictions.
+ *
+ * Trusted local only: the CLI (`gbrain takes journal`, `gbrain takes
+ * scorecard --group-by`) and the local op path read it; a remote caller that
+ * asks for groups gets `scorecard_group_by_local_only`
+ * (src/core/ops/takes.ts).
+ *
+ * Prediction time: when the belief ledger recorded the exact claim (claim,
+ * kind, holder) on the page, either its first live `take.asserted` or, for a
+ * take the page was created with, the creation snapshot (see
+ * recordedPredictionTimes), certified only where the ledger's coverage
+ * certifies that instant (a managed source with no drift or truncated purge
+ * walk); without a recorded time, the take's since_date, never certified.
+ */
+import type { BrainEngine } from './engine.ts';
+import { coverageAt, coverageIntervals } from './belief/coverage-report.ts';
+import { takeClaimHash } from './belief/keys.ts';
+import { readTakeHorizons, type HorizonBasis } from './takes-horizon.ts';
+
+export type JournalState = 'resolved' | 'overdue' | 'open' | 'undated';
+export interface PredictionTime { at: string | null; basis: 'recorded' | 'since_date' | null; certified: boolean }
+export interface JournalEntry {
+ take_id: number; source_id: string; page_slug: string; row_num: number; claim: string; kind: string; holder: string; weight: number | null;
+ prediction: PredictionTime;
+ horizon: { date: string; basis: HorizonBasis; current: true } | null;
+ state: JournalState;
+ resolution: { quality: string; resolved_at: string | null; resolved_by: string | null; resolved_source: string | null } | null;
+}
+export interface JournalTotals { predictions: number; resolved: number; unresolved: number; open: number; overdue: number; undated: number; certified_prediction_times: number }
+export interface JournalQuery {
+ sourceId?: string; sourceIds?: string[]; holder?: string; about?: string; since?: string; until?: string;
+ state?: JournalState; asOf?: Date; limit?: number;
+}
+export interface ScorecardGroup {
+ key: string; n: number; correct: number; incorrect: number; partial: number; unresolvable: number;
+ accuracy: number | null; accuracy_shrunk: number | null; accuracy_wilson95: [number, number] | null; accuracy_recent: number | null;
+ brier: number | null; brier_skill: number | null; citations: number;
+ open: number; overdue: number; undated: number; unresolved: number; low_n: boolean;
+}
+
+/** Pseudo-observations of the Beta prior centred on the pooled accuracy. */
+export const SCORECARD_PRIOR_STRENGTH = 10;
+/** Half-life, in days since resolution, of the recency-weighted accuracy. */
+export const SCORECARD_RECENCY_HALF_LIFE_DAYS = 365;
+export const SCORECARD_DEFAULT_MIN_N = 10;
+
+const iso = (v: string | Date | null) => v == null ? null : new Date(v).toISOString();
+
+interface TakeRow {
+ id: number | string; source_id: string; page_slug: string; row_num: number; claim: string; kind: string; holder: string; weight: number | string | null;
+ since_date: string | null; resolved_quality: string | null; resolved_at: string | Date | null; resolved_by: string | null; resolved_source: string | null;
+}
+
+async function readPredictions(engine: BrainEngine, q: JournalQuery): Promise<TakeRow[]> {
+ const sources = q.sourceIds?.length ? q.sourceIds : q.sourceId ? [q.sourceId] : null;
+ return engine.executeRaw<TakeRow>(
+ `SELECT t.id, p.source_id, p.slug AS page_slug, t.row_num, t.claim, t.kind, t.holder, t.weight, t.since_date,
+ t.resolved_quality, t.resolved_at, t.resolved_by, t.resolved_source
+ FROM takes t JOIN pages p ON p.id = t.page_id
+ WHERE p.deleted_at IS NULL AND t.active AND t.kind <> 'fact'
+ AND ($1::text[] IS NULL OR p.source_id = ANY($1::text[]))
+ AND ($2::text IS NULL OR t.holder = $2)
+ AND ($3::text IS NULL OR left(p.slug, length($3)) = $3)
+ AND ($4::text IS NULL OR t.since_date >= $4)
+ AND ($5::text IS NULL OR t.since_date <= $5)
+ ORDER BY p.source_id, p.slug, t.row_num`,
+ [sources, q.holder ?? null, q.about ?? null, q.since ?? null, q.until ?? null]);
+}
+
+interface LedgerRow { source_id: string; slug: string; event_type: string; subject_key: string | null; at: string | Date }
+
+/**
+ * Recorded prediction times from the belief ledger, keyed by (source, slug,
+ * claim hash), over each page's current lifetime. A take added after its
+ * page was created has a live `take.asserted`; its earliest is the time.
+ * A take present when the page was created has no per-take creation event
+ * (the create is one `page.published` snapshot, BELIEF_LEDGER.md section 4),
+ * so it takes the snapshot's time, but only when coverage has run without a
+ * stop, restore or drift mark on the page since then: otherwise the take
+ * could have been added while the ledger was not watching. A take whose first
+ * event is `take.transferred` came from another page and gets no recorded
+ * time. Certified only where coverageAt certifies the instant.
+ */
+async function recordedPredictionTimes(engine: BrainEngine, rows: TakeRow[]): Promise<Map<string, PredictionTime>> {
+ const out = new Map<string, PredictionTime>();
+ if (!rows.length) return out;
+ const sources = [...new Set(rows.map(r => r.source_id))];
+ const events = await engine.executeRaw<LedgerRow>(
+ `SELECT l.source_id, l.slug, e.event_type, e.subject_key, e.recorded_at AS at
+ FROM belief_page_lifetimes l
+ JOIN sources s ON s.id = l.source_id AND s.incarnation = l.source_incarnation
+ JOIN belief_events e ON e.source_id = l.source_id AND e.source_incarnation = l.source_incarnation AND e.page_lifetime = l.page_lifetime
+ WHERE l.ended_at IS NULL AND l.source_id = ANY($1::text[]) AND l.slug = ANY($2::text[]) AND e.origin <> 'backfill'
+ AND (e.subject_kind = 'take' OR (e.event_type = 'page.published' AND e.value->>'revision_before' IS NULL))
+ ORDER BY e.id`,
+ [sources, [...new Set(rows.map(r => r.page_slug))]]);
+ const created = new Map<string, string>();
+ const firstTakeEvent = new Map<string, { type: string; at: string }>();
+ for (const e of events) {
+ const page = `${e.source_id}\u0000${e.slug}`;
+ if (e.event_type === 'page.published') { if (!created.has(page)) created.set(page, iso(e.at)!); continue; }
+ const key = `${page}\u0000${String((JSON.parse(e.subject_key!) as unknown[])[2])}`;
+ if (!firstTakeEvent.has(key)) firstTakeEvent.set(key, { type: e.event_type, at: iso(e.at)! });
+ }
+ const intervals = new Map<string, Awaited<ReturnType<typeof coverageIntervals>>>();
+ for (const id of sources) intervals.set(id, await coverageIntervals(engine, id));
+ const watchedSince = (sourceId: string, slug: string, at: string) => {
+ const open = intervals.get(sourceId)!.at(-1);
+ return !!open && !open.stopped_at && open.started_at <= at
+ && !open.restores.some(r => r.at > at) && !open.drift.some(d => d.slug === slug && d.to > at);
+ };
+ for (const r of rows) {
+ const page = `${r.source_id}\u0000${r.page_slug}`;
+ const key = `${page}\u0000${takeClaimHash(r.claim, r.kind, r.holder)}`;
+ if (out.has(key)) continue;
+ const first = firstTakeEvent.get(key);
+ const pageCreated = created.get(page);
+ const at = first?.type === 'take.asserted' ? first.at
+ : first?.type === 'take.transferred' || !pageCreated || !watchedSince(r.source_id, r.page_slug, pageCreated) ? null
+ : pageCreated;
+ if (!at) continue;
+ const coverage = await coverageAt(engine, r.source_id, at, r.page_slug);
+ if (!coverage.ok) continue;
+ out.set(key, { at, basis: 'recorded', certified: coverage.certified });
+ }
+ return out;
+}
+
+/** The journal: entries (filtered by `state`, then capped by `limit`) and totals over every prediction the other filters match. */
+export async function readForecastJournal(engine: BrainEngine, q: JournalQuery = {}): Promise<{ as_of: string; entries: JournalEntry[]; totals: JournalTotals }> {
+ const asOf = q.asOf ?? new Date();
+ const today = asOf.toISOString().slice(0, 10);
+ const rows = await readPredictions(engine, q);
+ const horizons = await readTakeHorizons(engine, rows.map(r => Number(r.id)));
+ const recorded = await recordedPredictionTimes(engine, rows);
+ const all: JournalEntry[] = rows.map(r => {
+ const h = horizons.get(Number(r.id));
+ const horizon = h?.current ? { date: h.horizon_date, basis: h.basis, current: true as const } : null;
+ const state: JournalState = r.resolved_quality ? 'resolved' : !horizon ? 'undated' : horizon.date < today ? 'overdue' : 'open';
+ const prediction = recorded.get(`${r.source_id}\u0000${r.page_slug}\u0000${takeClaimHash(r.claim, r.kind, r.holder)}`)
+ ?? { at: r.since_date, basis: r.since_date ? 'since_date' as const : null, certified: false };
+ return {
+ take_id: Number(r.id), source_id: r.source_id, page_slug: r.page_slug, row_num: r.row_num, claim: r.claim, kind: r.kind, holder: r.holder,
+ weight: r.weight == null ? null : Number(r.weight), prediction, horizon, state,
+ resolution: r.resolved_quality ? { quality: r.resolved_quality, resolved_at: iso(r.resolved_at), resolved_by: r.resolved_by, resolved_source: r.resolved_source } : null,
+ };
+ });
+ const count = (s: JournalState) => all.filter(e => e.state === s).length;
+ const totals: JournalTotals = {
+ predictions: all.length, resolved: count('resolved'), unresolved: all.length - count('resolved'),
+ open: count('open'), overdue: count('overdue'), undated: count('undated'),
+ certified_prediction_times: all.filter(e => e.prediction.certified).length,
+ };
+ const filtered = q.state ? all.filter(e => e.state === q.state) : all;
+ return { as_of: asOf.toISOString(), entries: q.limit === undefined ? filtered : filtered.slice(0, q.limit), totals };
+}
+
+function wilson95(k: number, n: number): [number, number] | null {
+ if (n === 0) return null;
+ const z = 1.959963984540054, p = k / n, d = 1 + z * z / n;
+ const centre = (p + z * z / (2 * n)) / d;
+ const half = z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d;
+ return [Math.max(0, centre - half), Math.min(1, centre + half)];
+}
+
+/**
+ * Per holder or source, over the journal's predictions: accuracy on
+ * correct/incorrect resolutions, shrunk toward the pooled accuracy with a
+ * Beta prior of SCORECARD_PRIOR_STRENGTH pseudo-observations, its Wilson 95%
+ * interval, recency-weighted accuracy, Brier and Brier skill (against the
+ * group's own base rate), citations (resolutions naming a source), the open,
+ * overdue and undated counts, and low_n when n < minN.
+ */
+export async function scorecardGroups(engine: BrainEngine, q: JournalQuery & { groupBy: 'holder' | 'source'; minN?: number }): Promise<ScorecardGroup[]> {
+ const asOf = q.asOf ?? new Date();
+ const { entries } = await readForecastJournal(engine, { ...q, state: undefined, limit: undefined, asOf });
+ const byKey = new Map<string, JournalEntry[]>();
+ for (const e of entries) {
+ const key = q.groupBy === 'holder' ? e.holder : e.source_id;
+ byKey.set(key, [...(byKey.get(key) ?? []), e]);
+ }
+ const scored = (e: JournalEntry) => e.resolution?.quality === 'correct' || e.resolution?.quality === 'incorrect';
+ const pooledN = entries.filter(scored).length;
+ const pooled = pooledN ? entries.filter(e => e.resolution?.quality === 'correct').length / pooledN : 0.5;
+ const minN = q.minN ?? SCORECARD_DEFAULT_MIN_N;
+ return [...byKey.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([key, group]) => {
+ const resolved = group.filter(scored);
+ const outcome = (e: JournalEntry) => e.resolution!.quality === 'correct' ? 1 : 0;
+ const n = resolved.length;
+ const correct = resolved.filter(e => outcome(e) === 1).length;
+ const weighted = resolved.filter(e => e.weight != null);
+ const brier = weighted.length ? weighted.reduce((s, e) => s + (e.weight! - outcome(e)) ** 2, 0) / weighted.length : null;
+ const base = weighted.length ? weighted.filter(e => outcome(e) === 1).length / weighted.length : null;
+ const ref = base === null ? 0 : base * (1 - base);
+ const dated = resolved.filter(e => e.resolution!.resolved_at);
+ const decay = (e: JournalEntry) => 0.5 ** (Math.max(0, asOf.getTime() - Date.parse(e.resolution!.resolved_at!)) / 86_400_000 / SCORECARD_RECENCY_HALF_LIFE_DAYS);
+ const wSum = dated.reduce((s, e) => s + decay(e), 0);
+ const count = (s: JournalState) => group.filter(e => e.state === s).length;
+ return {
+ key, n, correct, incorrect: n - correct,
+ partial: group.filter(e => e.resolution?.quality === 'partial').length,
+ unresolvable: group.filter(e => e.resolution?.quality === 'unresolvable').length,
+ accuracy: n ? correct / n : null,
+ accuracy_shrunk: (correct + SCORECARD_PRIOR_STRENGTH * pooled) / (n + SCORECARD_PRIOR_STRENGTH),
+ accuracy_wilson95: wilson95(correct, n),
+ accuracy_recent: wSum > 0 ? dated.reduce((s, e) => s + decay(e) * outcome(e), 0) / wSum : null,
+ brier, brier_skill: brier !== null && ref > 0 ? 1 - brier / ref : null,
+ citations: resolved.filter(e => e.resolution!.resolved_source?.trim()).length,
+ open: count('open'), overdue: count('overdue'), undated: count('undated'), unresolved: group.length - count('resolved'),
+ low_n: n < minN,
+ };
+ });
+}
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 1d53db07fc..00026dbc55 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -3704,6 +3704,18 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"until": {
"type": "string",
"description": "Window end (YYYY-MM-DD)"
+ },
+ "group_by": {
+ "type": "string",
+ "enum": [
+ "holder",
+ "source"
+ ],
+ "description": "Trusted local CLI only: per-group journal statistics"
+ },
+ "min_n": {
+ "type": "number",
+ "description": "Trusted local CLI only: groups with fewer resolved predictions are flagged low_n (default 10)"
}
},
"cliHints": {
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 7d37a7633c..26bb36e380 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -15,6 +15,7 @@ import { opTransport, paramUse } from './op-fix.ts';
import {
readPolicyOpts,
readHolders,
+ sourceScopeOpts,
thinkSourceScopeOpts,
enforceClientSlugFence,
validatePageSlug,
@@ -146,8 +147,23 @@ const takes_scorecard: Operation = {
domain_prefix: { type: 'string', description: 'Slug prefix (e.g. companies/) to scope the scorecard' },
since: { type: 'string', description: 'Window start (YYYY-MM-DD)' },
until: { type: 'string', description: 'Window end (YYYY-MM-DD)' },
+ group_by: { type: 'string', enum: ['holder', 'source'], description: 'Trusted local CLI only: per-group journal statistics' },
+ min_n: { type: 'number', description: 'Trusted local CLI only: groups with fewer resolved predictions are flagged low_n (default 10)' },
},
handler: async (ctx, p) => {
+ // W7: the grouped journal statistics are private. A remote caller that
+ // asks for them is refused, never silently given today's output.
+ const grouped = p.group_by !== undefined || p.min_n !== undefined;
+ if (grouped && ctx.remote !== false) {
+ throw opError('scorecard_group_by_local_only', 'takes_scorecard: group_by and min_n read the private forecast journal and run only from the trusted local CLI.',
+ 'Omit group_by and min_n, or ask the brain owner to run gbrain takes scorecard --group-by on the brain host.');
+ }
+ if (grouped && p.group_by !== 'holder' && p.group_by !== 'source') {
+ throw opError('invalid_params', 'takes_scorecard: group_by must be holder or source.', 'Pass group_by: "holder" or "source".');
+ }
+ if (p.min_n !== undefined && !(Number.isSafeInteger(p.min_n) && (p.min_n as number) >= 1)) {
+ throw opError('invalid_params', 'takes_scorecard: min_n must be a positive integer.', 'Pass min_n as a whole number, e.g. 10.');
+ }
const card = await ctx.engine.getScorecard(
{
...await readPolicyOpts(ctx),
@@ -164,7 +180,20 @@ const takes_scorecard: Operation = {
// ground truth. Op-layer SQL (plain executeRaw both engines share) —
// no engine method added, parity untouched. Unfiltered by the window/
// domain params (coarse by design; documented).
- return { ...card, mcp_resolved: await countMcpResolved(ctx) };
+ const base = { ...card, mcp_resolved: await countMcpResolved(ctx) };
+ if (!grouped) return base;
+ const { readForecastJournal, scorecardGroups } = await import('../forecast-journal.ts');
+ const scope = sourceScopeOpts(ctx);
+ const query = {
+ ...(scope.sourceIds?.length ? { sourceIds: scope.sourceIds } : scope.sourceId ? { sourceId: scope.sourceId } : {}),
+ ...(p.holder ? { holder: p.holder as string } : {}), ...(p.domain_prefix ? { about: p.domain_prefix as string } : {}),
+ ...(p.since ? { since: p.since as string } : {}), ...(p.until ? { until: p.until as string } : {}),
+ };
+ return {
+ ...base,
+ groups: await scorecardGroups(ctx.engine, { ...query, groupBy: p.group_by as 'holder' | 'source', ...(p.min_n !== undefined ? { minN: p.min_n as number } : {}) }),
+ journal: (await readForecastJournal(ctx.engine, { ...query, limit: 0 })).totals,
+ };
},
cliHints: { name: 'takes-scorecard' },
};
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 188ccd76f8..2dc8e5fd12 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": 241057,
- "stdoutSha256": "49eb8473ee380c158399b9e9e48d8ed817820ebb11018fac1a81cee2e169f78e",
+ "stdoutBytes": 241508,
+ "stdoutSha256": "fe1070079cf281df12dcfe6508a3cfaa22fc38d4f01c9e0998f596bfa25a0ea5",
"toolNames": [
"remember",
"entity",
@@ -4427,7 +4427,9 @@
"name": "takes_scorecard",
"parameters": {
"domain_prefix": "string?",
+ "group_by": "string?",
"holder": "string?",
+ "min_n": "number?",
"since": "string?",
"until": "string?"
},
@@ -4438,10 +4440,22 @@
"description": "Slug prefix (e.g. companies/) to scope the scorecard",
"type": "string"
},
+ "group_by": {
+ "description": "Trusted local CLI only: per-group journal statistics",
+ "enum": [
+ "holder",
+ "source"
+ ],
+ "type": "string"
+ },
"holder": {
"description": "Filter to this holder (world|garry|brain|<slug>)",
"type": "string"
},
+ "min_n": {
+ "description": "Trusted local CLI only: groups with fewer resolved predictions are flagged low_n (default 10)",
+ "type": "number"
+ },
"since": {
"description": "Window start (YYYY-MM-DD)",
"type": "string"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 837d29a390..d418984dc9 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6325,7 +6325,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/forecast-journal-cli.test.ts b/test/forecast-journal-cli.test.ts
new file mode 100644
index 0000000000..5f32680a8e
--- /dev/null
+++ b/test/forecast-journal-cli.test.ts
@@ -0,0 +1,108 @@
+/**
+ * W7: `gbrain takes journal` and `gbrain takes scorecard --group-by`
+ * (trusted local; thin clients refuse both, see
+ * test/thin-client-routing.test.ts). The journal lists every prediction
+ * with its state and keeps the unresolved denominator in its totals; the
+ * grouped scorecard adds per-holder or per-source rows to the plain card.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runTakes } from '../src/commands/takes.ts';
+import { scanStatedHorizons } from '../src/core/takes-horizon.ts';
+
+let engine: PGLiteEngine;
+
+async function capture(fn: () => Promise<void>): Promise<string> {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try { await fn(); } finally { console.log = orig; }
+ return lines.join('\n');
+}
+
+async function exitOf(fn: () => Promise<void>): Promise<{ code: number | undefined; stderr: string }> {
+ const origExit = process.exit;
+ const origErr = process.stderr.write.bind(process.stderr);
+ let stderr = '';
+ process.stderr.write = ((chunk: unknown) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;
+ process.exit = ((code?: number) => { throw Object.assign(new Error('EXIT'), { exitCode: code }); }) as typeof process.exit;
+ try { await fn(); return { code: undefined, stderr }; }
+ catch (e) { if ((e as Error).message === 'EXIT') return { code: (e as { exitCode?: number }).exitCode, stderr }; throw e; }
+ finally { process.exit = origExit; process.stderr.write = origErr; }
+}
+
+async function take(slug: string, claim: string, holder: string, since: string, resolved?: 'correct' | 'incorrect'): Promise<void> {
+ await engine.putPage(slug, { type: 'company', title: slug, compiled_truth: `${slug} test page.` });
+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);
+ await engine.addTakesBatch([{ page_id: page!.id, row_num: 1, claim, kind: 'bet', holder, weight: 0.7, since_date: since }]);
+ if (resolved) {
+ await engine.executeRaw(`UPDATE takes SET resolved_at = '2025-03-01T00:00:00Z', resolved_quality = $2, resolved_outcome = $3, resolved_by = 'owner' WHERE page_id = $1`,
+ [page!.id, resolved, resolved === 'correct']);
+ }
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await take('companies/acme-example', 'Acme-example will reach $5M ARR by the end of 2024', 'alice-example', '2023-02', 'correct');
+ await take('companies/bluefin-example', 'Bluefin-example will open a Berlin office by Q2 2025', 'bob-example', '2023-06');
+ await take('companies/cobalt-example', 'Cobalt-example will list by the end of 2099', 'alice-example', '2024-01');
+ await take('companies/dune-example', 'Dune-example has the strongest team in its market', 'bob-example', '2024-02', 'incorrect');
+ await scanStatedHorizons(engine, { apply: true });
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+describe('gbrain takes journal', () => {
+ test('--json lists every prediction with its state; totals keep the unresolved denominator', async () => {
+ const j = JSON.parse(await capture(() => runTakes(engine, ['journal', '--json'])));
+ expect(j.totals).toEqual({ predictions: 4, resolved: 2, unresolved: 2, open: 1, overdue: 1, undated: 0, certified_prediction_times: 0 });
+ expect(Object.fromEntries(j.entries.map((e: { page_slug: string; state: string }) => [e.page_slug, e.state]))).toEqual({
+ 'companies/acme-example': 'resolved', 'companies/bluefin-example': 'overdue', 'companies/cobalt-example': 'open', 'companies/dune-example': 'resolved' });
+ expect(j.entries[0].prediction).toEqual({ at: '2023-02', basis: 'since_date', certified: false });
+ });
+
+ test('filters by holder, page prefix and state, and caps with --limit', async () => {
+ const bob = JSON.parse(await capture(() => runTakes(engine, ['journal', '--holder', 'bob-example', '--json'])));
+ expect(bob.entries.map((e: { page_slug: string }) => e.page_slug)).toEqual(['companies/bluefin-example', 'companies/dune-example']);
+ const about = JSON.parse(await capture(() => runTakes(engine, ['journal', '--about', 'companies/cobalt', '--json'])));
+ expect(about.entries.map((e: { page_slug: string }) => e.page_slug)).toEqual(['companies/cobalt-example']);
+ const overdue = JSON.parse(await capture(() => runTakes(engine, ['journal', '--state', 'overdue', '--limit', '5', '--json'])));
+ expect([overdue.entries.length, overdue.totals.predictions]).toEqual([1, 4]);
+ });
+
+ test('the text form labels uncertified prediction times and prints the denominator', async () => {
+ const text = await capture(() => runTakes(engine, ['journal']));
+ expect(text).toContain('4 predictions: 2 resolved, 2 unresolved (1 overdue, 1 open, 0 undated)');
+ expect(text).toContain('[overdue]');
+ expect(text).toContain('2023-06 (since_date, uncertified)');
+ expect(text).toContain('Bluefin-example will open a Berlin office by Q2 2025');
+ });
+
+ test('refuses an unknown state and a bad limit', async () => {
+ expect(await exitOf(() => runTakes(engine, ['journal', '--state', 'late']))).toMatchObject({ code: 1, stderr: expect.stringContaining('Usage: gbrain takes journal') });
+ expect(await exitOf(() => runTakes(engine, ['journal', '--limit', '0']))).toMatchObject({ code: 1, stderr: expect.stringContaining('--limit') });
+ });
+});
+
+describe('gbrain takes scorecard --group-by', () => {
+ test('--json keeps the plain card and adds groups and journal totals', async () => {
+ const plain = JSON.parse(await capture(() => runTakes(engine, ['scorecard', '--json'])));
+ const grouped = JSON.parse(await capture(() => runTakes(engine, ['scorecard', '--group-by', 'holder', '--min-n', '1', '--json'])));
+ expect({ ...grouped, groups: undefined, journal: undefined, mcp_resolved: undefined }).toEqual({ ...plain, groups: undefined, journal: undefined, mcp_resolved: undefined });
+ expect(grouped.groups.map((g: { key: string; n: number; low_n: boolean }) => [g.key, g.n, g.low_n])).toEqual([['alice-example', 1, false], ['bob-example', 1, false]]);
+ expect(grouped.journal).toMatchObject({ predictions: 4, unresolved: 2 });
+ });
+
+ test('the text form prints one row per group and flags low_n', async () => {
+ const text = await capture(() => runTakes(engine, ['scorecard', '--group-by', 'holder']));
+ expect(text).toContain('By holder');
+ expect(text).toMatch(/alice-example\s+n=1/);
+ expect(text).toContain('low_n');
+ });
+
+ test('refuses an unknown grouping', async () => {
+ expect(await exitOf(() => runTakes(engine, ['scorecard', '--group-by', 'domain']))).toMatchObject({ code: 1, stderr: expect.stringContaining('--group-by holder|source') });
+ });
+});
diff --git a/test/forecast-journal.test.ts b/test/forecast-journal.test.ts
index 8fcffb508a..bbc6aa1d12 100644
--- a/test/forecast-journal.test.ts
+++ b/test/forecast-journal.test.ts
@@ -20,6 +20,7 @@ import { operationsByName } from '../src/core/operations.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { readForecastJournal, scorecardGroups } from '../src/core/forecast-journal.ts';
import { scanStatedHorizons } from '../src/core/takes-horizon.ts';
+import { disableBeliefLedger } from '../src/core/belief/coverage.ts';
import { testBackends } from './helpers/test-backends.ts';
import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';
@@ -69,19 +70,34 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
test('a managed source certifies the recorded prediction time; a take that predates the ledger falls back to since_date', () => beliefBrain(async b => {
await b.put('companies/acme-example', takesPage([{ claim: 'Acme-example will reach $9M ARR by the end of 2027', who: 'alice-example', since: '2026-09' }]));
- const asserted = (await b.events()).find(e => e.subject_kind === 'take' && e.event_type === 'take.asserted')!;
+ const created = (await b.events()).find(e => e.slug === 'companies/acme-example' && e.event_type === 'page.published' && e.value?.revision_before == null)!;
const j = await readForecastJournal(b.engine, { sourceId: b.sourceId, asOf: AS_OF });
const byClaim = Object.fromEntries(j.entries.map(e => [e.claim, e]));
- expect(byClaim['Acme-example will reach $9M ARR by the end of 2027']!.prediction).toEqual({ at: new Date(asserted.recorded_at).toISOString(), basis: 'recorded', certified: true });
+ expect(byClaim['Acme-example will reach $9M ARR by the end of 2027']!.prediction).toEqual({ at: new Date(created.recorded_at).toISOString(), basis: 'recorded', certified: true });
expect(byClaim['Old-example will merge by the end of 2026']!.prediction).toEqual({ at: '2025-01', basis: 'since_date', certified: false });
expect(j.totals.certified_prediction_times).toBe(1);
}, { managed: true, databaseUrl: engineCase.databaseUrl,
setup: async b => { await b.put('companies/old-example', takesPage([{ claim: 'Old-example will merge by the end of 2026', who: 'bob-example', since: '2025-01' }])); } }), 180_000);
- test('an unmanaged source records the prediction time but does not certify it', () => beliefBrain(async b => {
+ test('an unmanaged source records the prediction time but does not certify it; a take added later gets its own take.asserted time', () => beliefBrain(async b => {
+ const first = { claim: 'Acme-example will hire 50 people by Q4 2027', who: 'alice-example', since: '2026-09' };
+ await b.put('companies/acme-example', takesPage([first]));
+ const created = (await b.events()).find(e => e.event_type === 'page.published')!;
+ const mark = await b.lastId();
+ await b.put('companies/acme-example', takesPage([first, { claim: 'Acme-example will open a second office by 2028', who: 'bob-example', since: '2026-10' }]));
+ const asserted = (await b.events(mark)).filter(e => e.event_type === 'take.asserted');
+ expect(asserted).toHaveLength(1);
+ const byClaim = Object.fromEntries((await readForecastJournal(b.engine, { sourceId: b.sourceId, asOf: AS_OF })).entries.map(e => [e.claim, e]));
+ expect(byClaim[first.claim]!.prediction).toEqual({ at: new Date(created.recorded_at).toISOString(), basis: 'recorded', certified: false });
+ expect(byClaim['Acme-example will open a second office by 2028']!.prediction).toEqual({ at: new Date(asserted[0]!.recorded_at).toISOString(), basis: 'recorded', certified: false });
+ }, { databaseUrl: engineCase.databaseUrl }), 120_000);
+
+ test('a coverage stop after the page was created drops the snapshot time: the take falls back to since_date', () => beliefBrain(async b => {
await b.put('companies/acme-example', takesPage([{ claim: 'Acme-example will hire 50 people by Q4 2027', who: 'alice-example', since: '2026-09' }]));
+ await disableBeliefLedger(b.engine, b.sourceId);
+ await b.enable();
const [e] = (await readForecastJournal(b.engine, { sourceId: b.sourceId, asOf: AS_OF })).entries;
- expect(e!.prediction).toMatchObject({ basis: 'recorded', certified: false });
+ expect(e!.prediction).toEqual({ at: '2026-09', basis: 'since_date', certified: false });
}, { databaseUrl: engineCase.databaseUrl }), 120_000);
test('grouped scorecard: shrunk accuracy, interval, Brier skill, recency, citations, low_n; remote group_by is refused', () => beliefBrain(async b => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 78215bc04e..5ca292e55e 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -61,6 +61,7 @@ test/extraction-watermark-atoms.test.ts
test/fact-fence-adoption-exits.test.ts
test/fact-purge-lookup-timeout-6511.test.ts
test/fence-repair-receipts.test.ts
+test/forecast-journal.test.ts
test/frontmatter-reserved-keys-6454.test.ts
test/get-chunks-paging.test.ts
test/graduation-copy.test.ts
diff --git a/test/thin-client-routing.test.ts b/test/thin-client-routing.test.ts
index f00c9e6dfc..057a19d195 100644
--- a/test/thin-client-routing.test.ts
+++ b/test/thin-client-routing.test.ts
@@ -243,6 +243,10 @@ describe('routeThinClientCommand — (b) host-bound forms return false', () => {
['takes', ['horizon', 'scan']],
['takes', ['horizon', 'set', 'companies/acme-example', '--row', '1', '--date', '2025-06-30']],
['takes', ['horizon', 'clear', 'companies/acme-example', '--row', '1']],
+ ['takes', ['journal']],
+ ['takes', ['journal', '--holder', 'alice-example', '--json']],
+ ['takes', ['scorecard', '--group-by', 'holder']],
+ ['takes', ['scorecard', 'alice-example', '--min-n', '5']],
];
for (const [command, args] of hostBound) {