git:20260330.4e5d8f6 to git:20260402.460f56e

147 added, 110 removed. Audit A to A.

What this update changes in the checks

No check changed: every fixed check gives the same answer before and after this update.

A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.

---
name: adding-a-command
- description: Creates a new CLI command following the Commander.js pattern in src/commands/. Handles command registration in src/cli.ts, telemetry tracking via tracked() wrapper, and option parsing. Use when user says 'add command', 'new CLI command', 'create subcommand', or adds files to src/commands/. Do NOT use for modifying existing commands or fixing bugs in existing commands.
+ description: Creates a new CLI command following the Commander.js pattern in src/commands/. Handles command registration in src/cli.ts, telemetry tracking via tracked() wrapper, and option parsing. Use when user says add command, new CLI command, create subcommand, or adds files to src/commands/. Do NOT use for modifying existing commands or fixing bugs in existing commands.
+ paths:
+ - src/commands/**/*.ts
+ - src/cli.ts
---
# Adding a Command
## Critical
- - **All commands must be wrapped in `tracked()`** from `src/telemetry/index.ts`. This is non-negotiable — every command logs its execution for metrics.
- - **Commands are exported as default functions** from `src/commands/{name}.ts`. The function signature must match: `export default function commandName(program: Command): void`.
- - **Register the command in `src/cli.ts`** in the main CLI builder. Import the command function and call it, passing the program instance.
- - **Test the command exists** before merging: `npm run build && npx caliber {command-name} --help` should return the help text without errors.
+ - **Export pattern**: Command must export a named async function: `export async function myCommand(options?: OptionType)`. Never use default exports.
+ - **Registration in cli.ts**: Every command must be imported and registered with `.command()` chain in `src/cli.ts`, wrapped with `tracked()` for telemetry.
+ - **Error signaling**: Use `throw new Error('__exit__')` to exit gracefully without printing the error message. Use chalk for user-facing messages.
+ - **Options typing**: Commands receiving options must define a TypeScript interface for those options. Pass options as a destructured object parameter.
## Instructions
- 1. **Create the command file** at `src/commands/{command-name}.ts`.
- - Use kebab-case for file names (`src/commands/my-command.ts`).
- - Export a default async function that receives `program: Command` parameter.
- - The function builds and registers the command via `program.command('name')`.
- - Verify: File exists and exports a default function with the correct signature.
-
- 2. **Define the command using Commander.js**.
- - Chain `.description()`, `.option()`, `.action()` on the command object.
- - Use `command.command('name').description('...')` for the command definition.
- - Store the returned command object and call `.action()` on it.
- - Verify: The action callback receives correct parameters (e.g., options object, command instance).
+ 1. **Create the command file** at `src/commands/{commandName}.ts` with named async export.
+ - Signature: `export async function {commandName}Command(options?: { optionName?: optionType }) { ... }`
+ - Import only what you need (avoid kitchen-sink imports).
+ - Return void (handle all output via console.log or chalk).
+ - Verify the file follows the naming convention: camelCase function + "Command" suffix.
- 3. **Wrap the action handler in `tracked()`**.
- - Import `tracked` from `src/telemetry/index.ts`.
- - Call `tracked('command-name', async (context) => { ... })` inside `.action()`.
- - The callback receives `context` parameter (telemetry context); use it to report custom metrics if needed.
- - Return the Promise from the tracked wrapper.
- - Verify: The command runs and completes without telemetry errors (check console output).
+ 2. **Handle errors consistently**: Wrap error-prone operations in try/catch. Distinguish between user errors and system errors:
+ - User error (bad input): `console.error(chalk.red('message')); throw new Error('__exit__');`
+ - System error (missing dependency): `throw new Error('Detailed error message');` — this will print and exit with code 1.
+ - Parse-like errors: Use ora spinner with `.fail()` before throwing.
+ - This step prevents double error printing in bin.ts.
- 4. **Parse and validate options**.
- - Extract options from the options object passed to the action callback.
- - Use destructuring: `const { optionName, flag } = options`.
- - For required options, validate they exist and throw an error if missing.
- - Verify: Running the command without required options produces a clear error message.
+ 3. **Import and register in src/cli.ts** in the correct location:
+ - Add import at the top: `import { {commandName}Command } from './commands/{commandName}.js';`
+ - Register the command in the appropriate section (main commands, or nested under a group like `sources`).
+ - For main commands: `.command('{kebab-name}').description('...').option(...).action(tracked('{kebab-name}', {commandName}Command))`
+ - For subcommands (like `sources add`): `sources.command('add').description(...).action(tracked('sources:add', sourcesAddCommand))`
+ - Key: Wrap handler with `tracked('{command-name}', handler)` for automatic telemetry.
+ - Verify the command name in tracked() uses kebab-case for main commands and colon-separated for subcommands.
- 5. **Register the command in `src/cli.ts`**.
- - Import the command function at the top: `import myCommand from './commands/my-command.js'`.
- - Call it in the buildCli function: `myCommand(program)`.
- - Commands are registered in the order they appear in the function.
- - Verify: `npx caliber --help` lists your command in the available commands.
+ 4. **Define options (if needed)**:
+ - Add `.option()` chains before `.action()`: `.option('--flag', 'Description')` or `.option('--opt <value>', 'Description')`
+ - For parsed options (like comma-separated agents), add a parse function: `.option('--opt <value>', 'Description', parseFunction)`
+ - Pass options to handler: `.action(tracked('name', (opts) => command(opts)))`
+ - Define TypeScript interface for the options object.
+ - Verify option names use camelCase (Commander converts kebab-case flags to camelCase).
- 6. **Write a test** in `src/commands/__tests__/{command-name}.test.ts`.
- - Use Vitest patterns from existing tests (e.g., `src/commands/__tests__/status.test.ts`).
- - Mock external dependencies (filesystem, LLM calls, telemetry).
- - Test: command registration, option parsing, success path, error handling.
- - Verify: `npm run test -- src/commands/__tests__/{command-name}.test.ts` passes.
+ 5. **Verify before proceeding**:
+ - Function exports correctly and is imported in cli.ts.
+ - Command is registered with tracked() wrapper.
+ - Output uses chalk for colors, not plain console.log.
+ - Error paths throw `new Error('__exit__')` for user errors.
## Examples
- ### Example: User requests "add a greet command that takes a --name option"
+ ### Example 1: Simple command (status)
- **Action 1: Create `src/commands/greet.ts`**
+ User says: "Add a command to show config status"
+
+ **Actions taken**:
+ 1. Create src/commands/status.ts with statusCommand() export
+ 2. Import and register in src/cli.ts with tracked() wrapper
+
+ **Result**: `caliber status` displays config status; `caliber status --json` outputs JSON.
+
+ Code example:
```typescript
- import { Command } from 'commander';
- import { tracked } from '../telemetry/index.js';
+ import chalk from 'chalk';
+ import { loadConfig } from '../llm/config.js';
- export default function greetCommand(program: Command): void {
- const cmd = program
- .command('greet')
- .description('Greet a user by name')
- .option('--name <string>', 'Name to greet', 'World')
- .action(async (options) => {
- return tracked('greet', async (context) => {
- const { name } = options;
- console.log(`Hello, ${name}!`);
- });
- });
+ export async function statusCommand(options?: { json?: boolean }) {
+ const config = loadConfig();
+
+ if (options?.json) {
+ console.log(JSON.stringify({ configured: !!config }, null, 2));
+ return;
+ }
+
+ console.log(chalk.bold('Status'));
+ console.log(` LLM: ${chalk.green(config?.provider || 'Not configured')}`);
}
```
- **Action 2: Register in `src/cli.ts`**
- - Add import: `import greetCommand from './commands/greet.js'`
- - Call in buildCli: `greetCommand(program)`
-
- **Action 3: Test in `src/commands/__tests__/greet.test.ts`**
+ Registration in src/cli.ts:
```typescript
- import { describe, it, expect, vi } from 'vitest';
- import { Command } from 'commander';
- import greetCommand from '../greet.js';
+ import { statusCommand } from './commands/status.js';
+ program
+ .command('status')
+ .description('Show config status')
+ .option('--json', 'Output as JSON')
+ .action(tracked('status', statusCommand));
+ ```
- describe('greet', () => {
- it('registers the command', () => {
- const program = new Command();
- greetCommand(program);
- const cmd = program.commands.find((c) => c.name() === 'greet');
- expect(cmd).toBeDefined();
- });
+ ---
- it('greets with default name', async () => {
- const program = new Command();
- greetCommand(program);
- const consoleSpy = vi.spyOn(console, 'log');
- await program.parseAsync(['node', 'caliber', 'greet']);
- expect(consoleSpy).toHaveBeenCalledWith('Hello, World!');
- });
+ ### Example 2: Subcommand with arguments
- it('greets with custom name', async () => {
- const program = new Command();
- greetCommand(program);
- const consoleSpy = vi.spyOn(console, 'log');
- await program.parseAsync(['node', 'caliber', 'greet', '--name', 'Alice']);
- expect(consoleSpy).toHaveBeenCalledWith('Hello, Alice!');
- });
- });
+ User says: "Add a sources add subcommand"
+
+ **Actions taken**:
+ 1. Create src/commands/sources.ts with sourcesAddCommand() export
+ 2. Register under sources group with tracked('sources:add', ...)
+
+ **Result**: `caliber sources add ../lib` adds a source.
+
+ Code example:
+ ```typescript
+ export async function sourcesAddCommand(sourcePath: string) {
+ if (!fs.existsSync(sourcePath)) {
+ console.log(chalk.red(`Path not found: ${sourcePath}`));
+ throw new Error('__exit__');
+ }
+ const existing = loadSourcesConfig(process.cwd());
+ existing.push({ type: 'repo', path: sourcePath });
+ writeSourcesConfig(process.cwd(), existing);
+ console.log(chalk.green(`Added ${sourcePath}`));
+ }
```
- **Action 4: Verify**
- ```bash
- npm run build
- npx caliber greet --help # Shows help text
- npx caliber greet # Output: Hello, World!
- npx caliber greet --name Alice # Output: Hello, Alice!
- npm run test -- src/commands/__tests__/greet.test.ts # All tests pass
+ Registration:
+ ```typescript
+ const sources = program.command('sources');
+ sources
+ .command('add')
+ .argument('<path>', 'Path to add')
+ .action(tracked('sources:add', sourcesAddCommand));
```
+ ---
+
+ ### Example 3: Command with option parsing
+
+ User says: "Add init with --agent flag supporting comma-separated values"
+
+ **Actions taken**:
+ 1. Create parseAgentOption() parser in src/cli.ts
+ 2. Create src/commands/init.ts with initCommand(options)
+ 3. Register with custom parser
+
+ **Result**: `caliber init --agent claude,cursor` passes parsed array to handler.
+
+ Parser code:
+ ```typescript
+ function parseAgentOption(value: string) {
+ const agents = value.split(',').map(s => s.trim().toLowerCase());
+ if (agents.length === 0) {
+ console.error('Invalid agent');
+ process.exit(1);
+ }
+ return agents;
+ }
+
+ program.command('init')
+ .option('--agent <type>', 'Agents (comma-separated)', parseAgentOption)
+ .action(tracked('init', initCommand));
+ ```
+
## Common Issues
- **Error: "Command 'mycommand' is not a valid command"**
- - Verify the command function was called in `src/cli.ts` inside `buildCli()`: look for `myCommand(program)`.
- - Verify the import path is correct: `import myCommand from './commands/my-command.js'` (note `.js` extension for ESM).
- - Run `npm run build` to regenerate dist/ and try again.
+ **Issue**: "SyntaxError: The requested module does not provide an export named 'myCommand'"
+ - **Cause**: Function not exported or exported as default instead of named.
+ - **Fix**: Use `export async function myCommand(...)` (not `export default`).
- **Error: "tracked is not a function"**
- - Verify import: `import { tracked } from '../telemetry/index.js'` at the top of the command file.
- - Verify the tracked call is async: `.action(async (options) => { return tracked(...); })`.
- - Verify the tracked callback returns or awaits a value; the action must return the Promise.
+ **Issue**: Command appears in help but crashes when run
+ - **Cause**: Handler not wrapped with `tracked()` or function import mismatch.
+ - **Fix**: Verify import name matches function export. Wrap with `tracked('command-name', handler)`.
- **Error: "Option parsing failed" or options are undefined**
- - Verify options are defined via `.option()` before `.action()`.
- - Verify the action callback destructures options correctly: `const { optionName } = options`.
- - If testing, ensure the command is parsed with `await program.parseAsync([...])` including the command name and options.
+ **Issue**: "Error: __exit__" appears in output for user errors
+ - **Cause**: Throwing generic error instead of using error exit pattern.
+ - **Fix**: Use `console.error(chalk.red('message')); throw new Error('__exit__');` for user-facing errors.
- **Command appears in --help but fails when run**
- - Verify the tracked wrapper is present and the action callback is async.
- - Check for console errors: the action may throw before telemetry completes.
- - Verify external dependencies (file reads, LLM calls) are mocked in tests.
- - Run in dev mode: `npm run dev` and test locally before committing.
+ **Issue**: --dry-run flag not recognized
+ - **Cause**: Option not declared with `.option()` or wrong camelCase in interface.
+ - **Fix**: Add `.option('--dry-run', 'Description')` and ensure options interface has `dryRun?: boolean`.
- **Test fails with "Command is not registered"**
- - Verify the test calls `greetCommand(program)` to register it.
- - Verify the command name in the test matches the `.command('name')` call.
- - Use `program.commands.find((c) => c.name() === 'name')` to debug if the command exists.
+ **Issue**: Subcommand crashes but parent command works
+ - **Cause**: Using `program.command()` instead of `groupVar.command()` for subcommands.
+ - **Fix**: Register on group: `const sources = program.command('sources'); sources.command('add')...`
+
+ **Issue**: Telemetry not appearing
+ - **Cause**: Handler not wrapped with `tracked()` or wrong command name.
+ - **Fix**: Ensure `.action(tracked('{kebab-case}', handler))` wraps handler. Use colon for subcommands like 'sources:add'.
+
+ **Issue**: "Cannot find module" with relative imports
+ - **Cause**: Using `.ts` extension in imports.
+ - **Fix**: Always use `.js` extension: `import { x } from '../lib/file.js'` (required for ESM).