Compare commits

..
Author SHA1 Message Date
Garry TanandClaude Fable 5 55290e9088 docs(tutorial): drop dead --remote flag from company-brain search examples
With unknown op flags now a hard error (this PR), the tutorial's
`gbrain search ... --remote` invocations would fail: no code path ever
read a --remote flag — thin-client installs route shared ops through the
remote MCP server automatically. Update the three examples to the
flagless form and explain the automatic routing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 11:10:47 -07:00
04a2a1f7bf fix(cli): put --file, reject unknown op flags, list pagination (#380, #856, #2876)
Three CLI ergonomics fixes on the shared-op dispatch path:

- parseOpArgs now hard-errors on undeclared flags instead of silently
  swallowing them into params (#380). A pass-through allowlist keeps the
  undeclared-but-honored flags working: --source (makeContext's source
  resolver), --brain (mount axis), --dry-run (ctx.dryRun), --json.
  Value-taking flags with no value also error instead of being dropped.

- `gbrain put SLUG --file PATH` reads content from a file (#380, takeover
  of #856). Driven by the op's cliHints.stdin declaration rather than
  put_page hard-coding, so volunteer-context gets it too. Mutually
  exclusive with --content/stdin in either flag order; 5MB cap shared
  with stdin; unreadable path is a loud error instead of an empty page.
  put --help documents the flag.

- `--json` on shared ops now actually emits raw JSON (docs already
  promised it); same seam on local-engine and thin-client routed paths.

- list_pages declares `offset` (both engines already supported it on
  PageFilters) and the limit description discloses the 100-row cap
  (#2876), so `gbrain list` can paginate past 100 instead of silently
  truncating.

Co-authored-by: Kage18 <Kage18@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:40:45 -07:00
11 changed files with 260 additions and 250 deletions
+5 -3
View File
@@ -223,14 +223,16 @@ export GBRAIN_REMOTE_CLIENT_ID=<Alice's client_id>
export GBRAIN_REMOTE_CLIENT_SECRET=<Alice's client_secret>
export GBRAIN_REMOTE_MCP_URL=https://brain.acme-co.com/mcp
gbrain search "performance review" --remote
gbrain search "performance review"
```
(On a thin-client install every shared op routes through the remote MCP server automatically — no flag needed. The env vars select whose credentials the call uses.)
Alice should see results only from `customers` and `shared`. The performance-review notes live in `internal`, which she's not scoped to read. She shouldn't see them.
```bash
# Terminal 2, as Bob (export his credentials similarly)
gbrain search "performance review" --remote
gbrain search "performance review"
```
Bob should see the performance-review notes from `internal`, plus anything related from `shared`. He shouldn't see anything that lives only in `customers`.
@@ -514,7 +516,7 @@ The first sync embeds every page, which takes time. Check `gbrain sources status
### "I see a page I shouldn't see"
This shouldn't happen, but if you suspect it, run `gbrain search <query> --remote --json` as the constrained client and inspect the `source_id` field on every returned result. Every row should be in the client's `--federated-read` set. If one isn't, file an issue with the exact slug and source IDs.
This shouldn't happen, but if you suspect it, run `gbrain search <query> --json` as the constrained client (thin-client install, with the client's `GBRAIN_REMOTE_*` env exported) and inspect the `source_id` field on every returned result. Every row should be in the client's `--federated-read` set. If one isn't, file an issue with the exact slug and source IDs.
### "The synthesized answer is wrong"
+85 -27
View File
@@ -365,12 +365,6 @@ async function main() {
if (def.required && params[key] === undefined) {
if (queryHasAlt && key === 'query') continue;
const cliName = op.cliHints?.name || op.name;
// #2822: when the missing param is the op's stdin-fed one, the usage
// line alone is misleading (the positionals may all be present — the
// pipe was just empty). Name the real problem.
if (op.cliHints?.stdin === key) {
console.error(`Error: required "${key}" is missing — stdin was empty or not piped. Pipe content on stdin or pass --${key.replace(/_/g, '-')}.`);
}
const positional = op.cliHints?.positional || [];
const usage = positional.map(p => `<${p}>`).join(' ');
console.error(`Usage: gbrain ${cliName} ${usage}`);
@@ -470,7 +464,11 @@ async function main() {
// routed path. Date → ISO string; bigint → string (postgres.js shape);
// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
const result = JSON.parse(JSON.stringify(rawResult, bigintToStringReplacer));
const output = formatResult(op.name, result);
// #380 pass-through: `--json` (undeclared on most ops, promised by docs)
// emits the raw op result instead of the human formatter.
const output = params.json === true
? JSON.stringify(result, null, 2) + '\n'
: formatResult(op.name, result);
if (output) process.stdout.write(output);
} catch (e: unknown) {
// v0.42.20.0 (codex D4): on error, set exitCode + return so the `finally`
@@ -553,7 +551,10 @@ async function runThinClientRouted(
signal: sigintController.signal,
});
const result = unpackToolResult(raw);
const output = formatResult(op.name, result);
// #380: same --json seam as the local-engine path (renderer parity).
const output = params.json === true
? JSON.stringify(result, null, 2) + '\n'
: formatResult(op.name, result);
if (output) process.stdout.write(output);
} catch (e: unknown) {
if (e instanceof RemoteMcpError) {
@@ -763,14 +764,28 @@ export function resolveQueryImage(
return { path: imagePath, base64, mime };
}
/**
* #380: undeclared flags that are honored DOWNSTREAM of parseOpArgs and must
* keep passing through when unknown flags become hard errors:
* - source → makeContext's resolveSourceId (the --source axis)
* - brain → the mount/brain routing axis (docs promise the flag)
* - dry_run → makeContext's ctx.dryRun (ops without a declared dry_run)
* - json → raw-JSON output seam (local + thin-client paths)
*/
const PASSTHROUGH_VALUE_FLAGS = new Set(['source', 'brain']);
const PASSTHROUGH_BOOL_FLAGS = new Set(['dry_run', 'json']);
export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
const params: Record<string, unknown> = {};
const positional = op.cliHints?.positional || [];
let posIdx = 0;
// #2822: track which params came from positionals so a later flag that
// silently discards one (`gbrain put CONTENT --slug foo` — CONTENT was
// parsed as the slug) gets a stderr warning instead of vanishing.
const positionallySet = new Set<string>();
const cliName = op.cliHints?.name || op.name;
const MAX_STDIN = 5_000_000; // 5MB cap, shared by stdin and --file
// #380: `--file <path>` fills the op's declared stdin param (put's `content`)
// from a file. Driven by cliHints.stdin — no per-op hard-coding — and
// disabled when the op declares a real `file` param of its own.
const fileParam = op.cliHints?.stdin && !op.params.file ? op.cliHints.stdin : undefined;
let filePath: string | undefined;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
@@ -784,40 +799,79 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
}
}
const key = arg.slice(2).replace(/-/g, '_');
if (fileParam && key === 'file') {
if (i + 1 >= args.length) {
console.error(`Error: ${arg} requires a value.`);
process.exit(1);
}
filePath = args[++i];
continue;
}
const paramDef = op.params[key];
if (paramDef?.type === 'boolean') {
if (!paramDef) {
if (PASSTHROUGH_BOOL_FLAGS.has(key)) {
params[key] = true;
continue;
}
if (PASSTHROUGH_VALUE_FLAGS.has(key)) {
if (i + 1 >= args.length) {
console.error(`Error: ${arg} requires a value.`);
process.exit(1);
}
params[key] = args[++i];
continue;
}
// #380: unknown flags were silently swallowed into params, so typos
// like `put --file` created empty pages instead of erroring.
console.error(`Unknown option for gbrain ${cliName}: ${arg}`);
console.error(`Run 'gbrain ${cliName} --help' for valid flags.`);
process.exit(1);
}
if (paramDef.type === 'boolean') {
params[key] = true;
} else if (i + 1 < args.length) {
if (positionallySet.has(key) && params[key] !== args[i + 1]) {
console.error(`Warning: ${arg} overrides the positional <${key}> value ${JSON.stringify(params[key])}.`);
}
params[key] = args[++i];
if (paramDef?.type === 'number') params[key] = Number(params[key]);
if (paramDef.type === 'number') params[key] = Number(params[key]);
} else {
console.error(`Error: ${arg} requires a value.`);
process.exit(1);
}
} else if (posIdx < positional.length) {
const key = positional[posIdx++];
const paramDef = op.params[key];
if (params[key] !== undefined && params[key] !== (paramDef?.type === 'number' ? Number(arg) : arg)) {
console.error(`Warning: positional <${key}> overrides the earlier --${key.replace(/_/g, '-')} value ${JSON.stringify(params[key])}.`);
}
params[key] = paramDef?.type === 'number' ? Number(arg) : arg;
positionallySet.add(key);
}
}
// #380: resolve --file AFTER the loop so --file/--content conflicts are
// caught in either order.
if (filePath !== undefined && fileParam) {
if (params[fileParam] !== undefined) {
console.error(`Error: use only one of --file, --${fileParam}, or stdin for gbrain ${cliName}.`);
process.exit(1);
}
let fileContent: string;
try {
fileContent = readFileSync(filePath, 'utf-8');
} catch (e) {
console.error(`Error: cannot read --file ${filePath}: ${e instanceof Error ? e.message : String(e)}`);
process.exit(1);
}
if (Buffer.byteLength(fileContent, 'utf-8') > MAX_STDIN) {
console.error(`Error: file content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
process.exit(1);
}
params[fileParam] = fileContent;
}
// Read stdin for content params
if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
const stdinContent = readFileSync(0, 'utf-8');
const MAX_STDIN = 5_000_000; // 5MB
if (Buffer.byteLength(stdinContent, 'utf-8') > MAX_STDIN) {
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
process.exit(1);
}
// #2822: empty/whitespace-only stdin (cron with no input, broken pipe)
// stays UNSET so the required-param check rejects the call instead of
// silently writing an empty page (0 chunks, invisible to search and
// embed --stale).
if (stdinContent.trim().length > 0) params[op.cliHints.stdin] = stdinContent;
params[op.cliHints.stdin] = stdinContent;
}
return params;
@@ -2274,6 +2328,10 @@ export function printOpHelp(op: Operation, invokedName?: string) {
const prefix = isPos ? ` <${key}>` : ` --${key.replace(/_/g, '-')}`;
console.log(`${prefix.padEnd(28)} ${def.description || ''}${req}`);
}
// #380: ops that read stdin also accept --file <path> (parseOpArgs).
if (op.cliHints?.stdin && !op.params.file) {
console.log(`${' --file <path>'.padEnd(28)} Read ${op.cliHints.stdin} from a file (alternative to --${op.cliHints.stdin} or stdin)`);
}
}
}
-1
View File
@@ -48,7 +48,6 @@ const FRONTMATTER_RULE_NAMES: Record<ParseValidationCode, string> = {
NESTED_QUOTES: 'frontmatter-nested-quotes',
NON_STRING_FIELD: 'frontmatter-non-string-field',
EMPTY_FRONTMATTER: 'frontmatter-empty',
MULTI_FRONTMATTER: 'frontmatter-multi',
};
/** Codes whose lint findings are fixable by `gbrain frontmatter validate --fix`. */
+1 -22
View File
@@ -301,17 +301,6 @@ export async function importFromContent(
// silently fabricated a duplicate at (default, slug) — causing later
// bare-slug subqueries (getTags, deleteChunks, etc.) to crash with 21000.
const sourceId = opts.sourceId;
// #2822: reject empty/whitespace-only content before any work happens. An
// empty page writes 0 chunks — invisible to search AND to `embed --stale`
// (nothing to embed), so the mistake never surfaces. Empty content is
// always a caller bug (empty piped stdin, bad shell substitution). Thrown
// (not returned) so every wrapper site surfaces the message, matching the
// ContentSanityBlockError flow.
if (content.trim().length === 0) {
throw new Error(
`Content for "${slug}" is empty; refusing to write an empty page (0 chunks would be invisible to search and embed --stale).`,
);
}
// Reject oversized payloads before any parsing, chunking, or embedding happens.
// Uses Buffer.byteLength to count UTF-8 bytes the same way disk size would,
// so the network path behaves identically to the file path.
@@ -325,17 +314,7 @@ export async function importFromContent(
};
}
const parsed = parseMarkdown(content, slug + '.md', { activePack: opts.activePack, validate: true });
// #2743: reject stacked frontmatter (the double-put corruption class —
// already-serialized markdown re-wrapped in fresh frontmatter). gray-matter
// parses only the first block; the second would land verbatim in the body
// and poison every subsequent round-trip. Only MULTI_FRONTMATTER rejects
// here — the other validation codes keep their lint-only semantics.
const multiFm = parsed.errors?.find(e => e.code === 'MULTI_FRONTMATTER');
if (multiFm) {
throw new Error(`MULTI_FRONTMATTER: ${multiFm.message} (slug "${slug}", line ${multiFm.line})`);
}
const parsed = parseMarkdown(content, slug + '.md', { activePack: opts.activePack });
// v0.42 (#1699 trust boundary): strip gate-owned markers from UNTRUSTED
// input. parseMarkdown preserves every frontmatter key except type/title/
+1 -46
View File
@@ -11,8 +11,7 @@ export type ParseValidationCode =
| 'NULL_BYTES'
| 'NESTED_QUOTES'
| 'NON_STRING_FIELD'
| 'EMPTY_FRONTMATTER'
| 'MULTI_FRONTMATTER';
| 'EMPTY_FRONTMATTER';
export interface ParseValidationError {
code: ParseValidationCode;
@@ -332,50 +331,6 @@ function collectValidationErrors(
});
}
}
// 9. MULTI_FRONTMATTER (#2743) — a second ---…--- block right after the
// closing fence is stacked frontmatter (the double-put corruption class:
// already-serialized markdown re-wrapped in fresh frontmatter).
// gray-matter parses only the first block and silently leaves the second
// in the body. Heuristic: first non-empty line after the close is `---`,
// a later `---` closes it, EVERY line between is frontmatter-shaped
// (YAML `key:`, `- ` list item, `#` comment, indented continuation, or
// blank — the issue's "stop at the first non-frontmatter character"
// spec), and at least one is a `key:` line. A lone `---` stays a
// markdown horizontal rule, and an hrule followed by prose — even
// colon-prefixed prose like `Note: …` mixed with plain lines — is body
// content, not a stacked block.
let afterClose = closeLine + 1;
while (afterClose < lines.length && lines[afterClose].trim().length === 0) afterClose++;
if (afterClose < lines.length && lines[afterClose].trim() === '---') {
let secondClose = -1;
for (let i = afterClose + 1; i < lines.length; i++) {
const trimmed = lines[i].trim();
if (trimmed === '---') {
secondClose = i;
break;
}
const yamlShaped =
trimmed.length === 0 ||
/^[A-Za-z_][\w-]*\s*:/.test(trimmed) ||
trimmed.startsWith('- ') ||
trimmed === '-' ||
trimmed.startsWith('#') ||
/^\s/.test(lines[i]);
if (!yamlShaped) break; // first non-frontmatter line → body prose, not a stacked block
}
if (
secondClose > afterClose + 1 &&
lines.slice(afterClose + 1, secondClose).some(l => /^\s*[A-Za-z_][\w-]*\s*:/.test(l))
) {
errors.push({
code: 'MULTI_FRONTMATTER',
message:
'Stacked frontmatter: a second ---…--- block follows the frontmatter (double-put corruption); merge into a single frontmatter block',
line: afterClose + 1,
});
}
}
}
/**
+9 -2
View File
@@ -769,7 +769,7 @@ const get_page: Operation = {
const put_page: Operation = {
name: 'put_page',
description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. On the CLI, `gbrain put SLUG --file PATH` reads content from a file (also `--content` or stdin). For provenance write-through and a binary-NUL guard, prefer `gbrain capture --file PATH --slug SLUG` (v0.39.3.0).',
params: {
slug: { type: 'string', required: true, description: 'Page slug' },
content: { type: 'string', required: true, description: 'Full markdown content with YAML frontmatter' },
@@ -1384,7 +1384,10 @@ const list_pages: Operation = {
params: {
type: { type: 'string', description: 'Filter by page type' },
tag: { type: 'string', description: 'Filter by tag' },
limit: { type: 'number', description: 'Max results (default 50)' },
limit: { type: 'number', description: 'Max results (default 50, capped at 100 — use offset to paginate beyond)' },
// #2876: the 100-row cap was silent and there was no way past it even
// though both engines already support OFFSET on listPages.
offset: { type: 'number', description: 'Skip first N results (pagination; pair with limit)' },
// v0.29 — surface filter that already exists on PageFilters.
updated_after: {
type: 'string',
@@ -1415,6 +1418,10 @@ const list_pages: Operation = {
type: p.type as any,
tag: p.tag as string,
limit: clampSearchLimit(p.limit as number | undefined, 50, 100),
// #2876: thread pagination through (engines already honor offset).
offset: Number.isFinite(p.offset as number) && (p.offset as number) > 0
? Math.floor(p.offset as number)
: undefined,
includeDeleted: (p.include_deleted as boolean) === true,
updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
sort,
+33 -69
View File
@@ -1,12 +1,41 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import { join, resolve } from 'path';
import { mkdtempSync, rmSync } from 'fs';
import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { parseOpArgs } from '../src/cli.ts';
import { operationsByName } from '../src/core/operations.ts';
describe('parseOpArgs', () => {
// #380: `gbrain put SLUG --file PATH` reads content from the file instead
// of silently swallowing the flag and creating an empty page.
test('put --file reads the stdin param (content) from a file', () => {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-put-file-'));
try {
const pagePath = join(dir, 'page.md');
writeFileSync(pagePath, '# From file\n\nBody loaded from --file.\n');
const params = parseOpArgs(operationsByName.put_page, ['concepts/from-file', '--file', pagePath]);
expect(params.slug).toBe('concepts/from-file');
expect(params.content).toBe('# From file\n\nBody loaded from --file.\n');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// #380 regression guard: undeclared-but-honored flags must keep passing
// through when unknown flags become hard errors (--source is read by
// makeContext; --json by the output seam; --dry-run by ctx.dryRun).
test('pass-through allowlist flags survive on ops that do not declare them', () => {
const params = parseOpArgs(operationsByName.get_page, [
'people/alice-example', '--source', 'wiki', '--json', '--dry-run',
]);
expect(params).toEqual({
slug: 'people/alice-example',
source: 'wiki',
json: true,
dry_run: true,
});
});
test('--no-<boolean> maps to false without consuming the next flag', () => {
const params = parseOpArgs(operationsByName.query, [
'freshEmbedSourceScope code source',
@@ -24,70 +53,5 @@ describe('parseOpArgs', () => {
source_id: 'gstack-code-repo-0e4763c9',
});
});
describe('positional/flag overwrite warning (#2822)', () => {
const errors: string[] = [];
const origError = console.error;
const captureErrors = () => {
console.error = (...args: unknown[]) => errors.push(args.join(' '));
};
afterEach(() => {
console.error = origError;
errors.length = 0;
});
test('a flag that overwrites a positional value warns to stderr', () => {
captureErrors();
const params = parseOpArgs(operationsByName.query, ['positional text', '--query', 'flag text']);
expect(params.query).toBe('flag text');
expect(errors.some(e => e.includes('Warning') && e.includes('--query'))).toBe(true);
});
test('a positional that overwrites an earlier flag value warns to stderr', () => {
captureErrors();
const params = parseOpArgs(operationsByName.query, ['--query', 'flag text', 'positional text']);
expect(params.query).toBe('positional text');
expect(errors.some(e => e.includes('Warning') && e.includes('<query>'))).toBe(true);
});
test('no warning when flag and positional agree', () => {
captureErrors();
parseOpArgs(operationsByName.query, ['same', '--query', 'same']);
expect(errors).toEqual([]);
});
});
});
describe('gbrain put — empty non-TTY stdin rejects (#2822)', () => {
const REPO = resolve(import.meta.dir, '..');
const CLI = join(REPO, 'src', 'cli.ts');
const runPut = (input: string) => {
// Isolated HOME so a regression can never write into a real brain.
const home = mkdtempSync(join(tmpdir(), 'gbrain-put-empty-'));
try {
return spawnSync('bun', [CLI, 'put', 'inbox/empty-stdin-test'], {
stdio: ['pipe', 'pipe', 'pipe'],
input,
encoding: 'utf-8',
timeout: 60_000,
env: { ...process.env, HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' },
});
} finally {
rmSync(home, { recursive: true, force: true });
}
};
test('empty stdin exits 1 and names the missing content param', () => {
const res = runPut('');
expect(res.status).toBe(1);
expect(res.stderr).toContain('content');
expect(res.stderr).toContain('stdin');
}, 90_000);
test('whitespace-only stdin also exits 1', () => {
const res = runPut(' \n\t\n');
expect(res.status).toBe(1);
expect(res.stderr).toContain('stdin');
}, 90_000);
});
+71 -1
View File
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -120,6 +120,76 @@ describe('CLI dispatch integration', () => {
expect(exitCode).toBe(0);
});
// #380 / PR #856: put --help documents the --file input path.
test('put --help documents --file input', async () => {
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'put', '--help'], {
cwd: repoRoot,
stdout: 'pipe',
stderr: 'pipe',
});
const stdout = await new Response(proc.stdout).text();
const exitCode = await proc.exited;
expect(stdout).toContain('Usage: gbrain put');
expect(stdout).toContain('--file <path>');
expect(exitCode).toBe(0);
});
// #380: unknown flags on shared ops are a hard error (previously silently
// swallowed into params — `put --file` created empty pages). parseOpArgs
// runs BEFORE engine connect, so the error must fire without a brain.
test('unknown shared-op flags fail before DB connection', async () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-unknown-flag-'));
try {
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'get', 'people/alice', '--bogus'], {
cwd: repoRoot,
stdout: 'pipe',
stderr: 'pipe',
env: isolatedEnv(home),
});
const stderr = await new Response(proc.stderr).text();
const exitCode = await proc.exited;
expect(stderr).toContain('Unknown option for gbrain get: --bogus');
expect(stderr).not.toContain('No brain configured');
expect(exitCode).toBe(1);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
test('put rejects combining --file and --content', async () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-put-conflict-'));
try {
const pagePath = join(home, 'page.md');
writeFileSync(pagePath, 'file body\n');
const proc = Bun.spawn(
['bun', 'run', 'src/cli.ts', 'put', 'a/b', '--content', 'inline', '--file', pagePath],
{ cwd: repoRoot, stdout: 'pipe', stderr: 'pipe', env: isolatedEnv(home) },
);
const stderr = await new Response(proc.stderr).text();
const exitCode = await proc.exited;
expect(stderr).toContain('use only one of --file, --content, or stdin');
expect(exitCode).toBe(1);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
test('put --file with a missing path errors instead of writing an empty page', async () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-put-missing-file-'));
try {
const proc = Bun.spawn(
['bun', 'run', 'src/cli.ts', 'put', 'a/b', '--file', join(home, 'nope.md')],
{ cwd: repoRoot, stdout: 'pipe', stderr: 'pipe', env: isolatedEnv(home) },
);
const stderr = await new Response(proc.stderr).text();
const exitCode = await proc.exited;
expect(stderr).toContain('cannot read --file');
expect(exitCode).toBe(1);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
test('upgrade --help prints usage without running upgrade', async () => {
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'upgrade', '--help'], {
cwd: repoRoot,
-29
View File
@@ -708,32 +708,3 @@ body unchanged
expect(shortCircuited).toBe(true);
});
});
describe('importFromContent — empty content guard (#2822)', () => {
test('empty string throws instead of writing an invisible 0-chunk page', async () => {
const engine = mockEngine();
await expect(importFromContent(engine, 'inbox/empty', '', { noEmbed: true })).rejects.toThrow(/empty/i);
expect((engine as any)._calls.find((c: any) => c.method === 'putPage')).toBeUndefined();
});
test('whitespace-only content throws', async () => {
const engine = mockEngine();
await expect(importFromContent(engine, 'inbox/ws', ' \n\t \n', { noEmbed: true })).rejects.toThrow(/empty/i);
});
});
describe('importFromContent — stacked frontmatter rejection (#2743)', () => {
test('double-put shaped content (two ---…--- blocks) throws MULTI_FRONTMATTER', async () => {
const engine = mockEngine();
const md = '---\ntitle: outer\n---\n\n---\ntitle: inner\ntype: concept\n---\n\nreal body';
await expect(importFromContent(engine, 'inbox/double', md, { noEmbed: true })).rejects.toThrow(/MULTI_FRONTMATTER/);
expect((engine as any)._calls.find((c: any) => c.method === 'putPage')).toBeUndefined();
});
test('normal content with horizontal rules in the body still imports', async () => {
const engine = mockEngine();
const md = '---\ntitle: ok\ntype: concept\n---\n\nprose before\n\n---\n\nprose after the rule';
const result = await importFromContent(engine, 'inbox/hrule', md, { noEmbed: true });
expect(result.status).toBe('imported');
});
});
+55
View File
@@ -0,0 +1,55 @@
import { describe, test, expect } from 'bun:test';
import { operationsByName } from '../src/core/operations.ts';
/**
* #2876: `gbrain list --limit` silently clamped at 100 with no pagination.
* list_pages now declares `offset` (both engines already supported it on
* PageFilters) and the limit description discloses the 100-row cap.
*/
describe('list_pages pagination (#2876)', () => {
const listPagesOp = operationsByName.list_pages;
function makeCtx(captured: unknown[]) {
return {
engine: {
listPages: async (filters: unknown) => {
captured.push(filters);
return [];
},
},
config: { engine: 'pglite' },
logger: { info() {}, warn() {}, error() {} },
dryRun: false,
remote: false,
sourceId: 'default',
} as any;
}
test('declares offset param and discloses the 100-row cap on limit', () => {
expect(listPagesOp.params.offset).toBeDefined();
expect(listPagesOp.params.offset.type).toBe('number');
expect(listPagesOp.params.limit.description).toContain('100');
});
test('threads offset through to engine.listPages', async () => {
const captured: any[] = [];
await listPagesOp.handler(makeCtx(captured), { limit: 10, offset: 30 });
expect(captured[0].offset).toBe(30);
expect(captured[0].limit).toBe(10);
});
test('drops negative, non-finite, and zero offsets', async () => {
const captured: any[] = [];
const ctx = makeCtx(captured);
await listPagesOp.handler(ctx, { offset: -5 });
await listPagesOp.handler(ctx, { offset: Infinity });
await listPagesOp.handler(ctx, { offset: 0 });
for (const f of captured) expect(f.offset).toBeUndefined();
});
test('floors fractional offsets', async () => {
const captured: any[] = [];
await listPagesOp.handler(makeCtx(captured), { offset: 7.9 });
expect(captured[0].offset).toBe(7);
});
});
-50
View File
@@ -256,56 +256,6 @@ body`;
});
});
describe('MULTI_FRONTMATTER (#2743)', () => {
test('stacked frontmatter immediately after the close fence', () => {
const md = `${fence}\ntitle: outer\n${fence}\n${fence}\ntitle: inner\ntype: concept\n${fence}\n\nbody`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).toContain('MULTI_FRONTMATTER');
});
test('stacked frontmatter with a blank line between blocks (serializeMarkdown shape)', () => {
const md = `${fence}\ntitle: outer\n${fence}\n\n${fence}\ntitle: inner\n${fence}\n\nbody`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).toContain('MULTI_FRONTMATTER');
});
test('horizontal rules in the body are NOT flagged', () => {
const md = `${fence}\ntitle: ok\n${fence}\n\nsome prose\n\n${fence}\n\nmore prose\n\n${fence}\n\nend`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
});
test('hrule pair at body start without YAML-shaped lines is NOT flagged', () => {
const md = `${fence}\ntitle: ok\n${fence}\n\n${fence}\n\nplain prose between rules\n\n${fence}\n\nend`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
});
test('timeline sentinel form is NOT flagged', () => {
const md = `${fence}\ntitle: ok\n${fence}\n\nbody text\n\n${fence}\n\n## Timeline\n- 2024-01-01: thing`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
});
test('body hrule + colon-prefixed prose (`Note: …`) mixed with plain lines is NOT flagged', () => {
const md = `${fence}\ntitle: ok\ntype: concept\n${fence}\n\n${fence}\n\nNote: remember to follow up\n\nlots of plain prose here\n\n${fence}\n\nmore prose`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
});
test('fence pairing stops at the first non-frontmatter line (no far-fence pairing across prose)', () => {
const md = `${fence}\ntitle: ok\n${fence}\n\n${fence}\n\n${'plain prose line\n'.repeat(40)}TODO: fix the widget\n${'more prose\n'.repeat(40)}${fence}\nend`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).not.toContain('MULTI_FRONTMATTER');
});
test('stacked block with list-valued keys is still flagged', () => {
const md = `${fence}\ntitle: outer\n${fence}\n\n${fence}\ntitle: inner\ntags:\n - a\n - b\n${fence}\n\nbody`;
const parsed = parseMarkdown(md, undefined, { validate: true });
expect(parsed.errors!.map(e => e.code)).toContain('MULTI_FRONTMATTER');
});
});
test('error.line is set for line-bearing errors', () => {
const md = `${fence}\ntype: concept\n${fence}\n# Heading inline\n\nbody\x00drop`;
const parsed = parseMarkdown(md, undefined, { validate: true });