diff --git a/.changeset/1352-cli-flag-values.md b/.changeset/1352-cli-flag-values.md new file mode 100644 index 0000000000..c874b45f2c --- /dev/null +++ b/.changeset/1352-cli-flag-values.md @@ -0,0 +1,12 @@ +--- +"@schlessera/brain": minor +--- + +**Breaking (#1352):** core CLI commands now read flag values through one typed accessor, so a malformed value is a usage error (exit 1, message on stderr, nothing on stdout) in human and JSON modes, refused before any query runs. Valid values keep their meaning, a repeated flag still keeps its last value, and no new upper bound is introduced. + +- **`brain search --limit`**, before: read with `parseInt`, so `10abc` searched with 10, `1.5` with 1, `abc` came back empty with an `FTS search failed: datatype mismatch` warning, and `0` or `-5` was passed on to the query. **After:** a whole number of 1 or more; `abc`, `0`, `-5`, `1.5`, `10abc` and an empty value are refused. +- **`brain search --mode`**, before: an unknown mode ran neither lane and returned nothing without a warning. **After:** `fts`, `vector` or `hybrid`; anything else, including an empty value, is refused (`--mode must be one of fts, vector, hybrid, got "bogus"`). +- **`brain context --max-tokens`** and **`brain briefing --limit`**, before: `parseInt`, so `abc` reached the assembler as `NaN` and briefing silently fell back to 15. **After:** a whole number of 1 or more; `abc`, `0`, `1.5`, `10abc` and an empty value are refused. +- **A value flag with no value** (`brain search q --type`, `brain list --tag --status active`, `brain add "…" --tags`), before: flowed on as `true`, or for `add --tags` failed with exit 2. **After:** `-- needs a value`. + +`brain search --sort` and the date filters keep their existing usage errors. diff --git a/docs/decisions/interpreted-briefing.md b/docs/decisions/interpreted-briefing.md index c71e768189..aeaa091fdd 100644 --- a/docs/decisions/interpreted-briefing.md +++ b/docs/decisions/interpreted-briefing.md @@ -25,14 +25,14 @@ retain sanitized tool requests. ## What the source already supplies `generateBriefing` performs the mechanical work -(`generateBriefing`, `packages/core/src/cli/commands/briefing.ts:183-319`): +(`generateBriefing`, `packages/core/src/cli/commands/briefing.ts:184-320`): focus warnings and linked documents; non-archived deadlines from today through sixty days; overdue reviews strictly before today, with a five-item cap and remaining count; module-aware audit totals and hygiene counts; recent activity, silent modifications and taxonomy-driven staleness. Its existing `now` option permits the evaluation clock without changing product code. The CLI exposes the plain-text report -(`briefingCommand`, `packages/core/src/cli/commands/briefing.ts:321-340`). +(`briefingCommand`, `packages/core/src/cli/commands/briefing.ts:322-341`). The shipped `whatsup` skill gathers that report, may read up to three files, then interprets urgency, groups action and FYI, and writes terse bullets. diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index 1fad8668d8..3a5483b03e 100644 --- a/docs/integration-contract/cli.md +++ b/docs/integration-contract/cli.md @@ -370,6 +370,12 @@ resumption. The host must retain a successful complete export at least every `--baseline` gate; `3` is runs that are not comparable, the report still printed). - Boolean flags never consume the following argument. +- A value flag given without a value (last, or followed by another `--flag`) + is a usage error in `brain search`, `list`, `add`, `read`, `context` and + `briefing` (`--type needs a value`). A repeated flag keeps its last + value. **Breaking in 0.45.0 (#1352):** such a flag used to flow on as `true` + (`brain search --type`, `brain list --tag --status active`), and a bare + `brain add --tags` failed with exit `2`. - End-of-options: a bare `--` stops flag parsing, and every later argument is positional verbatim. Output-mode and help flags after it are positional too (additive in 0.33.0). @@ -380,11 +386,11 @@ resumption. The host must retain a successful complete export at least every | Command | Shape | |---------|-------| -| `brain search "q" --json` | `{ "results": SearchResult[], "warnings": string[] }` — `warnings` reports degraded modes (no vectors, model mismatch, missing key, a reranker that did not run, a [withheld provider key](#withheld-provider-keys-additive-0440-1666)). `--rerank none\|heuristic\|jev`: `jev` added in 0.39.0, additively; unset, the configured `reranker.provider` (judgment requires `reranker.enabled: true`; otherwise local `heuristic`, or `none` when selected). `--rerank-dry-run` (0.39.0) prints the reranker's outbound request to stderr and sends nothing, even while disabled or keyless. Date filters `--updated-since`, `--updated-before`, `--deadline-from`, `--deadline-to` (`YYYY-MM-DD`, inclusive; a deadline filter drops undated docs), `--sort score\|updated\|deadline` (default `score`; `updated` newest first, `deadline` earliest first with undated docs last) and `--upcoming` (= `--deadline-from --sort deadline`) added in 0.38.0, additively. Stored dates are compared as their UTC day (sorts keep full timestamp precision). A stored value counts only as an ISO `YYYY-MM-DD`, optionally followed by `T` or a space, `HH:MM`, seconds, a fraction and a `Z` or `±HH:MM` offset. Anything else, `2026-02-30` and `now` included, counts as missing: it matches no bound and sorts last. With a query, a date sort picks the results by date from a candidate pool: the full-text lane's best `max(limit × 20, 500)` documents, plus the documents behind the vector lane's nearest chunks (at most that many documents, from at most 500 chunks). An invalid date or sort is a usage error (exit `1`) | +| `brain search "q" --json` | `{ "results": SearchResult[], "warnings": string[] }` — `warnings` reports degraded modes (no vectors, model mismatch, missing key, a reranker that did not run, a [withheld provider key](#withheld-provider-keys-additive-0440-1666)). `--rerank none\|heuristic\|jev`: `jev` added in 0.39.0, additively; unset, the configured `reranker.provider` (judgment requires `reranker.enabled: true`; otherwise local `heuristic`, or `none` when selected). `--rerank-dry-run` (0.39.0) prints the reranker's outbound request to stderr and sends nothing, even while disabled or keyless. Date filters `--updated-since`, `--updated-before`, `--deadline-from`, `--deadline-to` (`YYYY-MM-DD`, inclusive; a deadline filter drops undated docs), `--sort score\|updated\|deadline` (default `score`; `updated` newest first, `deadline` earliest first with undated docs last) and `--upcoming` (= `--deadline-from --sort deadline`) added in 0.38.0, additively. Stored dates are compared as their UTC day (sorts keep full timestamp precision). A stored value counts only as an ISO `YYYY-MM-DD`, optionally followed by `T` or a space, `HH:MM`, seconds, a fraction and a `Z` or `±HH:MM` offset. Anything else, `2026-02-30` and `now` included, counts as missing: it matches no bound and sorts last. With a query, a date sort picks the results by date from a candidate pool: the full-text lane's best `max(limit × 20, 500)` documents, plus the documents behind the vector lane's nearest chunks (at most that many documents, from at most 500 chunks). An invalid date or sort is a usage error (exit `1`). `--limit` is a whole number of `1` or more, default `20`, with no upper bound; the whole argument must be an integer literal. `--mode` is `fts`, `vector` or `hybrid`. Anything else (`--limit abc`, `0`, `-5`, `1.5`, `10abc`, an empty value, `--mode bogus`, or either flag, or a filter flag, without a value) is a usage error (exit `1`, a message on stderr, nothing on stdout) in human and JSON modes, and no query runs. **Breaking in 0.45.0 (#1352):** `--limit` used to be read with `parseInt`, so `10abc` searched with 10 and `1.5` with 1, `abc` came back as an empty result with an `FTS search failed: datatype mismatch` warning, and `0` or a negative was passed on to the query; an unknown `--mode` ran neither lane and returned nothing, without a warning | | `brain audit --json` | `{ "issues": AuditIssue[], "errors", "warnings", "infos", "mustFix", "informational" }` — markdown documents only (assets excluded). The three severity counts are the number of issues at each severity. `mustFix` is `errors + warnings` and `informational` is `infos` (both additive in 0.40.0): severity stays the one classification, and the two totals only name its halves. Every count is of issues, not of markers. **Breaking in 0.40.0:** `todo` and `verify` issues are grouped, one per document and category (see [`AuditIssue`](#auditissue)), and `verify` is `info` instead of `warning`, so a brain with markers reports fewer issues and fewer warnings than before for the same content. **Additive in 0.41.0:** `brain audit --fix --json` returns `AuditFixResult[]`, one result per finding in finding order: `{ path, issue, suggestion, canAutoFix, fix?, repair? }`. `path` is the finding path, `issue` its message, and `suggestion` its own advice (or "Manual review needed."); an unavailable `index-stale` instead names the failed repair premise, or says no registry content change is required. `canAutoFix` is true only for an actually available deterministic registry repair: safe contained path, valid opted-in registry with a content change, configured child types and no validation errors under the index directory. Available results also carry `repair: { capability: "registry", path: }`; all other categories and failed premises are manual with no `repair`. `repair` describes availability, grants no permission, and applies nothing. Optional `fix` means exact replacement text; this command never emits it. No completion provider is called, even if configured | -| `brain context "q" --max-tokens N` | assembled markdown context (text) | +| `brain context "q" --max-tokens N` | assembled markdown context (text). `--max-tokens` is a whole number of `1` or more, default `4000`; anything else (`abc`, `0`, `1.5`, or no value) is a usage error (exit `1`) and no query runs. **Breaking in 0.45.0 (#1352):** it used to be read with `parseInt`, so `10abc` meant 10 and `abc` reached the assembler as `NaN` | | `brain read [--section ] [--max-tokens N]` | the document text; the flags behave as `brain_read`'s `section` and `max_tokens`, and an unknown section exits `1` (flags additive in 0.38.0) | -| `brain briefing` | briefing text (mechanical: deadlines, reviews due, silent edits — no LLM) | +| `brain briefing` | briefing text (mechanical: deadlines, reviews due, silent edits — no LLM). `--limit` (recently active documents) is a whole number of `1` or more, default `15`; anything else (`abc`, `0`, `1.5`, or no value) is a usage error (exit `1`). **Breaking in 0.45.0 (#1352):** a malformed `--limit` used to fall back to 15 silently, and `10abc` meant 10 | | `brain index [--force] [--embeddings] --json` | `{ "total", "added", "updated", "deleted", "unchanged", "chunks", "embeddings", "assets", "graphMs", "graphNodes" }`, all numbers, each counting this run only. See [`brain index` counters](#brain-index-counters). Incremental by default, `--force` = full rebuild, `--incremental` accepted as no-op | | `brain index --forget-cache --json` | `{ "path", "forgotten" }` — `forgotten` is the number of sidecar lines removed for that document or asset (for an asset, every line for its bytes, whatever the title). Runs no index pass; the next `--embeddings` run regenerates what was forgotten. A path not in the index is a usage error (additive in 0.38.0) | | `brain index --compact --json` | `{ "compacted", "before": { "live", "allocated" }, "after": { "live", "allocated" } }` — rebuilds `vec_chunks` from its live rows and runs `VACUUM`, reclaiming the slots deleted vectors leave behind; `before`/`after` have the shape of `brain stats` `size.db.vectorSlots`. `compacted` is `false` only when there is no vector table. Makes no provider call and runs no index pass (additive in 0.38.0) | diff --git a/docs/investigations/note-disposition-investigation.md b/docs/investigations/note-disposition-investigation.md index 3d428b7585..5d503c81c9 100644 --- a/docs/investigations/note-disposition-investigation.md +++ b/docs/investigations/note-disposition-investigation.md @@ -38,7 +38,7 @@ proposals, show review requirements and delegate deterministic mutation to CLI code rather than describing a proposal as a completed move. `brain add` performs ingestion, with the smart branch handing off to an agent -(`addCommand`, `packages/core/src/cli/commands/add.ts:15-65`). +(`addCommand`, `packages/core/src/cli/commands/add.ts:15-68`). `brain archive` is a separate operation: it sets archived status, demotes primary/unset relevance, preserves other bytes, and moves only active projects to the archive directory (`archiveDocument`, diff --git a/packages/core/src/cli/commands/add.ts b/packages/core/src/cli/commands/add.ts index 5656cb2e13..9b5738d8a2 100644 --- a/packages/core/src/cli/commands/add.ts +++ b/packages/core/src/cli/commands/add.ts @@ -1,7 +1,7 @@ -import type { DocumentType } from "../../lib/types.js"; import { ingest } from "../../lib/ingestion.js"; import { openDatabase } from "../../lib/db.js"; import type { CoreCommand } from "../types.js"; +import { stringFlag } from "../flags.js"; import { emit, parseArgs, UsageError } from "../io.js"; import { runAgent } from "../agent.js"; @@ -32,18 +32,21 @@ export const addCommand: CoreCommand = { return; } + // Read before the database is opened: a flag without a value writes nothing. + const type = stringFlag(flags, "type"); + const title = stringFlag(flags, "title"); + const tagList = stringFlag(flags, "tags"); + const tags = tagList ? tagList.split(",").map((t) => t.trim()) : undefined; + const db = openDatabase(cli.brain.dbPath); try { - const tags = flags.tags - ? (flags.tags as string).split(",").map((t) => t.trim()) - : undefined; // ingest() reindexes internally (incremental, no embeddings) via its // injected reindex → indexAll hook. const result = await ingest( { content, - type: flags.type as DocumentType | undefined, - title: flags.title as string | undefined, + type, + title, tags, }, db, diff --git a/packages/core/src/cli/commands/briefing.ts b/packages/core/src/cli/commands/briefing.ts index d0269d6cf9..ed41f83f40 100644 --- a/packages/core/src/cli/commands/briefing.ts +++ b/packages/core/src/cli/commands/briefing.ts @@ -21,6 +21,7 @@ import { filterSearch } from "../../lib/search-engine.js"; import { resolveStatsThresholds } from "../../lib/stats.js"; import { readStatsTrends } from "../../lib/stats-trends.js"; import type { CoreCommand } from "../types.js"; +import { positiveIntegerFlag } from "../flags.js"; import { parseArgs, UsageError } from "../io.js"; function addDays(dateStr: string, days: number): string { @@ -326,7 +327,7 @@ export const briefingCommand: CoreCommand = { --limit-reviews Overdue reviews to list before "… and N more" (default: 5)`, async run(args, cli) { const { flags } = parseArgs(args); - const limit = parseInt(flags.limit as string, 10) || 15; + const limit = positiveIntegerFlag(flags, "limit") ?? 15; let reviewLimit: number | undefined; if (flags["limit-reviews"] !== undefined) { reviewLimit = typeof flags["limit-reviews"] === "string" ? Number(flags["limit-reviews"]) : NaN; diff --git a/packages/core/src/cli/commands/context.ts b/packages/core/src/cli/commands/context.ts index a2bf09ce01..482299a14e 100644 --- a/packages/core/src/cli/commands/context.ts +++ b/packages/core/src/cli/commands/context.ts @@ -2,6 +2,7 @@ import { rerankSetup } from "../../lib/registry.js"; import { assembleContext } from "../../lib/context-assembler.js"; import { loadVecSupport } from "../../lib/db.js"; import type { CoreCommand } from "../types.js"; +import { positiveIntegerFlag } from "../flags.js"; import { openReadonlyDb, parseArgs, UsageError } from "../io.js"; const HELP = `brain context — assemble a token-limited context block @@ -20,12 +21,12 @@ export const contextCommand: CoreCommand = { throw new UsageError("Usage: brain context [--max-tokens N]"); } + // Read before the database is opened: a malformed budget runs no query. + const maxTokens = positiveIntegerFlag(flags, "max-tokens"); + const db = openReadonlyDb(cli.brain); try { await loadVecSupport(db); - const maxTokens = flags["max-tokens"] - ? parseInt(flags["max-tokens"] as string, 10) - : undefined; const context = await assembleContext(db, cli.brain, { query, maxTokens, diff --git a/packages/core/src/cli/commands/list.ts b/packages/core/src/cli/commands/list.ts index 963d31ae3f..a0b4cb9386 100644 --- a/packages/core/src/cli/commands/list.ts +++ b/packages/core/src/cli/commands/list.ts @@ -2,6 +2,7 @@ import type { SearchOptions } from "../../lib/types.js"; import { filterSearch } from "../../lib/search-engine.js"; import { DEFAULT_LIST_LIMIT, listLimitSchema, MAX_LIST_LIMIT } from "../../lib/ops/read.js"; import type { CoreCommand } from "../types.js"; +import { stringFlag } from "../flags.js"; import { emit, type Flags, openReadonlyDb, parseArgs, UsageError } from "../io.js"; const HELP = `brain list — list/browse documents @@ -34,18 +35,20 @@ export const listCommand: CoreCommand = { helpBlock: HELP, async run(args, cli) { const { flags } = parseArgs(args); - // Validated before the database is opened: a bad limit runs no query. + // Validated before the database is opened: a bad limit or a filter flag + // without a value runs no query. const limit = parseListLimit(flags.limit); + const status = stringFlag(flags, "status"); + const opts: SearchOptions = { + type: stringFlag(flags, "type"), + tag: stringFlag(flags, "tag"), + status, + relevance: stringFlag(flags, "relevance"), + includeArchived: status === "archived" || flags["include-archived"] === true, + limit, + }; const db = openReadonlyDb(cli.brain); try { - const opts: SearchOptions = { - type: flags.type as string | undefined, - tag: flags.tag as string | undefined, - status: flags.status as string | undefined, - relevance: flags.relevance as string | undefined, - includeArchived: flags.status === "archived" || flags["include-archived"] === true, - limit, - }; const results = filterSearch(db, opts); diff --git a/packages/core/src/cli/commands/read.ts b/packages/core/src/cli/commands/read.ts index d5a2d6aadc..31b0ddac58 100644 --- a/packages/core/src/cli/commands/read.ts +++ b/packages/core/src/cli/commands/read.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "fs"; import { readDocumentPart, SectionNotFoundError } from "../../lib/document-parts.js"; import { safeResolve } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; +import { stringFlag } from "../flags.js"; import { parseArgs, UsageError } from "../io.js"; const HELP = `brain read — print a document (frontmatter included) @@ -47,7 +48,7 @@ export const readCommand: CoreCommand = { try { console.log( readDocumentPart(readFileSync(fullPath, "utf-8"), { - section: flags.section as string | undefined, + section: stringFlag(flags, "section"), maxTokens, sectionHint: '--section ""', }) diff --git a/packages/core/src/cli/commands/search.ts b/packages/core/src/cli/commands/search.ts index 5b0732a19e..3484231e1f 100644 --- a/packages/core/src/cli/commands/search.ts +++ b/packages/core/src/cli/commands/search.ts @@ -3,8 +3,11 @@ import { hybridSearch, isIsoDate } from "../../lib/search-engine.js"; import { loadVecSupport } from "../../lib/db.js"; import { rerankSetup } from "../../lib/registry.js"; import type { CoreCommand } from "../types.js"; +import { enumFlag, positiveIntegerFlag, stringFlag } from "../flags.js"; import { emit, openReadonlyDb, parseArgs, today, UsageError } from "../io.js"; +const SEARCH_MODES = ["fts", "vector", "hybrid"] as const satisfies ReadonlyArray; + const DATE_FLAGS = ["updated-since", "updated-before", "deadline-from", "deadline-to"] as const; const HELP = `brain search — hybrid FTS5 + vector search @@ -48,9 +51,15 @@ export const searchCommand: CoreCommand = { throw new UsageError(`--${flag} needs a date written YYYY-MM-DD, got ${JSON.stringify(value)}`); } } - if (flags.sort !== undefined && !(SEARCH_SORTS as readonly unknown[]).includes(flags.sort)) { - throw new UsageError(`--sort must be one of ${SEARCH_SORTS.join(", ")}, got ${JSON.stringify(flags.sort)}`); - } + // Every flag is read here, before the database is opened: a malformed + // value is a usage error that runs no query (#1352). + const sort = enumFlag(flags, "sort", SEARCH_SORTS); + const mode = enumFlag(flags, "mode", SEARCH_MODES) ?? "hybrid"; + const limit = positiveIntegerFlag(flags, "limit") ?? 20; + const type = stringFlag(flags, "type"); + const tag = stringFlag(flags, "tag"); + const relevance = stringFlag(flags, "relevance"); + const status = stringFlag(flags, "status"); let setup; try { @@ -62,22 +71,23 @@ export const searchCommand: CoreCommand = { } const opts: SearchOptions = { query, - mode: (flags.mode as SearchOptions["mode"]) || "hybrid", + mode, rerank: setup.rerank, - type: flags.type as string | undefined, - tag: flags.tag as string | undefined, - relevance: flags.relevance as string | undefined, - status: flags.status as string | undefined, - includeArchived: flags.status === "archived" || flags["include-archived"] === true, + type, + tag, + relevance, + status, + includeArchived: status === "archived" || flags["include-archived"] === true, assetsOnly: flags["assets-only"] === true, chunks: flags.chunks === true, - limit: flags.limit ? parseInt(flags.limit as string, 10) : 20, - updatedSince: flags["updated-since"] as string | undefined, - updatedBefore: flags["updated-before"] as string | undefined, + limit, + // The date flags are checked above; these reads only narrow the type. + updatedSince: stringFlag(flags, "updated-since"), + updatedBefore: stringFlag(flags, "updated-before"), // --upcoming is sugar; an explicit --deadline-from or --sort wins. - deadlineFrom: (flags["deadline-from"] as string | undefined) ?? (flags.upcoming ? today() : undefined), - deadlineTo: flags["deadline-to"] as string | undefined, - sort: (flags.sort as SearchOptions["sort"]) ?? (flags.upcoming ? "deadline" : undefined), + deadlineFrom: stringFlag(flags, "deadline-from") ?? (flags.upcoming ? today() : undefined), + deadlineTo: stringFlag(flags, "deadline-to"), + sort: sort ?? (flags.upcoming ? "deadline" : undefined), }; const dated = opts.updatedSince || opts.updatedBefore || opts.deadlineFrom || opts.deadlineTo; diff --git a/packages/core/src/cli/flags.ts b/packages/core/src/cli/flags.ts new file mode 100644 index 0000000000..c99dbc9b4e --- /dev/null +++ b/packages/core/src/cli/flags.ts @@ -0,0 +1,47 @@ +/** + * Typed reads of parsed CLI flags (#1352). `parseArgs` stores a flag's value + * as a string, or `true` when the flag has no value (it is last, or the next + * argument is another `--flag`); a repeated flag keeps its last value. These + * accessors turn a value of the wrong kind into a {@link UsageError} instead + * of letting `true`, `NaN` or an unknown enum member flow into a query. + * + * Each returns `undefined` when the flag is absent, so a command keeps its own + * default. Call them before opening the database: a malformed flag then runs + * no query. + */ + +import { type Flags, UsageError } from "./io.js"; + +/** The flag's string value. A flag given without a value is a usage error. */ +export function stringFlag(flags: Flags, name: string): string | undefined { + const raw = flags[name]; + if (raw === undefined) return undefined; + if (typeof raw !== "string") throw new UsageError(`--${name} needs a value`); + return raw; +} + +/** + * The flag as a whole number of 1 or more. The whole argument must be an + * integer literal, as for `brain list --limit`: `10abc` and `1.5` are refused + * rather than read as 10 and 1, and `0` or a negative is refused rather than + * passed on. There is no upper bound. + */ +export function positiveIntegerFlag(flags: Flags, name: string): number | undefined { + const raw = flags[name]; + if (raw === undefined) return undefined; + const value = typeof raw === "string" && /^-?\d+$/.test(raw) ? Number(raw) : NaN; + if (!(value >= 1)) { + throw new UsageError(`--${name} must be a whole number of 1 or more, got ${JSON.stringify(raw)}`); + } + return value; +} + +/** The flag's value when it is one of `values`; anything else is a usage error. */ +export function enumFlag(flags: Flags, name: string, values: readonly T[]): T | undefined { + const raw = flags[name]; + if (raw === undefined) return undefined; + if (typeof raw !== "string" || !(values as readonly string[]).includes(raw)) { + throw new UsageError(`--${name} must be one of ${values.join(", ")}, got ${JSON.stringify(raw)}`); + } + return raw as T; +} diff --git a/packages/core/tests/cli-contract.test.ts b/packages/core/tests/cli-contract.test.ts index 2d5c629cc9..d5d7219644 100644 --- a/packages/core/tests/cli-contract.test.ts +++ b/packages/core/tests/cli-contract.test.ts @@ -106,6 +106,93 @@ describe("search", () => { }); }); +// #1352: flag values go through one typed accessor (cli/flags.ts). A malformed +// one is a usage error (exit 1, message on stderr, nothing on stdout) in both +// output modes, and is refused before any query runs. +describe("malformed flag values", () => { + const whole = (flag: string, got: string) => `--${flag} must be a whole number of 1 or more, got ${got}`; + const invalid: Array<[string, string[], string]> = [ + ["search --limit abc", ["search", "raft", "--limit", "abc"], whole("limit", '"abc"')], + ["search --limit 0", ["search", "raft", "--limit", "0"], whole("limit", '"0"')], + ["search --limit -5", ["search", "raft", "--limit", "-5"], whole("limit", '"-5"')], + ["search --limit 1.5", ["search", "raft", "--limit", "1.5"], whole("limit", '"1.5"')], + ["search --limit 10abc", ["search", "raft", "--limit", "10abc"], whole("limit", '"10abc"')], + ["search --mode bogus", ["search", "raft", "--mode", "bogus"], '--mode must be one of fts, vector, hybrid, got "bogus"'], + ["a bare search --type", ["search", "raft", "--type"], "--type needs a value"], + ["search --tag before another flag", ["search", "raft", "--tag", "--mode", "fts"], "--tag needs a value"], + ["list --tag before another flag", ["list", "--tag", "--status", "active"], "--tag needs a value"], + ["context --max-tokens abc", ["context", "raft", "--max-tokens", "abc"], whole("max-tokens", '"abc"')], + ["briefing --limit abc", ["briefing", "--limit", "abc"], whole("limit", '"abc"')], + // These two were usage errors before #1352 and keep their messages. + ["search --sort bogus", ["search", "raft", "--sort", "bogus"], '--sort must be one of score, updated, deadline, got "bogus"'], + [ + "a malformed search --updated-since", + ["search", "raft", "--updated-since", "yesterday"], + '--updated-since needs a date written YYYY-MM-DD, got "yesterday"', + ], + ]; + for (const mode of ["--json", "--human"]) { + for (const [what, args, message] of invalid) { + test(`${what} is a usage error in ${mode} mode, with no output`, async () => { + const { stdout, stderr, code } = await runCli(root, [...args, mode]); + expect({ code, stdout, stderr: stderr.trim() }).toEqual({ code: 1, stdout: "", stderr: message }); + }); + } + } + + // Without an index, a query fails with "Database not found". A malformed + // flag reports itself instead, so it is refused before any query is tried. + test("a malformed flag is refused before the database is opened", async () => { + const unindexed = makeTempBrain(); + try { + const valid = await runCli(unindexed, ["search", "raft", "--limit", "5", "--json"]); + expect({ code: valid.code, stderr: valid.stderr.trim() }).toEqual({ + code: 1, + stderr: "Database not found. Run `brain index` first.", + }); + for (const [what, args, message] of invalid) { + if (args[0] === "list") continue; + const bad = await runCli(unindexed, [...args, "--json"]); + expect({ what, code: bad.code, stdout: bad.stdout, stderr: bad.stderr.trim() }).toEqual({ + what, + code: 1, + stdout: "", + stderr: message, + }); + } + const add = await runCli(unindexed, ["add", "Penelope weaves by day", "--tags", "--json"]); + expect({ code: add.code, stdout: add.stdout, stderr: add.stderr.trim() }).toEqual({ + code: 1, + stdout: "", + stderr: "--tags needs a value", + }); + expect(existsSync(join(unindexed, "brain.db"))).toBe(false); + } finally { + cleanup(unindexed); + } + }); + + const paths = async (args: string[]) => { + const { stdout, stderr, code } = await runCli(root, ["search", "raft", "--mode", "fts", ...args, "--json"]); + expect({ code, stderr }).toEqual({ code: 0, stderr: "" }); + return (JSON.parse(stdout) as { results: Array<{ path: string }> }).results.map((r) => r.path); + }; + + test("a repeated --limit keeps its last value", async () => { + const seven = await paths(["--limit", "7"]); + expect(seven).toHaveLength(7); + expect(await paths(["--limit", "5", "--limit", "7"])).toEqual(seven); + }); + + test("valid values keep their results: --limit 50 and --mode fts", async () => { + const all = await paths(["--limit", "50"]); + // The corpus has fewer than 20 raft matches, so 50 and the default agree. + expect(all.length).toBeGreaterThan(7); + expect(all.length).toBeLessThan(20); + expect(await paths([])).toEqual(all); + }); +}); + describe("read", () => { test("prints the whole file with no flag", async () => { const { stdout, code } = await runCli(root, ["read", "me/identity.md"]);