add-command
Skill331 starsChanged 7 days agoMITView on GitHub
Guide for adding new CLI commands or subcommands to todoist-cli. Use when implementing new SDK endpoints, adding subcommands to existing command groups, or extending CLI functionality.
7 other projects use a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- coralogix/cx-clitheir own version, first seen Nov 8, 2026
- rajdeepratan/SlashForgetheir own version, first seen Oct 9, 2026
- redis/go-redistheir own version, first seen Oct 8, 2026
- gitkraken/vscode-gitlenstheir own version, first seen Oct 8, 2026
- microsoft/vscode-cmake-toolstheir own version, first seen Apr 20, 2026
- Doist/twist-cliedited, first seen Apr 3, 2026
Other versions7 projects use a version of this.
Word for word · 0
None found.
Edited · 1
- Doist/twist-cli★ 353% same
Wrote their own version · 6
- redis/go-redis★ 22ksame name
- gitkraken/vscode-gitlens★ 10ksame name
- microsoft/vscode-cmake-tools★ 1.7ksame name
- ldayton/Dippy★ 243same name
- coralogix/cx-cli★ 241same name
- rajdeepratan/SlashForge★ 5same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository11 other files it gives its agents.
- AGENTS.mdAGENTS.md
- docs/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- build-featureSkill
- fix-bugSkill
- learnSkill
- refactorSkill
- review-changesSkill
- verifySkill
- write-testsSkill
- todoist-cliSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
15 rules. 0 are common, 3 are distinctive, and 12 are very specific to this project.
0
Common
Most of the 6 edited versions we read keep these.
3
Distinctive
This author's own choices. Worth a look.
12
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Follow this checklist when adding new commands.
- Very specific: line 12
Add a mock for each new SDK method in createMockApi().
- Very specific: line 19
Add an entry to API_SPINNER_MESSAGES for each new SDK method.
- Distinctive: line 36
Every new command should satisfy these properties.
- Very specific: line 67
helpers.ts: Only needed when multiple subcommands share a utility/constant.
- Very specific: line 73
Create a new file src/commands/<entity>/<action>.ts with the handler function
- Very specific: line 74
Import and wire it in src/commands/<entity>/index.ts
- Very specific: line 92
Always use CliError from src/lib/errors.ts instead of bare throw new Error(...).
- Very specific: line 100
When adding a new error code, add it to the ErrorCode type in src/lib/errors.ts under the appropriate category.
- Very specific: line 136
Every .description() string should be a clear one-line purpose — agents read this to decide which subcommand to call
- Very specific: line 145
Color-coded status/severity: If color conveys meaning (e.g., green=good, red=bad), add a text prefix or label in accessible mode so the …
- Very specific: line 173
If adding a new shared formatter to output.ts, use Record<ExactType, ...> rather than Record<string, ...> so the compiler catches missing …
- Very specific: line 177
Follow the existing pattern: mock getApi, use program.parseAsync().
- Very specific: line 188
Update SKILL_CONTENT with examples for the new command.
- Distinctive: line 197
After all code changes are complete:
“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Adding a New CLI Command or Subcommand
Follow this checklist when adding new commands. Each step references the exact file to modify.
1. Mock API (src/test-support/mock-api.ts)
Add a mock for each new SDK method in createMockApi(). Place it in the correct entity group.
- List/read methods:
.mockResolvedValue({ results: [], nextCursor: null })or appropriate empty default - Mutation methods:
vi.fn()(no default return needed)
2. Spinner Messages (src/lib/api/core.ts)
Add an entry to API_SPINNER_MESSAGES for each new SDK method.
Color convention:
blue— read/fetch operationsgreen— create/join operationsyellow— update/delete/archive mutations
3. Read-Only Permissions (src/lib/permissions.ts)
If the new command uses a read-only SDK method (e.g., getXxx, listXxx), add it to the KNOWN_SAFE_API_METHODS set. This set uses a default-deny approach: any method not listed is treated as mutating and will be blocked when the CLI is authenticated with a read-only OAuth token (td auth login --read-only).
- Read-only methods (fetch/list/view): add to
KNOWN_SAFE_API_METHODS - Mutating methods (add/update/delete/archive/move): do NOT add — they are blocked by default, which is the correct behavior
4. Agent-Friendly Design Checklist
Every new command should satisfy these properties. They ensure the CLI works well for both humans and AI agents. See 7 Principles for Agent-Friendly CLIs for background.
- Non-interactive by default — All input via flags, positional args, or
--stdin. Never usereadline,prompt(), or block waiting for TTY input. When a required argument is missing, callfailWithUsage(cmd)fromsrc/lib/missing-argument.ts— don't prompt. - Structured, parseable output — Data commands must support
--json(and--ndjsonfor lists). Results go to stdout, diagnostics to stderr. Spinners auto-suppress when!process.stdout.isTTY(seesrc/lib/spinner.ts). Exit code 0 on success, non-zero on failure. - Fail fast with actionable errors — Use
CliErrorwith a specific error code, a message naming the exact problem, and hints that include correct invocation syntax, valid values, or example commands. Validate all inputs before making API calls. - Safe retries and explicit mutation boundaries — Mutating commands support
--dry-run. Destructive + irreversible commands require--yes. Create commands return the entity ID (useisQuiet()for bare ID output for scripting, e.g.id=$(td task add "Buy milk" -q)). - Progressive help discovery — Parent command groups include
.addHelpText('after', ...)with 2–3 concrete examples. Every.description()is a clear one-line purpose statement. When a required positional arg is missing, callfailWithUsage(cmd): it prints help to stderr and exits 1, or throwsMISSING_ARGUMENTunder--json/--ndjson. Never a barecmd.help(), which prints to stdout and exits 0. - Composable and predictable structure — Use consistent subcommand verbs (
list/view/create/update/delete/browse). Use consistent flag names across entities (--project <ref>,--json,--dry-run,--yes,--limit,--cursor,--all). Support--stdinfor text content where applicable (read it withreadStdin()from@doist/cli-core, and test it withmockStdin()from@doist/cli-core/testing). - Bounded, high-signal responses — List commands use
paginate()fromsrc/lib/pagination.tswith--limit <n>,--cursor, and--allflags. When results are truncated,formatNextCursorFooter()tells the user how to fetch more. JSON output usesformatJson()orformatPaginatedJson()to return essential fields by default, passing the--fullflag for complete output.
5. Command Implementation (src/commands/<entity>/)
Commands with multiple subcommands use a folder-based structure:
src/commands/<entity>/
index.ts # registerXxxCommand — creates parent cmd, wires subcommands
list.ts # async function listXxx(...) — one file per subcommand
view.ts # async function viewXxx(...)
create.ts # async function createXxx(...)
helpers.ts # shared constants/utilities used by multiple subcommands (optional)- index.ts: Imports all subcommand handlers, creates the Commander tree, exports
registerXxxCommand - Subcommand files: Export one async action handler + any option interfaces. Use
../../lib/for lib imports. No Commander imports (only index.ts uses Commander). - helpers.ts: Only needed when multiple subcommands share a utility/constant.
Single-subcommand commands (e.g., add.ts, today.ts) remain as flat files.
Adding a subcommand to an existing command
- Create a new file
src/commands/<entity>/<action>.tswith the handler function - Import and wire it in
src/commands/<entity>/index.ts
Flag conventions
| Command type | Flags |
| Read-only | --json (and --ndjson for lists) |
| Mutating (returns entity) | --json (use formatJson), --dry-run |
| Mutating (no return) | --dry-run |
| Destructive + irreversible | --yes, --dry-run |
| Reversible (archive/unarchive) | --dry-run (no --yes) |
| List (paginated) | --limit <n>, --cursor, --all, --json, --ndjson |
| List (non-paginated) | --json, --ndjson |
The --quiet / -q flag suppresses success messages on mutations. Create commands in quiet mode print only the bare entity ID for scripting (e.g., id=$(td task add "Buy milk" -q)).
Error handling
Always use CliError from src/lib/errors.ts instead of bare throw new Error(...). This ensures structured error output in JSON mode and consistent formatting in text mode.
import { CliError } from '../../lib/errors.js'
throw new CliError('ERROR_CODE', 'User-facing message', ['Optional hint'])When adding a new error code, add it to the ErrorCode type in src/lib/errors.ts under the appropriate category. The type provides intellisense for known codes while accepting any string for dynamic codes.
To make errors actionable for agents:
- The
messagemust name the specific problem (not generic "invalid input") - The
hintsarray should include at least one of: correct invocation syntax, valid values, or a working example command - Validate all flag constraints and input early — before any API calls. If flags conflict, throw
CliError('CONFLICTING_OPTIONS', ...)immediately
ID resolution
resolveXxxRef(api, ref)— when the user knows the entity by name (projects, tasks, labels). Add new wrappers inrefs.ts—resolveRefis private.lenientIdRef(ref, 'entity')— when there is no list endpoint for lookup, or the user can't access the entity yet (e.g., comments, reminders, joining an unjoined project)- Context-scoped resolvers (
resolveSectionId,resolveParentTaskId,resolveWorkspaceRef) — when resolving a name within a parent context (e.g., a section name within a specific project). Each has custom logic inrefs.ts.
Subcommand registration pattern
const myCmd = parent
.command('my-action [ref]')
.description('Do something')
.option('--json', 'Output as JSON')
.option('--dry-run', 'Preview what would happen without executing')
.action((ref, options) => {
if (!ref) {
failWithUsage(myCmd)
return
}
return myAction(ref, options)
})The variable assignment (const myCmd = ...) is needed so the .action() callback can call failWithUsage(myCmd) when the argument is missing.
Help text quality:
- Parent command groups (the
registerXxxCommandfunction) should include.addHelpText('after', ...)with 2–3 concrete invocation examples - Every
.description()string should be a clear one-line purpose — agents read this to decide which subcommand to call - The
if (!ref) { failWithUsage(cmd); return }pattern ensures the command never blocks when a required argument is missing
6. Accessibility (src/lib/output.ts)
The CLI supports accessible mode via isAccessible() from src/lib/global-args.ts (checks TD_ACCESSIBLE=1 or --accessible flag). When adding output that uses color or visual elements, consider whether information is conveyed only by color or decoration.
When to add accessible alternatives
- Color-coded status/severity: If color conveys meaning (e.g., green=good, red=bad), add a text prefix or label in accessible mode so the meaning is available without color. Example:
formatHealthStatusadds[+],[!],[!!]prefixes. - ASCII art / visual bars: Omit entirely in accessible mode — screen readers read each character individually (e.g.,
====----becomes "equals equals equals equals dash dash dash dash"). Show only the numeric value instead. - Decorative symbols: Stars, checkmarks, or icons used alongside color should have text equivalents. Example: favorites get
★only in accessible mode since the yellow color already signals it visually.
When you don't need to do anything
- Text that is already descriptive: Status names like
ON_TRACK,COMPLETEDare self-explanatory — color just reinforces them. Still consider adding indicator prefixes for severity. - Plain numbers and dates: Already accessible.
- Dim/styled labels:
chalk.dim()for secondary info is fine — screen readers ignore styling.
Pattern
import { isAccessible } from '../lib/global-args.js'
// For color-coded values: add text prefix in accessible mode
const a11y = isAccessible()
const prefix = a11y ? '[!] ' : ''
console.log(chalk.yellow(`${prefix}AT_RISK`))
// For visual bars: skip entirely in accessible mode
if (isAccessible()) {
console.log(`${percent}%`)
} else {
console.log(`[${'='.repeat(filled)}${'-'.repeat(empty)}] ${percent}%`)
}If adding a new shared formatter to output.ts, use Record<ExactType, ...> rather than Record<string, ...> so the compiler catches missing variants.
7. Tests (next to the command, e.g. src/commands/<entity>/<entity>.test.ts)
Follow the existing pattern: mock getApi, use program.parseAsync(). The write-tests skill has the helpers and the quality bar.
Always test:
- Happy path (correct output, correct API call)
INVALID_REFrejection forlenientIdRefcommands (plain text like"Planning"should fail)--dry-runfor mutating commands (API method should NOT be called, preview text shown)--jsonoutput where applicable
8. Skill Content (src/lib/skills/content.ts)
Update SKILL_CONTENT with examples for the new command. Update relevant sections:
- Command examples in the entity's
### Sectionblock - Quick Reference if adding a top-level command
- Mutating
--jsonlist if the command returns an entity --dry-runlist if applicable
9. Sync Skill File
After all code changes are complete:
npm run sync:skillThis builds the project and regenerates skills/todoist-cli/SKILL.md from the compiled skill content. The regenerated file must be committed. CI will fail (npm run check:skill-sync) if it is out of sync.
10. Verify
npm run verifyThen follow the verify skill to prove the command does what was asked.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

