savecontext-cli 0.1.31

SaveContext CLI - Persistent memory for AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# SaveContext CLI (`sc`)

The Rust-native command-line interface for SaveContext. This CLI is the primary implementation, with the MCP server delegating operations to it via a bridge pattern.

## Installation

### From Source (Development)

```bash
cd cli
cargo build --release
# Binary at target/release/sc
```

### Add to PATH

```bash
# Option 1: Symlink to a directory in PATH
ln -sf "$(pwd)/target/release/sc" /usr/local/bin/sc

# Option 2: Add to shell profile
export PATH="$PATH:/path/to/savecontext/cli/target/release"
```

## Architecture

```
AI Coding Tools (Claude Code, Cursor, Cline, etc.)
    ┌───────────────────────────────────────────┐
    │  MCP Server (TypeScript)                  │
    │  @savecontext/mcp                         │
    │               │                           │
    │               ▼                           │
    │  ┌─────────────────────────────────────┐  │
    │  │  CLI Bridge                         │  │
    │  │  server/src/cli/bridge.ts           │  │
    │  │  Delegates to Rust CLI              │  │
    │  └─────────────────────────────────────┘  │
    └───────────────────┬───────────────────────┘
    ┌───────────────────────────────────────────┐
    │  Rust CLI (`sc`)                          │
    │  50+ commands: sessions, issues, time,    │
    │  context, memory, plans, checkpoints      │
    │  Background embedding generation          │
    └───────────────────┬───────────────────────┘
    ┌───────────────────────────────────────────┐
    │  SQLite Database                          │
    │  ~/.savecontext/data/savecontext.db       │
    └───────────────────────────────────────────┘
```

The MCP server acts as a thin transport layer that receives tool calls from AI coding assistants and delegates them to the Rust CLI. This architecture provides:

- **Single source of truth**: All business logic lives in Rust
- **Direct CLI access**: Power users can use `sc` directly from terminal
- **Background processing**: Embedding generation happens asynchronously after save
- **Performance**: Native Rust execution for database operations

## Quick Reference

### Global Flags

```bash
--db <path>       # Custom database path (default: ~/.savecontext/data/savecontext.db)
--actor <name>    # Actor name for audit trail
--session <id>    # Active session ID
--json            # Output as JSON
--format <fmt>    # Output format: json, csv, table (default: table)
--silent          # Minimal output (IDs only for create/mutate)
--dry-run         # Preview mutations without writing
-v, -vv, -vvv    # Increase verbosity (info, debug, trace)
-q, --quiet       # Quiet mode
--no-color        # Disable colored output
```

### Commands

#### Session Management
```bash
sc session start "Feature work" -d "Description"   # Start a session
sc session list                                     # List sessions
sc session list --status all                        # Include completed
sc session pause                                    # Pause current session
sc session resume <id>                              # Resume a session
sc session end                                      # End current session
sc session rename "New name"                        # Rename session
sc session delete <id>                              # Delete session
sc session add-path /path/to/project                # Add path to session
sc session remove-path /path/to/project             # Remove path from session
```

#### Context Items
```bash
sc save auth-decision "Using JWT tokens" -c decision -p high
sc get --query "authentication"                     # Semantic search
sc get --query "auth" --search-all-sessions         # Search all sessions
sc get --query "auth" --search-mode fast            # Fast mode (Model2Vec only)
sc get --key auth-decision                          # Get by key
sc get --category decision                          # Filter by category
sc update auth-decision --value "Updated reasoning"
sc delete auth-decision
sc tag add auth-decision -t important,security
sc tag remove auth-decision -t security
```

#### Issues
```bash
sc issue create "Fix login bug" -t bug -p 3         # Create issue
sc issue list                                       # List open issues
sc issue list --status all                          # Include closed
sc issue show SC-a1b2                               # Show details
sc issue update SC-a1b2 --status in_progress        # Update
sc issue complete SC-a1b2                           # Mark done
sc issue claim SC-a1b2                              # Assign to self
sc issue release SC-a1b2                            # Unassign
sc issue clone SC-a1b2                              # Clone issue
sc issue duplicate SC-a1b2 --of SC-c3d4             # Mark as duplicate
sc issue ready                                      # List ready issues
sc issue next-block -c 3                            # Claim next batch
sc issue complete SC-a1b2 --reason "Done"           # Complete with reason
sc issue count                                      # Count by status
sc issue count --group-by type                      # Count by type
sc issue stale                                      # Stale issues (7+ days)
sc issue stale --days 3                             # Stale issues (3+ days)
sc issue blocked                                    # Blocked issues + blockers
sc issue dep tree SC-a1b2                           # Dependency tree
sc issue dep tree                                   # Trees for all epics
sc issue label add SC-a1b2 -l frontend,urgent
sc issue dep add SC-a1b2 --depends-on SC-c3d4
```

#### Checkpoints
```bash
sc checkpoint create "pre-refactor" --include-git
sc checkpoint list
sc checkpoint show <id>
sc checkpoint restore <id>
sc checkpoint delete <id>
sc checkpoint add-items <id> -k key1,key2
sc checkpoint remove-items <id> -k key1
```

#### Memory (Persistent Across Sessions)
```bash
sc memory save test-cmd "npm test" -c command
sc memory get test-cmd
sc memory list
sc memory list -c config
sc memory delete test-cmd
```

#### Projects
```bash
sc project create /path/to/project -n "My Project"
sc project list
sc project show <id>
sc project update <id> --name "New Name"
sc project delete <id>
```

#### Plans
```bash
sc plan create "Q1 Features" -c "## Goals\n- Feature 1\n- Feature 2"
sc plan list
sc plan show <id>
sc plan update <id> --status completed
sc plan capture                                # Import plan from AI agent's plan file
sc plan capture --agent claude --max-age 60    # Specific agent (claude, gemini, opencode, cursor, factory), 60min max age
sc plan capture --agent factory-ai             # Factory AI plans
```

#### Skills & Hooks
```bash
sc skills install                    # Auto-detect tools (claude-code, codex, gemini, factory-ai), install everything
sc skills install --tool claude-code # Target specific tool
sc skills install --tool factory-ai  # Factory AI tools
sc skills install --path /custom/path # Override skills directory
sc skills status                     # Check installed tools
sc skills update                     # Re-download latest
```

#### Time Tracking
```bash
sc time log 4 "Implementation work" --period "INV-001"   # Log hours
sc time log 1.5 "Bug fix" --issue SC-a1b2                # Link to issue
sc time log 2 "Research" --date 2026-02-10               # Backdate
sc time list                                              # All entries + total
sc time list --period "INV-001" --status logged           # Filter
sc time summary --period "INV-001"                        # Grouped subtotals
sc time total                                             # Running total
sc time total --status logged                             # Unbilled total
sc time update TE-a1b2 --hours 5                          # Update entry
sc time invoice --period "INV-001"                        # Batch logged→invoiced
sc time delete TE-a1b2                                    # Delete entry
```

#### Embeddings
```bash
sc embeddings status                                # Check config
sc embeddings configure --provider ollama --enable
sc embeddings configure --provider huggingface --token <token>
sc embeddings backfill                              # Generate for existing items
sc embeddings test "Hello world"                    # Test connectivity
```

#### Sync (JSONL Export/Import)
```bash
sc sync status
sc sync export
sc sync import
```

#### Prime (Context Injection)
```bash
sc prime --compact                                  # Fixed-limit category buckets
sc prime --smart --compact                          # Ranked by relevance within token budget
sc prime --smart --compact --budget 2000            # Custom token budget
sc prime --smart --compact --query "auth"           # Semantic boost for topic
sc prime --smart --compact --decay-days 7           # Aggressive recency bias
sc prime --smart --json                             # JSON with scoring stats
sc prime --transcript                               # Include Claude Code transcripts
```

Smart prime flags:

| Flag | Default | Description |
|------|---------|-------------|
| `--smart` | off | Enable relevance-ranked selection |
| `--budget <n>` | 4000 | Token budget for context items |
| `--query <text>` | none | Semantic boost for a topic |
| `--decay-days <n>` | 14 | Temporal decay half-life in days |

Scoring: `temporal_decay * priority_weight * category_weight * semantic_boost`

- **Temporal decay**: exponential (`today=1.0, 7d=0.71, 14d=0.5, 28d=0.25`)
- **Priority**: `high=3.0, normal=1.0, low=0.5`
- **Category**: `decision=2.0, reminder=1.5, progress=1.0, note=0.5`
- **Semantic boost**: `0.5x-2.5x` based on cosine similarity to `--query`
- **MMR diversity**: penalizes near-duplicate items by embedding similarity

#### Other
```bash
sc init --global                                    # Initialize database
sc status                                           # Show session status
sc compaction                                       # Prepare for compaction
sc completions bash > ~/.bash_completion.d/sc      # Shell completions
sc version
```

## Embedding Configuration

The CLI supports background embedding generation for semantic search. Configure via environment variables or the `embeddings configure` command:

### Ollama (Recommended for Local)

```bash
# Uses nomic-embed-text by default
sc embeddings configure --provider ollama --enable

# Or with custom model
sc embeddings configure --provider ollama --model mxbai-embed-large --enable
```

### HuggingFace (Cloud API)

```bash
sc embeddings configure --provider huggingface --token hf_xxx --enable
```

### Environment Variables

```bash
export SC_EMBEDDINGS_PROVIDER=ollama    # or huggingface
export SC_EMBEDDINGS_MODEL=nomic-embed-text
export SC_EMBEDDINGS_ENDPOINT=http://localhost:11434
export HUGGINGFACE_TOKEN=hf_xxx         # For HuggingFace
```

## Output Modes

### JSON Output

All commands support `--json` for machine-readable output:

```bash
sc session list --json | jq '.sessions[0].name'
sc issue list --json | jq '.issues | length'
sc get --query "auth" --json | jq '.items[].key'
```

### Auto-JSON (Non-TTY)

When stdout is piped, output is automatically JSON — no flag needed:

```bash
sc issue list | jq '.issues[].title'    # Auto-JSON (piped)
sc issue list                            # Human-readable (TTY)
```

### Format Flag

```bash
sc issue list --format json    # JSON output
sc issue list --format csv     # CSV output (id,title,status,priority,type,assigned_to)
sc issue list --format table   # Human-readable table (default)
```

### Silent Mode

For scripting — create/mutate commands print only the ID:

```bash
ID=$(sc issue create "Bug fix" --silent)
sc save my-key "value" --silent           # Prints: my-key
sc session start "work" --silent          # Prints: sess_xxxx
```

### Dry Run

Preview mutations without writing to the database:

```bash
sc issue create "Test" --dry-run          # Would create issue: Test [task, priority=2]
sc issue create "Test" --dry-run --json   # {"dry_run":true,"action":"create_issue",...}
```

## Error Handling

### Structured Errors

Errors include machine-readable codes, hints, and recovery suggestions:

```json
{
  "error": {
    "code": "ISSUE_NOT_FOUND",
    "message": "Issue not found: SC-xxxx",
    "retryable": false,
    "exit_code": 3,
    "hint": "Did you mean: SC-a1b2, SC-a1b3?"
  }
}
```

Structured JSON errors are automatic when piped (non-TTY) or with `--json`.

### Exit Code Categories

| Exit | Category | Action |
|------|----------|--------|
| 0 | Success | Continue |
| 1 | Internal | Report bug |
| 2 | Database | Check init/permissions |
| 3 | Not Found | Verify ID, check hint for suggestions |
| 4 | Validation | Fix input, retry |
| 5 | Dependency | Resolve dependency first |
| 6-9 | Other | See `cli/AGENTS.md` for full reference |

For the complete error code table and retryable flags, see [`cli/AGENTS.md`](AGENTS.md).

### Intent Detection

The CLI auto-normalizes common synonyms, so you don't need to memorize canonical values:

- **Status**: `done``closed`, `wip``in_progress`, `todo``open`
- **Type**: `defect``bug`, `story``feature`, `cleanup``chore`
- **Priority**: `critical` → 4, `high` → 3, `low` → 1, `P0`-`P4` accepted

### Similar ID Suggestions

When an ID isn't found, the error includes suggestions for similar existing IDs.

### Session Hints

When no active session is bound to your terminal, the error lists recent resumable sessions with their IDs, names, and statuses.

## Shell Completions

```bash
# Bash
sc completions bash > ~/.bash_completion.d/sc

# Zsh
sc completions zsh > ~/.zfunc/_sc

# Fish
sc completions fish > ~/.config/fish/completions/sc.fish

# PowerShell
sc completions powershell > $PROFILE.d/sc.ps1
```

## Development

```bash
# Build debug
cargo build

# Build release
cargo build --release

# Run tests
cargo test

# Run with verbose logging (or use -v/-vv flags)
RUST_LOG=debug cargo run -- session list
# Note: Debug output shows search pipeline stages, session/project resolution, and embedding operations

# Check lints
cargo clippy
```

## License

AGPL-3.0 - See [LICENSE](../LICENSE) for details.