mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 10:22:34 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00460441b7 | ||
|
|
fb5e7476f7 |
+22
-1
@@ -365,6 +365,12 @@ 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}`);
|
||||
@@ -761,6 +767,10 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
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>();
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
@@ -778,13 +788,20 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
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]);
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,7 +813,11 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[op.cliHints.stdin] = stdinContent;
|
||||
// #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;
|
||||
}
|
||||
|
||||
return params;
|
||||
|
||||
@@ -151,100 +151,6 @@ export function shouldSpawnAutopilotWorker(args: string[]): boolean {
|
||||
return !args.includes('--no-worker');
|
||||
}
|
||||
|
||||
/**
|
||||
* #1525 — positional subcommand translation.
|
||||
*
|
||||
* Pre-fix, `gbrain autopilot status` silently fell through to "start daemon"
|
||||
* because `runAutopilot()` only branched on flag forms (`--status`, etc.).
|
||||
* `status` was treated as a stray positional and ignored.
|
||||
*
|
||||
* This translator maps known positional subcommands to their flag form so
|
||||
* `autopilot status` is equivalent to `autopilot --status`, then rejects
|
||||
* any unrecognized positional with a fail-loud error before any side
|
||||
* effect (lockfile, daemon spawn, sync dispatch) runs.
|
||||
*
|
||||
* Scope decisions:
|
||||
* - Known aliases: `status` → `--status`, `install` → `--install`,
|
||||
* `uninstall` → `--uninstall`, `start` → (drop; default daemon launch).
|
||||
* - `stop` is intentionally NOT aliased here. Stopping a running daemon
|
||||
* is a new behavior (read PID from lock, SIGTERM, drain) that deserves
|
||||
* its own design and PR. Users typing `gbrain autopilot stop` today get
|
||||
* the unknown-positional error with the canonical alternatives.
|
||||
* - At most one positional allowed; multiple positionals fail loud.
|
||||
*/
|
||||
// Every flag that consumes the NEXT argv token. Missing one here makes the
|
||||
// translator misread the flag's value as a positional subcommand and exit 2
|
||||
// (e.g. `--install --target linux-cron`). Keep in sync with parseArg call sites.
|
||||
const AUTOPILOT_VALUE_FLAGS = new Set(['--repo', '--interval', '--target']);
|
||||
const AUTOPILOT_POSITIONAL_ALIASES: Record<string, string | null> = {
|
||||
status: '--status',
|
||||
install: '--install',
|
||||
uninstall: '--uninstall',
|
||||
start: null, // drop the positional; default behavior is daemon launch
|
||||
};
|
||||
|
||||
export type PositionalTranslation =
|
||||
| { ok: true; args: string[] }
|
||||
| {
|
||||
ok: false;
|
||||
reason: 'unknown_subcommand' | 'multiple_subcommands';
|
||||
message: string;
|
||||
};
|
||||
|
||||
export function translatePositionalSubcommands(args: string[]): PositionalTranslation {
|
||||
const out: string[] = [];
|
||||
let positionalSeen = false;
|
||||
let i = 0;
|
||||
while (i < args.length) {
|
||||
const a = args[i];
|
||||
if (AUTOPILOT_VALUE_FLAGS.has(a)) {
|
||||
// Pass through the flag and its value untouched. If the value is
|
||||
// missing at end-of-argv, fall through so the existing parseArg
|
||||
// path can report the broken usage.
|
||||
out.push(a);
|
||||
if (i + 1 < args.length) {
|
||||
out.push(args[i + 1]);
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (a.startsWith('-')) {
|
||||
out.push(a);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Positional subcommand.
|
||||
if (positionalSeen) {
|
||||
const known = Object.keys(AUTOPILOT_POSITIONAL_ALIASES).join(', ');
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'multiple_subcommands',
|
||||
message: `Multiple subcommands given. Use only one of: ${known}.`,
|
||||
};
|
||||
}
|
||||
positionalSeen = true;
|
||||
if (a in AUTOPILOT_POSITIONAL_ALIASES) {
|
||||
const alias = AUTOPILOT_POSITIONAL_ALIASES[a];
|
||||
if (alias) out.push(alias);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
const known = Object.keys(AUTOPILOT_POSITIONAL_ALIASES).join(', ');
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'unknown_subcommand',
|
||||
message:
|
||||
`Unknown subcommand: \`${a}\`.\n` +
|
||||
`Allowed subcommands: ${known}.\n` +
|
||||
`Or use the flag form: --status, --install, --uninstall.\n` +
|
||||
`Run \`gbrain autopilot --help\` for full usage.`,
|
||||
};
|
||||
}
|
||||
return { ok: true, args: out };
|
||||
}
|
||||
|
||||
export function isPidAlive(pid: number): boolean {
|
||||
if (!Number.isFinite(pid) || pid <= 0) return false;
|
||||
try {
|
||||
@@ -457,11 +363,6 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
' gbrain autopilot --install [--repo <path>]\n' +
|
||||
' gbrain autopilot --uninstall\n' +
|
||||
' gbrain autopilot --status [--json]\n\n' +
|
||||
'Subcommand aliases:\n' +
|
||||
' gbrain autopilot status → --status\n' +
|
||||
' gbrain autopilot install → --install\n' +
|
||||
' gbrain autopilot uninstall → --uninstall\n' +
|
||||
' gbrain autopilot start → (default daemon launch)\n\n' +
|
||||
'Self-maintaining brain daemon. Runs the full maintenance cycle\n' +
|
||||
'(lint + backlinks + sync + extract + embed + orphans) on an interval.\n\n' +
|
||||
'For a one-shot cron-triggered cycle, see `gbrain dream`.',
|
||||
@@ -469,16 +370,6 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// #1525: translate positional subcommands to their flag form BEFORE any
|
||||
// side effect (lockfile, daemon spawn, sync dispatch). Unknown positionals
|
||||
// fail loud here rather than silently starting the daemon.
|
||||
const translated = translatePositionalSubcommands(args);
|
||||
if (!translated.ok) {
|
||||
console.error(translated.message);
|
||||
process.exit(2);
|
||||
}
|
||||
args = translated.args;
|
||||
|
||||
if (args.includes('--install')) {
|
||||
await installDaemon(engine, args);
|
||||
return;
|
||||
|
||||
@@ -48,6 +48,7 @@ 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`. */
|
||||
|
||||
+22
-1
@@ -301,6 +301,17 @@ 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.
|
||||
@@ -314,7 +325,17 @@ export async function importFromContent(
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseMarkdown(content, slug + '.md', { activePack: opts.activePack });
|
||||
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})`);
|
||||
}
|
||||
|
||||
// v0.42 (#1699 trust boundary): strip gate-owned markers from UNTRUSTED
|
||||
// input. parseMarkdown preserves every frontmatter key except type/title/
|
||||
|
||||
+46
-1
@@ -11,7 +11,8 @@ export type ParseValidationCode =
|
||||
| 'NULL_BYTES'
|
||||
| 'NESTED_QUOTES'
|
||||
| 'NON_STRING_FIELD'
|
||||
| 'EMPTY_FRONTMATTER';
|
||||
| 'EMPTY_FRONTMATTER'
|
||||
| 'MULTI_FRONTMATTER';
|
||||
|
||||
export interface ParseValidationError {
|
||||
code: ParseValidationCode;
|
||||
@@ -331,6 +332,50 @@ 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
/**
|
||||
* Tests for translatePositionalSubcommands() — the v0.41.x #1525 fix that
|
||||
* prevents `gbrain autopilot status` from silently starting the daemon.
|
||||
*
|
||||
* IRON RULE regression guard: the exact ticket repro (`gbrain autopilot
|
||||
* status`) MUST translate to `--status`, not fall through to the default
|
||||
* daemon launch. Verified by the "ticket-exact repro" case below.
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { translatePositionalSubcommands } from '../src/commands/autopilot.ts';
|
||||
|
||||
describe('translatePositionalSubcommands — known aliases', () => {
|
||||
test('IRON RULE — `autopilot status` translates to `--status` (ticket #1525 repro)', () => {
|
||||
const r = translatePositionalSubcommands(['status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--status']);
|
||||
});
|
||||
|
||||
test('`install` translates to `--install`', () => {
|
||||
const r = translatePositionalSubcommands(['install']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--install']);
|
||||
});
|
||||
|
||||
test('`uninstall` translates to `--uninstall`', () => {
|
||||
const r = translatePositionalSubcommands(['uninstall']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--uninstall']);
|
||||
});
|
||||
|
||||
test('`start` drops the positional (default daemon launch)', () => {
|
||||
const r = translatePositionalSubcommands(['start']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual([]);
|
||||
});
|
||||
|
||||
test('`start --json` drops only the positional, keeps the flag', () => {
|
||||
const r = translatePositionalSubcommands(['start', '--json']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--json']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('translatePositionalSubcommands — flag/positional interleaving', () => {
|
||||
test('`status --json` preserves the trailing flag', () => {
|
||||
const r = translatePositionalSubcommands(['status', '--json']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--status', '--json']);
|
||||
});
|
||||
|
||||
test('`--json status` preserves the leading flag', () => {
|
||||
const r = translatePositionalSubcommands(['--json', 'status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--json', '--status']);
|
||||
});
|
||||
|
||||
test('`--repo /foo status` does not mis-classify the path as positional', () => {
|
||||
const r = translatePositionalSubcommands(['--repo', '/foo', 'status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--repo', '/foo', '--status']);
|
||||
});
|
||||
|
||||
test('`--interval 300 install` does not mis-classify the number as positional', () => {
|
||||
const r = translatePositionalSubcommands(['--interval', '300', 'install']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--interval', '300', '--install']);
|
||||
});
|
||||
|
||||
test('`--install --target linux-cron` does not mis-classify the target as positional', () => {
|
||||
// --target is installDaemon's value flag; its value must never be read
|
||||
// as a positional subcommand (regression guard for the review fix).
|
||||
const r = translatePositionalSubcommands(['--install', '--target', 'linux-cron']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--install', '--target', 'linux-cron']);
|
||||
});
|
||||
|
||||
test('`install --target macos` keeps the alias translation and the target value', () => {
|
||||
const r = translatePositionalSubcommands(['install', '--target', 'macos']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--install', '--target', 'macos']);
|
||||
});
|
||||
|
||||
test('value-flag at end of argv with missing value passes through (so parseArg can report it)', () => {
|
||||
const r = translatePositionalSubcommands(['--repo']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--repo']);
|
||||
});
|
||||
|
||||
test('value-flag whose value looks like an alias is NOT translated', () => {
|
||||
// `--repo status` means "use repo path 'status'", not "show status".
|
||||
// Translator must not destructure the value of --repo.
|
||||
const r = translatePositionalSubcommands(['--repo', 'status']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--repo', 'status']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('translatePositionalSubcommands — pass-through cases', () => {
|
||||
test('empty args returns empty args', () => {
|
||||
const r = translatePositionalSubcommands([]);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual([]);
|
||||
});
|
||||
|
||||
test('flag-only invocation passes through unchanged', () => {
|
||||
const r = translatePositionalSubcommands(['--status', '--json']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['--status', '--json']);
|
||||
});
|
||||
|
||||
test('short flag `-h` passes through unchanged', () => {
|
||||
const r = translatePositionalSubcommands(['-h']);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(['-h']);
|
||||
});
|
||||
|
||||
test('all known bare flags pass through unchanged', () => {
|
||||
const flags = ['--help', '--install', '--uninstall', '--status', '--json', '--inline', '--no-worker'];
|
||||
const r = translatePositionalSubcommands(flags);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.args).toEqual(flags);
|
||||
});
|
||||
});
|
||||
|
||||
describe('translatePositionalSubcommands — rejection of unknown positionals', () => {
|
||||
test('unknown positional `foo` fails with reason=unknown_subcommand + structured message', () => {
|
||||
const r = translatePositionalSubcommands(['foo']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('Unknown subcommand: `foo`');
|
||||
expect(r.message).toContain('status');
|
||||
expect(r.message).toContain('install');
|
||||
expect(r.message).toContain('uninstall');
|
||||
expect(r.message).toContain('--help');
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown positional `stop` fails with reason=unknown_subcommand (NOT silently aliased)', () => {
|
||||
// Stop is mentioned in the ticket but deliberately NOT aliased in this
|
||||
// PR — stopping a running daemon is a new behavior, not just an alias.
|
||||
// Until that feature lands separately, `stop` must fail loud rather
|
||||
// than starting the daemon (the bug we're fixing).
|
||||
const r = translatePositionalSubcommands(['stop']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('Unknown subcommand: `stop`');
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown positional `status-detail` (close-but-not-matching) fails', () => {
|
||||
const r = translatePositionalSubcommands(['status-detail']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('Unknown subcommand: `status-detail`');
|
||||
}
|
||||
});
|
||||
|
||||
test('multiple positionals fail with reason=multiple_subcommands (`start install`)', () => {
|
||||
const r = translatePositionalSubcommands(['start', 'install']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('multiple_subcommands');
|
||||
expect(r.message).toContain('Multiple subcommands');
|
||||
}
|
||||
});
|
||||
|
||||
test('multiple positionals fail even when both are known aliases (`status install`)', () => {
|
||||
const r = translatePositionalSubcommands(['status', 'install']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('multiple_subcommands');
|
||||
expect(r.message).toContain('Multiple subcommands');
|
||||
}
|
||||
});
|
||||
|
||||
test('known-then-unknown rejects with multiple_subcommands (first-positional-wins)', () => {
|
||||
// First positional is known, second is not. Rejection comes from the
|
||||
// multiple-positional rule, which fires before the unknown check; the
|
||||
// intent is "only one subcommand allowed."
|
||||
const r = translatePositionalSubcommands(['status', 'garbage']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.reason).toBe('multiple_subcommands');
|
||||
});
|
||||
|
||||
test('unknown-then-known rejects on the unknown (unknown fires before second-positional check)', () => {
|
||||
const r = translatePositionalSubcommands(['garbage', 'status']);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) {
|
||||
expect(r.reason).toBe('unknown_subcommand');
|
||||
expect(r.message).toContain('garbage');
|
||||
}
|
||||
});
|
||||
});
|
||||
+70
-1
@@ -1,4 +1,8 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { join, resolve } from 'path';
|
||||
import { mkdtempSync, rmSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { parseOpArgs } from '../src/cli.ts';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
|
||||
@@ -20,5 +24,70 @@ 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);
|
||||
});
|
||||
|
||||
@@ -708,3 +708,32 @@ 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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -256,6 +256,56 @@ 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 });
|
||||
|
||||
Reference in New Issue
Block a user