Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cli): link commands honor --source-id/--all-sources; thin client refuses ignored scope (#5827)

garrytanf6725e94188a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index de16ac1769..410abcf4c3 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 3162 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts)
+src/cli.ts 3198 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts)
src/commands/autopilot.ts 1635 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195)
src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2187 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages
diff --git a/src/cli.ts b/src/cli.ts
index 0189e60a75..6365baf642 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -43,6 +43,7 @@ import { conceptNudge } from './core/search/query-intent.ts';
import { redactRetrievalOutput } from './core/search/output-redaction.ts';
import type { CliOptions } from './core/cli-options.ts';
import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from './core/mcp-client.ts';
+import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './cli/source-scope.ts';
import { maybePromptForUpgrade } from './core/thin-client-upgrade-prompt.ts';
import { CLI_FLAG_REGISTRY } from './core/cli-flag-registry.generated.ts';
import { migrationCliArgumentError } from './core/embedding-migration-cli.ts';
@@ -572,16 +573,26 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// #2098: the local path resolves --source / GBRAIN_SOURCE / .gbrain-source
// inside makeContext (ctx.sourceId), which this route never reaches — so
// scope must be mapped onto the op's source_id wire param before the call.
+ let ambientScope: AmbientSourceBinding | null;
try {
- applyThinClientSourceScope(op, params);
+ ambientScope = applyThinClientSourceScope(op, params);
} catch (e: unknown) {
console.error(e instanceof Error ? e.message : String(e));
process.exit(1);
}
- await runThinClientRouted(op, params, cfgPre!, cliOpts);
+ await runThinClientRouted(op, params, cfgPre!, cliOpts, ambientScope);
return;
}
+ // Locally --source reaches the op through makeContext (ctx.sourceId); a
+ // per-call --source-id / --all-sources would silently win over it.
+ try {
+ assertSingleSourceScopeFlag(op, params);
+ } catch (e: unknown) {
+ console.error(e instanceof Error ? e.message : String(e));
+ process.exit(1);
+ }
+
// The live PGLite owner exposes canonical operations over a dedicated
// local socket. Delegate before opening a competing engine connection.
{
@@ -740,6 +751,7 @@ async function runThinClientRouted(
params: Record<string, unknown>,
cfg: GBrainConfig,
cliOpts: CliOptions,
+ ambientScope: AmbientSourceBinding | null = null,
): Promise<void> {
// ENG-4: per-op timeout default; user override wins.
const defaultTimeoutMs = op.name === 'think' ? 180_000 : 30_000;
@@ -768,7 +780,9 @@ async function runThinClientRouted(
// unpacking (old servers lack _meta — capture is simply skipped).
const envelopeMeta = extractResponseMeta(raw);
if (envelopeMeta?.retrieval) captureRetrievalMeta('retrieval', envelopeMeta.retrieval);
+ checkHostHonoredParams(op, params, raw);
const result = unpackToolResult(raw);
+ hintAmbientNarrowing(op, params, result, ambientScope);
const skew = deliveryVersionSkewWarning(op.name, params, envelopeMeta?.retrieval as Record<string, unknown> | undefined, result);
if (skew) process.stderr.write(skew + '\n');
const output = formatResult(op.name, result, params);
@@ -1210,25 +1224,26 @@ export async function readStdinBounded(): Promise<string | null> {
// these; an explicit --source-id still passes through untouched above.
const NON_SCOPE_SOURCE_ID_OPS = new Set(['get_skill']);
+/**
+ * Returns the ambient binding (GBRAIN_SOURCE / .gbrain-source) that was mapped
+ * onto `source_id`, so an empty result can say what narrowed it; null when the
+ * scope came from a flag or nothing was mapped.
+ */
export function applyThinClientSourceScope(
op: Operation,
params: Record<string, unknown>,
cwd?: string,
-): void {
- if ('source' in op.params) return; // the op owns --source; not a scope flag
+): AmbientSourceBinding | null {
+ if ('source' in op.params) return null; // the op owns --source; not a scope flag
+ assertSingleSourceScopeFlag(op, params);
const explicit = typeof params.source === 'string' && params.source.length > 0
? (params.source as string)
: null;
delete params.source; // never a wire param on these ops — don't leak it
// Explicit per-call scope already on the wire wins over ambient tiers.
- if (params.source_id !== undefined || params.all_sources === true) {
- if (explicit) {
- throw new Error('Pass either --source or --source-id/--all-sources, not both.');
- }
- return;
- }
+ if (params.source_id !== undefined || params.all_sources === true) return null;
const resolved = resolveSourceIdEngineFree(explicit, cwd);
- if (!resolved) return;
+ if (!resolved) return null;
if (!('source_id' in op.params) || NON_SCOPE_SOURCE_ID_OPS.has(op.name)) {
if (explicit) {
const hint = NON_SCOPE_SOURCE_ID_OPS.has(op.name)
@@ -1238,9 +1253,12 @@ export function applyThinClientSourceScope(
`gbrain ${op.cliHints?.name || op.name} does not accept --source on a thin-client install ${hint}.`,
);
}
- return; // ambient env/dotfile scope with nowhere to send it
+ return null; // ambient env/dotfile scope with nowhere to send it
}
params.source_id = resolved;
+ if (explicit) return null;
+ const env = process.env.GBRAIN_SOURCE;
+ return { sourceId: resolved, via: env && env.length > 0 ? 'GBRAIN_SOURCE' : '.gbrain-source' };
}
// Exported for tests (same import-safety contract as applyThinClientSourceScope).
@@ -1429,8 +1447,9 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un
// #2561: when the source resolved via a NON-explicit tier (path-match /
// brain default / sole-non-default / seed default), unqualified search-shaped
// reads span every `config.federated = true` source. Computed here (the
- // trusted local boundary) and consumed by federatedSearchScope in
- // operations.ts, which additionally gates on ctx.remote === false.
+ // trusted local boundary) and consumed by federatedSearchScope
+ // (src/core/ops/context.ts), which widens only an unqualified read with no
+ // OAuth grant; remote transports compute the same field for no-grant tokens.
let localFederated: string[] | undefined;
// params.source is set when a CLI flag was parsed for the op (rare; most
// CLI ops don't take --source). Falls through to env/dotfile/path-match.
@@ -2858,6 +2877,25 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin
return engine;
}
+/** CLI-only usage examples appended to `gbrain <command> --help`. */
+const OP_HELP_EXAMPLES: Record<string, string[]> = {
+ get_links: [
+ 'gbrain links people/alice-example # resolved source (every federated source when unpinned)',
+ 'gbrain links people/alice-example --source business # one source',
+ 'gbrain links people/alice-example --all-sources # every source',
+ ],
+ get_backlinks: [
+ 'gbrain backlinks companies/acme-example',
+ 'gbrain backlinks companies/acme-example --source-id business',
+ 'gbrain backlinks companies/acme-example --all-sources --json',
+ ],
+ traverse_graph: [
+ 'gbrain graph people/alice-example --depth 2',
+ 'gbrain graph people/alice-example --source business --direction both',
+ 'gbrain graph people/alice-example --all-sources # same slug in two sources stays two nodes (source_id)',
+ ],
+};
+
export function printOpHelp(op: Operation, invokedName?: string) {
const positional = (op.cliHints?.positional || []).map(p => `<${p}>`).join(' ');
// v114 (#1941): when invoked via an alias (e.g. `gbrain link-add --help`),
@@ -2880,6 +2918,8 @@ export function printOpHelp(op: Operation, invokedName?: string) {
console.log(`${prefix.padEnd(28)} ${def.description || ''}${req}`);
}
}
+ const examples = OP_HELP_EXAMPLES[op.name];
+ if (examples) console.log(`\nExamples:\n${examples.map((line) => ` ${line}`).join('\n')}`);
}
function printHelp() {
diff --git a/src/cli/source-scope.ts b/src/cli/source-scope.ts
new file mode 100644
index 0000000000..3fdfe38cb8
--- /dev/null
+++ b/src/cli/source-scope.ts
@@ -0,0 +1,65 @@
+/**
+ * #5827: CLI source-scope checks shared by the local and thin-client op
+ * paths in src/cli.ts — the `--source` vs `--source-id`/`--all-sources`
+ * conflict, the mixed-version check that fails when a brain host ignored a
+ * scope param, and the ambient-narrowing hint for empty thin-client reads.
+ */
+import type { Operation } from '../core/operations.ts';
+import { ignoredRemoteParams } from '../core/mcp-client.ts';
+
+/** Where an ambient (not flag-supplied) thin-client source scope came from. */
+export type AmbientSourceBinding = { sourceId: string; via: 'GBRAIN_SOURCE' | '.gbrain-source' };
+
+/**
+ * `--source` together with `--source-id` / `--all-sources` names two scopes;
+ * refuse instead of letting one silently win (local and thin-client paths).
+ * Ops that own a `source` param are exempt: their --source is not scope.
+ */
+export function assertSingleSourceScopeFlag(op: Operation, params: Record<string, unknown>): void {
+ if ('source' in op.params) return;
+ const explicit = typeof params.source === 'string' && params.source.length > 0;
+ if (explicit && (params.source_id !== undefined || params.all_sources === true)) {
+ throw new Error('Pass either --source or --source-id/--all-sources, not both.');
+ }
+}
+
+/** Per-call scope params a thin client must never see silently dropped. */
+const SCOPE_WIRE_PARAMS = ['source_id', 'all_sources'];
+
+/**
+ * #5827 mixed versions: an older brain host that does not declare a scope
+ * param the client sent (from a flag, GBRAIN_SOURCE or .gbrain-source)
+ * answers unscoped with an unknown-parameter warning; fail instead of
+ * printing that result. Other ignored params this client's op declares are
+ * surfaced on stderr (CLI-local keys such as `json` are not). Hosts that
+ * predate unknown-parameter warnings cannot be detected here.
+ */
+export function checkHostHonoredParams(op: Operation, params: Record<string, unknown>, raw: unknown): void {
+ const ignored = ignoredRemoteParams(raw);
+ const scope = ignored.filter((name) => SCOPE_WIRE_PARAMS.includes(name) && params[name] !== undefined);
+ if (scope.length > 0) {
+ throw new Error(
+ `the brain host does not support ${scope.join(', ')} on ${op.name}; upgrade the host (gbrain upgrade on the brain host)`,
+ );
+ }
+ for (const name of ignored) {
+ if (!(name in op.params)) continue;
+ process.stderr.write(`[gbrain] warning: the brain host ignored parameter "${name}" on ${op.name}; upgrade the host to use it.\n`);
+ }
+}
+
+/**
+ * #5827: a thin-client read narrowed by an ambient binding that came back
+ * empty says which binding scoped it and how to widen; it names only the
+ * caller's own binding, never another source.
+ */
+export function hintAmbientNarrowing(op: Operation, params: Record<string, unknown>, result: unknown, ambient: AmbientSourceBinding | null): void {
+ if (!ambient || params.json === true || !('all_sources' in op.params)) return;
+ if (!Array.isArray(result) || result.length > 0) return;
+ const cliName = op.cliHints?.name || op.name;
+ const positional = (op.cliHints?.positional ?? []).map((key) => String(params[key] ?? `<${key}>`)).join(' ');
+ process.stderr.write(
+ `[gbrain] ${cliName}: no results within source ${ambient.sourceId} (set by ${ambient.via}). ` +
+ `To read every source you can see: gbrain ${cliName}${positional ? ` ${positional}` : ''} --all-sources\n`,
+ );
+}
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index ae2b406d34..9d94507086 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -529,3 +529,26 @@ export function extractResponseMeta(res: unknown): Record<string, unknown> | und
}
return undefined;
}
+
+/**
+ * Params the server reported it ignored (WP3 warn mode): `_meta.warnings`
+ * entries with code `unknown_param`, plus the model-visible warning blocks
+ * after content[0] for transports that drop `_meta`. Empty for hosts that
+ * predate unknown-parameter warnings, which cannot be detected.
+ */
+export function ignoredRemoteParams(res: unknown): string[] {
+ const names = new Set<string>();
+ const warnings = extractResponseMeta(res)?.warnings;
+ if (Array.isArray(warnings)) {
+ for (const w of warnings as Array<{ code?: unknown; param?: unknown }>) {
+ if (w?.code === 'unknown_param' && typeof w.param === 'string') names.add(w.param);
+ }
+ }
+ const content = (res as { content?: unknown[] } | undefined)?.content;
+ for (const block of Array.isArray(content) ? content.slice(1) : []) {
+ const text = (block as { text?: unknown })?.text;
+ if (typeof text !== 'string') continue;
+ for (const m of text.matchAll(/^warning: unknown parameter "([^"]+)" ignored/gm)) names.add(m[1]);
+ }
+ return [...names];
+}
diff --git a/test/link-reads-thin-client-5827.serial.test.ts b/test/link-reads-thin-client-5827.serial.test.ts
new file mode 100644
index 0000000000..f8da0f9ec2
--- /dev/null
+++ b/test/link-reads-thin-client-5827.serial.test.ts
@@ -0,0 +1,202 @@
+/**
+ * #5827 — link reads on a thin-client install, driven through the real CLI
+ * dispatcher (`__testing.main`) with a recorded `callRemoteTool`.
+ *
+ * Contracts protected:
+ * - the link commands forward an ambient GBRAIN_SOURCE / .gbrain-source
+ * binding as `source_id` (they declare it now), and an empty result says
+ * which binding narrowed it plus the exact `--all-sources` rerun command;
+ * - mixed versions: when the brain host answers with an unknown-parameter
+ * warning for a scope param the client sent (flag, env or dotfile), the
+ * command fails instead of printing the host's unscoped result;
+ * - `gbrain links` is the CLI name with `get_links` kept as an alias.
+ * Regression that fails it: the CLI printing the unscoped result (exit 0) or
+ * dropping the ambient scope, as on the wave-5 base. The stub response is
+ * built with the server's own warning builder (`buildUnknownParamWarnBlock`).
+ *
+ * Serial file: mock.module patches config.ts and mcp-client.ts process-wide.
+ */
+import { describe, test, expect, beforeAll, beforeEach, afterAll, mock } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { withEnv } from './helpers/with-env.ts';
+import { buildUnknownParamWarnBlock } from '../src/mcp/validate-params.ts';
+
+type Call = { name: string; params: Record<string, unknown> };
+const calls: Call[] = [];
+let respond: (call: Call) => unknown = () => ({ content: [{ type: 'text', text: '[]' }] });
+
+const realConfig = await import('../src/core/config.ts');
+mock.module('../src/core/config.ts', () => ({
+ ...realConfig,
+ loadConfig: () => ({
+ engine: 'postgres',
+ remote_mcp: { issuer_url: 'https://brain.example.test', mcp_url: 'https://brain.example.test/mcp', oauth_client_id: 'cid' },
+ }),
+ isThinClient: () => true,
+}));
+
+const realMcpClient = await import('../src/core/mcp-client.ts');
+mock.module('../src/core/mcp-client.ts', () => ({
+ ...realMcpClient,
+ callRemoteTool: async (_cfg: unknown, name: string, params: Record<string, unknown>) => {
+ const c = { name, params: { ...params } };
+ calls.push(c);
+ return respond(c);
+ },
+}));
+
+const { __testing } = await import('../src/cli.ts');
+
+class ExitSignal extends Error {
+ constructor(readonly code: number) { super(`process.exit(${code})`); }
+}
+
+let cwd: string;
+let dotfileDir: string;
+const savedCwd = process.cwd();
+
+beforeAll(() => {
+ cwd = mkdtempSync(join(tmpdir(), 'gbrain-5827-thin-'));
+ dotfileDir = mkdtempSync(join(tmpdir(), 'gbrain-5827-dot-'));
+ writeFileSync(join(dotfileDir, '.gbrain-source'), 'wiki\n');
+});
+
+afterAll(() => {
+ process.chdir(savedCwd);
+ rmSync(cwd, { recursive: true, force: true });
+ rmSync(dotfileDir, { recursive: true, force: true });
+});
+
+beforeEach(() => {
+ calls.length = 0;
+ respond = () => ({ content: [{ type: 'text', text: '[]' }] });
+});
+
+async function run(argv: string[], opts: { env?: Record<string, string | undefined>; dir?: string } = {}) {
+ const out: string[] = [];
+ const err: string[] = [];
+ const saved = { log: console.log, error: console.error, exit: process.exit, argv: process.argv,
+ stderr: process.stderr.write };
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ process.stderr.write = ((chunk: unknown) => { err.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ (process as unknown as { exit: (code?: number) => never }).exit = ((code?: number) => {
+ throw new ExitSignal(code ?? 0);
+ }) as never;
+ process.argv = [saved.argv[0]!, 'gbrain', ...argv];
+ process.chdir(opts.dir ?? cwd);
+ let code = 0;
+ try {
+ await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_NO_BANNER: '1', ...opts.env }, () => __testing.main());
+ } catch (e) {
+ if (!(e instanceof ExitSignal)) throw e;
+ code = e.code;
+ } finally {
+ console.log = saved.log;
+ console.error = saved.error;
+ process.stderr.write = saved.stderr;
+ (process as unknown as { exit: typeof saved.exit }).exit = saved.exit;
+ process.argv = saved.argv;
+ process.chdir(savedCwd);
+ }
+ return { code, log: out.join('\n'), stderr: err.join('\n') };
+}
+
+/** What a pre-#5827 host sends back: the unscoped result plus a WP3 warning per ignored key. */
+function oldHost(ignoredKeys: string[], body: unknown = [{ from_slug: 'x', to_slug: 'y' }]) {
+ return (c: Call) => {
+ const warnings = ignoredKeys.filter((k) => k in c.params).map((param) => ({ code: 'unknown_param', param }));
+ return {
+ content: [
+ { type: 'text', text: JSON.stringify(body) },
+ ...(warnings.length ? [{ type: 'text', text: buildUnknownParamWarnBlock(warnings as never) }] : []),
+ ],
+ ...(warnings.length ? { _meta: { warnings } } : {}),
+ };
+ };
+}
+
+describe('#5827 thin-client link reads follow ambient scope', () => {
+ test('GBRAIN_SOURCE is sent as source_id; an empty result names the binding and the --all-sources rerun', async () => {
+ const r = await run(['backlinks', 'companies/acme-example'], { env: { GBRAIN_SOURCE: 'business' } });
+ expect(r.code).toBe(0);
+ expect(calls).toEqual([{ name: 'get_backlinks', params: { slug: 'companies/acme-example', source_id: 'business' } }]);
+ expect(r.stderr).toContain(
+ '[gbrain] backlinks: no results within source business (set by GBRAIN_SOURCE). ' +
+ 'To read every source you can see: gbrain backlinks companies/acme-example --all-sources',
+ );
+ });
+
+ test('a .gbrain-source pin is sent as source_id and named in the hint', async () => {
+ const r = await run(['links', 'people/alice-example'], { dir: dotfileDir });
+ expect(calls[0]).toEqual({ name: 'get_links', params: { slug: 'people/alice-example', source_id: 'wiki' } });
+ expect(r.stderr).toContain('no results within source wiki (set by .gbrain-source)');
+ expect(r.stderr).toContain('gbrain links people/alice-example --all-sources');
+ });
+
+ test('a non-empty narrowed result prints no hint, and --all-sources goes on the wire', async () => {
+ respond = () => ({ content: [{ type: 'text', text: JSON.stringify([{ from_slug: 'a', to_slug: 'b' }]) }] });
+ const r = await run(['backlinks', 'companies/acme-example'], { env: { GBRAIN_SOURCE: 'business' } });
+ expect(r.code).toBe(0);
+ expect(r.stderr).not.toContain('no results within source');
+ calls.length = 0;
+ await run(['graph', 'people/alice-example', '--all-sources'], { env: { GBRAIN_SOURCE: 'business' } });
+ expect(calls[0]).toEqual({ name: 'traverse_graph', params: { slug: 'people/alice-example', all_sources: true } });
+ });
+
+ test('the get_links alias still dispatches', async () => {
+ await run(['get_links', 'people/alice-example', '--source-id', 'wiki']);
+ expect(calls[0]).toEqual({ name: 'get_links', params: { slug: 'people/alice-example', source_id: 'wiki' } });
+ });
+
+ test('--source with --source-id is refused before the wire', async () => {
+ const r = await run(['backlinks', 'companies/acme-example', '--source', 'business', '--source-id', 'wiki']);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain('Pass either --source or --source-id/--all-sources, not both.');
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('#5827 mixed versions: a host that ignores a scope param fails loudly', () => {
+ const origins: Array<[string, string[], () => { env?: Record<string, string | undefined>; dir?: string }]> = [
+ ['--source-id flag', ['backlinks', 'companies/acme-example', '--source-id', 'business'], () => ({})],
+ ['--source flag', ['backlinks', 'companies/acme-example', '--source', 'business'], () => ({})],
+ ['GBRAIN_SOURCE', ['backlinks', 'companies/acme-example'], () => ({ env: { GBRAIN_SOURCE: 'business' } })],
+ ['.gbrain-source', ['backlinks', 'companies/acme-example'], () => ({ dir: dotfileDir })],
+ ];
+ for (const [origin, argv, opts] of origins) {
+ test(`source_id from ${origin}`, async () => {
+ respond = oldHost(['source_id', 'all_sources']);
+ const r = await run(argv, opts());
+ expect(calls[0]?.params.source_id).toBeDefined();
+ // Exit 1 is raised before the result is formatted, so nothing reaches stdout.
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain(
+ 'the brain host does not support source_id on get_backlinks; upgrade the host (gbrain upgrade on the brain host)',
+ );
+ });
+ }
+
+ test('all_sources is checked the same way', async () => {
+ respond = oldHost(['source_id', 'all_sources']);
+ const r = await run(['links', 'people/alice-example', '--all-sources']);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain('the brain host does not support all_sources on get_links');
+ });
+
+ test('a host that honors the scope prints the result', async () => {
+ respond = oldHost([]);
+ const r = await run(['backlinks', 'companies/acme-example', '--source-id', 'business']);
+ expect(r.code).toBe(0);
+ expect(r.stderr).not.toContain('does not support');
+ });
+
+ test('an ignored non-scope param this op declares is a stderr warning, not a failure', async () => {
+ respond = oldHost(['direction']);
+ const r = await run(['graph', 'people/alice-example', '--direction', 'in']);
+ expect(r.code).toBe(0);
+ expect(r.stderr).toContain('the brain host ignored parameter "direction" on traverse_graph');
+ });
+});