Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/1352-cli-flag-values.md
Original file line number Diff line number Diff line change
@@ -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:** `--<flag> needs a value`.

`brain search --sort` and the date filters keep their existing usage errors.
4 changes: 2 additions & 2 deletions docs/decisions/interpreted-briefing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 9 additions & 3 deletions docs/integration-contract/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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 <today, UTC> --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 <today, UTC> --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: <index 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 <path> [--section <heading>] [--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 <path> --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) |
Expand Down
2 changes: 1 addition & 1 deletion docs/investigations/note-disposition-investigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
15 changes: 9 additions & 6 deletions packages/core/src/cli/commands/add.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/cli/commands/briefing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -326,7 +327,7 @@ export const briefingCommand: CoreCommand = {
--limit-reviews <n> 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;
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/cli/commands/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <query> — assemble a token-limited context block
Expand All @@ -20,12 +21,12 @@ export const contextCommand: CoreCommand = {
throw new UsageError("Usage: brain context <query> [--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,
Expand Down
21 changes: 12 additions & 9 deletions packages/core/src/cli/commands/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/cli/commands/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path> — print a document (frontmatter included)
Expand Down Expand Up @@ -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 "<heading>"',
})
Expand Down
Loading
Loading