securegit 0.7.3

Zero-trust git replacement with 12 built-in security scanners, universal undo, durable backups, and a 42-tool MCP server
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
<!--
  Copyright (c) 2026 ArmyKnife Labs

  This Specification is licensed under the Specification Commons License,
  Version 0.1 (SCL-0.1). See /LICENSE-SCL for the full license text.

  Evaluation Scenario Tier: Open
-->

# SecureGit

A zero-trust git replacement with 12 built-in security scanners, universal undo, durable backups, worktree management, and a 42-tool MCP server. Written in Rust. Single binary. Drop-in replacement for git.

## Why SecureGit?

You would need git + gitleaks + trufflehog + gh CLI + custom scripts + a backup solution to approximate what securegit does in one binary:

| Feature                        | git + gitleaks + gh    | securegit   |
|--------------------------------|------------------------|-------------|
| Secret detection on clone      | No (manual setup)      | Automatic   |
| Supply chain scanning          | No                     | 12 plugins  |
| Pre-commit security gate       | Hook scripts           | Built-in    |
| Universal undo                 | No                     | Yes         |
| Continuous snapshots           | No                     | Yes         |
| Stacked diffs                  | No                     | Yes         |
| AI commit messages             | No                     | Yes         |
| Durable backups (rsync/S3)     | No                     | Built-in    |
| MCP server for AI tools        | No                     | 42 tools    |
| Security-gated PRs             | No                     | Built-in    |
| LLM-optimized compact output   | No (needs RTK/proxy)   | Built-in    |
| Token usage analytics          | No                     | Built-in    |
| Drop-in git replacement        | N/A                    | Yes         |
| Single binary, no runtime      | N/A                    | Rust        |

## Installation

```bash
cargo install securegit
```

This installs two binaries:
- `securegit` -- the main CLI (drop-in git replacement)
- `securegit-mcp` -- the MCP server for AI tool integration

## Using as a Git Replacement

SecureGit is a drop-in replacement for git. You can alias it so that all your existing tools, scripts, and muscle memory work seamlessly.

### Shell Alias (recommended)

Add to your `~/.bashrc`, `~/.zshrc`, or `~/.config/fish/config.fish`:

```bash
# Bash / Zsh
alias git=securegit
```

```fish
# Fish
alias git securegit
```

After reloading your shell, every `git` command routes through securegit — including calls from editors, IDE terminals, and scripts:

```bash
git status          # → securegit status
git commit -m "hi"  # → securegit commit -m "hi"
git undo            # → securegit undo (innovation features work too)
```

### Symlink (system-wide)

If you want securegit to be the `git` binary for all users and processes:

```bash
# Create a symlink (adjust paths to match your install)
sudo ln -sf $(which securegit) /usr/local/bin/git
```

To revert, remove the symlink and your system git takes over again.

### Per-project via direnv

Use [direnv](https://direnv.net/) to enable securegit only in specific directories:

```bash
# In your project's .envrc
PATH_add $(dirname $(which securegit))
alias git=securegit
```

### IDE / Editor Integration

Most editors call whatever `git` is on your `$PATH`. With the alias or symlink above, these work automatically:

- **VS Code** — uses the `git` binary from your shell; no config needed
- **JetBrains (IntelliJ, CLion, etc.)** — Settings > Version Control > Git > Path to Git executable: set to the securegit binary path
- **Neovim / Vim** — fugitive, gitsigns, and other plugins call `git` from `$PATH`
- **Emacs** — magit calls `git` from `exec-path`; the alias covers it

### Verifying the Alias

```bash
git version
# → securegit 0.7.3
```

If you see the securegit version, everything is routed correctly.

## Quick Start

```bash
# Use securegit exactly like git
securegit init
securegit add -A
securegit commit -m "Initial commit"
securegit push origin main

# But with superpowers
securegit undo                              # Undo any operation
securegit snapshot                          # Save working tree state
securegit commit --ai                       # AI-generated commit message
securegit conflicts                         # Rich conflict details
securegit stack new feature                 # Start a stacked diff workflow
securegit scan .                            # Security scan anytime
securegit status --compact                  # Token-optimized output for LLMs
securegit gain                              # View token savings analytics
```

## Features

### Complete Git Operations

SecureGit implements every common git command natively in Rust via libgit2:

| Category | Commands |
|----------|----------|
| **Basics** | `init`, `clone`, `status`, `log`, `diff`, `show`, `blame` |
| **Staging** | `add`, `rm`, `mv`, `restore`, `reset`, `clean` |
| **Branching** | `branch`, `checkout`, `switch`, `merge`, `rebase`, `cherry-pick`, `revert` |
| **Remote** | `push`, `pull`, `fetch`, `remote` |
| **Worktrees** | `worktree` (list, add, remove, lock, unlock, prune) |
| **Other** | `tag`, `stash`, `config` |

**Git-compatible flags** — these common flags work the same as in git:

| Command | Supported Flags |
|---------|----------------|
| `checkout` | `-f` / `--force` |
| `merge` | `--no-ff`, `--squash`, `--ff-only` |
| `tag` | `-a` (annotated), `-l` (list/filter) |
| `rebase` | `--skip`, `--onto <base>` |
| `cherry-pick` | `--skip`, `-n` / `--no-commit` |
| `revert` | `--skip`, `-n` / `--no-commit` |
| `config` | `--global` (for `get`, `set`, `list`) |
| `clone` | `-b` / `--branch` |
| `clean` | `-x` (remove ignored files too) |

### Inbound Security (Code Acquisition)

- **ZIP-with-History model**: Downloads safe snapshots, fetches history separately, sanitizes everything
- **Multiple strategies**: `zip-with-history` (default), `zip-only`, `bare-checkout`
- **Git sanitization**: Removes all hooks, dangerous config keys, LFS auto-fetch
- **Archive validation**: Zip bomb protection, path traversal prevention, size limits
- **Integrity verification**: Ensures ZIP contents match git HEAD

```bash
# Standard acquisition with full history
securegit acquire github:facebook/react -o ./react

# Private repo with token
securegit acquire github:company/private --token $TOKEN

# Specific branch
securegit acquire github:company/repo -b develop

# Maximum security, no history
securegit acquire github:unknown/sketchy-lib --no-history
```

### Outbound Security (Commit/Push Protection)

- **Pre-commit scanning**: Catch secrets before they hit the repo
- **Pre-push scanning**: Final check before code goes to remote
- **Git hook management**: Install/uninstall securegit hooks

```bash
securegit hook install --all
securegit hook status
```

### 12 Built-in Security Scanners

See the [Plugin System](#plugin-system) section for full details on each scanner and how to write your own.

```bash
securegit scan ./my-project
securegit scan ./vendor --fail-on medium
```

---

## Innovation Features

These features go beyond what plain git offers.

### 1. Universal Undo (`securegit undo`)

Every mutating operation is journaled with before/after snapshots. Undo any operation instantly.

```bash
securegit commit -m "oops"
securegit undo                    # Restores HEAD, branches, index, working tree

securegit undo --list             # Show operation history
securegit undo --op <id>          # Undo a specific operation
```

The operation log is stored at `.git/securegit/oplog.jsonl`. All 18 mutating commands (commit, merge, rebase, checkout, reset, branch, tag, stash, etc.) are automatically tracked.

### 2. Continuous Snapshots (`securegit snapshot`)

Save and restore working tree state at any point, independent of commits.

```bash
securegit snapshot                        # Quick snapshot
securegit snapshot create -m "before refactor"
securegit snapshot list
securegit snapshot restore <id>           # Restore without moving HEAD
securegit snapshot prune --older-than 7d  # Clean up old snapshots
```

Snapshots are stored as orphan commits under `refs/snapshots/` — they live inside the git object database and don't pollute your branch history.

### 3. AI Commit Messages (`securegit commit --ai`)

Generate Conventional Commits messages from your staged diff using AI.

```bash
export SECUREGIT_AI_API_KEY=your-api-key
securegit add -A
securegit commit --ai                     # Generates message, asks for confirmation
```

Also triggers automatically when you run `securegit commit` without `-m` (if an API key is configured). The prompt enforces Conventional Commits format (`feat:`, `fix:`, `refactor:`, etc.) with imperative mood and 72-char first lines.

Environment variables:
- `SECUREGIT_AI_API_KEY` — API key for AI commit message generation
- `SECUREGIT_AI_MODEL` — model identifier
- `SECUREGIT_AI_URL` — API endpoint URL

### 4. First-Class Conflict Management (`securegit conflicts`, `securegit resolve`)

When merge, rebase, or cherry-pick hits conflicts, securegit records structured metadata (base/ours/theirs OIDs) in the git object database.

```bash
securegit merge feature-branch
# Conflict detected...

securegit conflicts                       # List all conflicted files
securegit conflicts --verbose             # Show base/ours/theirs OIDs
securegit resolve src/lib.rs --accept ours
securegit resolve src/main.rs --accept theirs
securegit resolve config.toml             # Manual (stage what's in working tree)
```

Conflict records are stored under `refs/conflicts/` and automatically cleaned up on resolution.

### 5. Stacked Diffs (`securegit stack`)

Manage chains of dependent branches for incremental code review.

```bash
securegit stack new my-feature            # Create stack on current branch
securegit stack push -b step-1            # Create and push branch onto stack
# ... make changes, commit ...
securegit stack push -b step-2            # Next branch in the chain
# ... make changes, commit ...

securegit stack status                    # Show all branches with commit counts
securegit stack rebase                    # Cascade rebase from base to tip
securegit stack log                       # Commits grouped by branch
securegit stack pop                       # Remove top branch from stack
```

Stack metadata is stored under `refs/stack-metadata/` in the git ODB.

### 6. Worktree Management (`securegit worktree`)

Manage multiple working trees for parallel development — work on multiple branches simultaneously without stashing.

```bash
securegit worktree                           # List all worktrees
securegit worktree add feature -b my-branch  # Create worktree with branch
securegit worktree add hotfix                # Create with auto-named branch
securegit worktree remove feature            # Remove a worktree
securegit worktree lock feature --reason wip # Lock to prevent pruning
securegit worktree unlock feature            # Unlock a worktree
securegit worktree prune                     # Clean up stale entries
securegit worktree prune --dry-run           # Preview what would be pruned
```

All worktree mutations are tracked by the universal undo system. Use `securegit undo` to reverse any worktree operation.

### 7. Compact Output Mode (`--compact`)

Token-optimized output for LLM contexts. Reduces output by 60-90% compared to standard git output, purpose-built for AI coding assistants.

```bash
# Enable via flag
securegit status --compact
securegit diff --compact
securegit log --compact
securegit show --compact

# Or via environment variable (ideal for hooks/scripts)
export SECUREGIT_COMPACT=1
securegit status    # Automatically uses compact output
```

**Per-command behavior:**

| Command | Standard Output | Compact Output |
|---------|----------------|----------------|
| `status` | Full file list with sections | Branch + counts (e.g., `main\n2 staged, 1 modified`) |
| `diff` | Full unified diff | Max 10 lines/hunk, 100 lines total, per-file summaries |
| `log` | Multi-line commit entries | One-liner per commit, max 10 entries |
| `show` | Full commit + diff | One-line header + stat + compact diff |
| `branch` | Decorated branch list | `* current\n  other` (remotes capped at 10) |
| `stash` | Full stash descriptions | Short descriptions, stripped prefixes |
| Write ops | Verbose success messages | `ok`, `ok <hash>`, `ok pushed` |

**Token savings analytics:**

```bash
securegit gain                  # Summary: total commands, tokens saved, efficiency
securegit gain --history        # Per-command history with savings breakdown
```

Example `gain` output:
```
Token Savings Summary
  Total commands:  42
  Input tokens:    12,450
  Output tokens:   3,210
  Tokens saved:    9,240 (74.3%)
```

### 8. Platform Integration (GitHub/GitLab)

Authenticate with GitHub or GitLab, create security-gated pull requests, auto-file issues from scan findings, create attested releases, and check CI status -- all without leaving the terminal.

```bash
# Authenticate
securegit auth login                         # Browser-based OAuth device flow
securegit auth login --provider gitlab       # GitLab device flow
securegit auth status                        # Show current auth state

# Self-hosted instances
securegit auth login --provider gitlab --host http://gitlab.example.com/api/v4 --token glpat-xxx

# Pull requests with security scan gate
securegit pr create --title "Add feature"    # Scans before creating PR
securegit pr list                            # List open PRs

# Auto-file issues from scan findings
securegit scan ./src --create-issues         # Creates GitHub/GitLab issues

# Releases with security attestation
securegit release create v1.0.0             # Attaches scan attestation JSON
securegit release list

# CI/CD status
securegit ci status                          # Check pipeline status
securegit ci watch                           # Live-updating status
```

### 9. Multi-Server Management

Register multiple GitHub and GitLab instances (including self-hosted) and push to all of them with a single command. Credentials are stored encrypted and never exposed in tool output.

```bash
# Register servers
securegit server add prod-gh --platform github --api-url https://api.github.com
securegit server add corp-gl --platform gitlab --api-url https://gitlab.corp.com/api/v4
securegit server add staging --platform gitlab --api-url http://gitlab-staging:8080/api/v4 --no-push

# List registered servers
securegit server list

# Check connectivity and auth status
securegit server status

# Remove a server
securegit server remove staging
```

**Token resolution priority** (per server):

1. Environment variable: `SECUREGIT_SERVER_<NAME>_TOKEN` (e.g., `SECUREGIT_SERVER_PROD_GH_TOKEN`)
2. Stored credential (encrypted in `~/.config/securegit/credentials.json`, keyed as `server:<name>`)
3. Host-based fallback (matches against `auth login` credentials by API URL hostname)

**Push to multiple servers:**

```bash
# Push to all push-enabled servers
securegit server push

# Push to specific servers only
securegit server push --servers prod-gh,corp-gl

# Force push
securegit server push --force
```

**Use with platform tools:**

Platform tools (`pr list`, `ci status`, `release list`) accept an optional `--server` flag to target a specific registered server instead of auto-detecting from the current remote.

```bash
securegit pr list --server corp-gl
securegit ci status --server prod-gh
```

### 10. Durable Backups (`securegit backup`)

Protect your code against GitHub outages, account lockouts, or local machine failure. Backup to any destination you control using git bundles.

Supported backends:
- **Local** -- USB drives, NAS mounts, any mounted path
- **rsync** -- SSH-accessible servers (`user@host:/path/`)
- **rclone** -- S3, B2, GCS, SFTP, Dropbox, OneDrive, and 70+ other providers (`remote:bucket/`)

```bash
securegit backup add nas user@192.168.1.10:/backups/git/ --auto
securegit backup add s3 aws:my-git-backups/securegit/
securegit backup push                        # Bundle and upload to all destinations
securegit backup status                      # Show last backup times
securegit backup restore user@host:/path/backup.bundle -o ./restored
securegit backup verify ./backup.bundle      # Verify bundle integrity
```

Backups are portable git bundles -- restore with `git clone backup.bundle` on any machine, even without securegit installed.

### 11. Security-Aware MCP Server (`securegit-mcp`)

A Model Context Protocol server that exposes 41 tools for AI assistants to interact with git repositories securely. All responses are automatically sanitized to strip credentials (GitHub/GitLab tokens, Bearer headers, URL-embedded passwords).

```bash
# Add to your MCP client configuration
securegit-mcp    # Runs on stdio (JSON-RPC 2.0)
```

#### Tools (42 total)

**Security (5) — unique to securegit:**

| Tool | Description |
|------|-------------|
| `securegit_scan` | Scan directory for security findings |
| `securegit_scan_staged` | Scan only staged changes |
| `securegit_safe_commit` | Scan + commit atomically (blocks on findings) |
| `securegit_review` | Security analysis of a specific file |
| `securegit_findings` | Query cached scan results by severity/file |

**Git Read (9):**

| Tool | Description |
|------|-------------|
| `securegit_status` | Structured repo status (JSON) |
| `securegit_log` | Commit history with filters |
| `securegit_diff` | Diffs between commits/index/working tree |
| `securegit_blame` | File blame |
| `securegit_show` | Commit/tag details |
| `securegit_branch_list` | List branches |
| `securegit_tag_list` | List tags |
| `securegit_remote_list` | List remotes |
| `securegit_stash_list` | List stashes |

**Git Write (11) — security-gated:**

| Tool | Description |
|------|-------------|
| `securegit_add` | Stage files |
| `securegit_commit` | Commit changes |
| `securegit_push` | Push to a git remote |
| `securegit_checkout` | Switch branches |
| `securegit_branch_create` | Create branch |
| `securegit_branch_delete` | Delete branch |
| `securegit_merge` | Merge branches |
| `securegit_stash_save` | Stash changes |
| `securegit_stash_pop` | Pop stash |
| `securegit_tag_create` | Create tag |
| `securegit_undo` | Undo last operation |

**Worktree (5) — parallel development:**

| Tool | Description |
|------|-------------|
| `securegit_worktree_list` | List all worktrees with branch and lock status |
| `securegit_worktree_add` | Create a new worktree |
| `securegit_worktree_remove` | Remove a worktree |
| `securegit_worktree_lock` | Lock a worktree to prevent pruning |
| `securegit_worktree_unlock` | Unlock a worktree |

**Backup (4):**

| Tool | Description |
|------|-------------|
| `securegit_backup_add` | Add a backup destination (local/rsync/rclone) |
| `securegit_backup_remove` | Remove a backup destination |
| `securegit_backup_list` | List configured backup destinations |
| `securegit_backup_push` | Create bundle and push to destinations |

**Platform (4) — accept optional `server` parameter for multi-server:**

| Tool | Description |
|------|-------------|
| `securegit_auth_status` | Show authentication status (includes registered servers) |
| `securegit_pr_list` | List pull requests / merge requests |
| `securegit_ci_status` | Show CI/CD pipeline status |
| `securegit_release_list` | List releases |

**Server Management (4) — multi-server credential vault:**

| Tool | Description |
|------|-------------|
| `securegit_server_add` | Register a server with encrypted credential storage |
| `securegit_server_remove` | Remove a registered server and its credentials |
| `securegit_server_list` | List registered servers (credentials never exposed) |
| `securegit_server_push` | Push to one or all registered servers |

#### MCP Client Configuration

Example MCP client configuration:
```json
{
  "mcpServers": {
    "securegit": {
      "command": "securegit-mcp",
      "args": []
    }
  }
}
```

---

## Workflow Scripts

SecureGit ships with 20 guided workflow scripts for developers learning professional git practices. Each script is interactive, menu-driven, and works with any language.

```bash
# Run any workflow from your repo
./workflows/14-dev-flow.sh          # Complete PR-first development flow
./workflows/05-commit-craft.sh      # Guided conventional commit builder
./workflows/20-project-setup.sh     # Bootstrap a new project with securegit
```

### Available Workflows

| # | Script | What It Teaches |
|---|--------|-----------------|
| 01 | `stash-manager` | Smart stash management with snapshots and search |
| 02 | `branch-manager` | Branch naming conventions, lifecycle, and protection |
| 03 | `pr-prepare` | Quality checks, security scan, and PR creation pipeline |
| 04 | `worktree-manager` | Parallel development with git worktrees |
| 05 | `commit-craft` | Conventional commits with type/scope/ticket references |
| 06 | `quality-gates` | Pre-commit linting, formatting, testing, and security scan |
| 07 | `history-navigator` | Interactive log search, blame, and commit archaeology |
| 08 | `cherry-pick-hotfix` | Safe cherry-pick with undo and conflict handling |
| 09 | `merge-strategy` | Merge/squash/rebase/ff-only with pre-merge checks |
| 10 | `prune-cleanup` | Delete stale branches, prune remotes, repo hygiene |
| 11 | `reset-recovery` | Safe reset with securegit undo and reflog recovery |
| 12 | `remote-manager` | Multi-remote management with auth status |
| 13 | `repo-architecture` | Set up .gitignore, CODEOWNERS, hooks, and structure |
| 14 | `dev-flow` | **Flagship** — complete PR-first professional workflow |
| 15 | `release-manager` | Version bumping, changelog, tagging, and release creation |
| 16 | `diff-mastery` | Compact diffs, patch creation, change complexity analysis |
| 17 | `code-promotion` | Promote code through dev → staging → production |
| 18 | `quality-check` | Quick quality validation on changed files only |
| 19 | `multi-repo` | Status, fetch, scan, and commands across multiple repos |
| 20 | `project-setup` | Bootstrap a new project with securegit from scratch |

### Configuration

Workflows are customizable without editing scripts. Config is loaded from (later overrides earlier):

1. `workflows/securegit-workflows.conf` (shipped defaults)
2. `~/.config/securegit/workflows.conf` (user global)
3. `.securegit/workflows.conf` (per-project)
4. Environment variables (runtime override)

Key settings: protected branches, commit types/scopes, merge strategy, quality gates, and auto-detected language/tool commands.

### Language Auto-Detection

Scripts automatically detect your project language and select the right test, lint, format, and build commands:

| Language | Test | Lint | Format |
|----------|------|------|--------|
| Rust | `cargo test` | `cargo clippy` | `cargo fmt` |
| Go | `go test ./...` | `golangci-lint run` | `gofmt -l .` |
| Python | `pytest` | `ruff check .` | `ruff format --check .` |
| JavaScript | `npm test` / `vitest` | `eslint` / `biome` | `prettier` / `biome` |
| Java | `./gradlew test` / `mvn test` |||
| Ruby | `bundle exec rspec` | `rubocop` | `rubocop` |
| PHP | `vendor/bin/phpunit` | `phpstan` | `php-cs-fixer` |
| C | `make test` |||

Override any command via config: `SG_TEST_CMD="my-custom-test-runner"`.

---

## All Commands

```
securegit <COMMAND>

Security:
  acquire      Download and scan code from remote source
  clone        Clone a repository (alias for acquire)
  scan         Scan existing local directory
  sanitize     Sanitize an existing git repository
  unzip        Safely extract and scan local archive
  hook         Install/uninstall/manage git hooks
  pre-commit   Scan staged changes (called by hook)
  pre-push     Scan commits being pushed (called by hook)

Git Operations:
  init         Initialize a new repository
  status       Show working tree status
  log          Show commit log
  diff         Show changes between commits, index, and working tree
  add          Add file contents to the index
  commit       Record changes to the repository
  push         Update remote refs along with associated objects
  pull         Fetch and integrate remote changes
  fetch        Download objects and refs from a remote repository
  merge        Join two or more development histories together
  checkout     Switch branches or restore working tree files
  switch       Switch branches (modern checkout)
  branch       List, create, or delete branches
  tag          Create, list, delete tags
  remote       Manage set of tracked repositories
  stash        Stash changes in working directory
  reset        Reset current HEAD to the specified state
  restore      Restore working tree files
  rebase       Reapply commits on top of another base
  cherry-pick  Apply changes from existing commits
  revert       Revert an existing commit
  blame        Show what revision and author last modified each line
  show         Show commit or tag details with diff
  config       Get and set repository or global options
  clean        Remove untracked files from the working tree
  rm           Remove files from the working tree and index
  mv           Move or rename a file

Worktrees:
  worktree     Manage multiple working trees (list, add, remove, lock, unlock, prune)

Innovation:
  undo         Undo the last securegit operation
  snapshot     Create and manage working tree snapshots
  conflicts    List active merge/rebase conflicts
  resolve      Resolve a conflicted file
  stack        Manage stacked branches (stacked diffs)
  gain         Show token savings analytics for compact mode

Platform:
  auth         Authenticate with GitHub or GitLab (including self-hosted)
  pr           Create and manage pull requests (with security scan gates)
  release      Create and manage releases (with security attestation)
  ci           Check CI/CD pipeline status
  server       Register and manage multiple GitHub/GitLab servers
  backup       Durable backups to local, rsync, or rclone destinations

Global Options:
  -v, --verbose  Verbose output
  -q, --quiet    Suppress non-essential output
      --json     Output in JSON format (for scan/status/log)
      --compact  Token-optimized output for LLMs (or set SECUREGIT_COMPACT=1)
```

## Plugin System

SecureGit has a plugin architecture that ships with 12 built-in security scanners and supports custom external plugins written in any language.

### Built-in Plugins

All 12 plugins are loaded automatically on every scan. No configuration required.

| Plugin | What It Detects | Severity Range |
|--------|----------------|----------------|
| **Secrets** | AWS keys, GitHub/Slack tokens, private keys, database passwords, OpenAI keys | High - Critical |
| **Patterns** | `eval()`/`exec()`, shell injection, reverse shells, backdoor indicators | High - Critical |
| **Entropy** | High-entropy strings indicating encrypted/obfuscated payloads | Medium - High |
| **Binary** | Unexpected ELF, PE, Mach-O executables in source trees | Medium - Critical |
| **Encoding** | Trojan Source (CVE-2021-42574): BiDi overrides, Cyrillic/Greek homoglyphs, zero-width characters | High - Critical |
| **Supply Chain** | 36 known typosquatted packages (npm/PyPI/Ruby), malicious lifecycle hooks, dependency confusion | High - Critical |
| **CI/CD** | `pull_request_target` abuse, `curl\|bash` in pipelines, secret exfiltration, Jenkins `@Grab` | High - Critical |
| **Container** | Privileged pods, Docker socket mounts, `cap_add: ALL`, RBAC wildcards, host namespaces | Medium - Critical |
| **IaC** | Open security groups, public S3 buckets, `local-exec` provisioners, Ansible shell pipes | Medium - Critical |
| **Deserialization** | Python `pickle`/`marshal`, `yaml.load()` without SafeLoader, Java `ObjectInputStream`, XXE | High - Critical |
| **Dangerous Files** | `.gitmodules` path traversal (CVE-2018-17456), `.gitconfig` fsmonitor hooks, `.gitattributes` filter drivers | High - Critical |
| **Git Internals** | Unexpected hooks remaining after sanitization, dangerous git config keys | High - Critical |

### Running Scans

```bash
# Scan a directory (uses all plugins)
securegit scan ./my-project

# Scan including .git internals
securegit scan ./my-project --include-git

# Fail on medium severity or above
securegit scan ./vendor --fail-on medium

# Quiet mode (only final result)
securegit scan . --quiet
```

### External Plugins

Write custom scanners in any language (Python, Bash, Go, Node.js, Rust, etc.). SecureGit discovers and loads them automatically from the plugins directory.

#### Plugin Directory

```
~/.config/securegit/plugins/
```

Place executable files in this directory. SecureGit loads every executable file on startup.

#### How It Works

1. SecureGit spawns your plugin as a subprocess for each file scanned
2. Your plugin receives the **file path** as its first CLI argument
3. Your plugin writes **JSON** to stdout
4. SecureGit parses the JSON and merges findings into the scan report

#### Output Format

Your plugin must print a JSON object to stdout:

```json
{
  "plugin_name": "my-custom-scanner",
  "version": "1.0.0",
  "findings": [
    {
      "id": "CUSTOM-001",
      "title": "Hardcoded database URL found",
      "description": "Production database URL detected in source code",
      "severity": "critical",
      "confidence": "high",
      "file_path": "src/config.py",
      "line_start": 42,
      "line_end": 42,
      "evidence": "DB_URL = 'postgres://prod-db.internal:5432/main'",
      "remediation": "Use environment variables for database configuration",
      "references": ["https://owasp.org/Top10/A05_2021/"],
      "cwe_ids": [798]
    }
  ],
  "scanned_files": 1,
  "duration_ms": 15
}
```

#### Field Reference

**Top-level fields:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `plugin_name` | string | yes | Your plugin's identifier |
| `version` | string | no | Plugin version |
| `findings` | array | yes | List of security findings (empty array if none) |
| `scanned_files` | number | no | Files processed (default: 1) |
| `duration_ms` | number | no | Scan time in milliseconds |

**Finding fields:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | yes | Unique finding identifier (e.g., `CUSTOM-001`) |
| `title` | string | yes | Short description of the issue |
| `severity` | string | yes | `critical`, `high`, `medium`, `low`, or `info` |
| `description` | string | no | Detailed explanation |
| `confidence` | string | no | `high`, `medium`, or `low` (default: `medium`) |
| `file_path` | string | no | File where issue was found (falls back to scanned path) |
| `line_start` | number | no | Starting line number |
| `line_end` | number | no | Ending line number |
| `evidence` | string | no | The matching text or code snippet |
| `remediation` | string | no | How to fix the issue |
| `references` | array | no | URLs to relevant documentation or CWEs |
| `cwe_ids` | array | no | CWE identifiers (e.g., `[798, 200]`) |

#### Example: Bash Plugin

```bash
#!/usr/bin/env bash
# ~/.config/securegit/plugins/check-todo-fixme
# Flags TODO and FIXME comments as low-severity findings

FILE="$1"
FINDINGS="[]"

while IFS= read -r line_num; do
    content=$(sed -n "${line_num}p" "$FILE")
    FINDINGS=$(echo "$FINDINGS" | jq --arg ln "$line_num" --arg c "$content" --arg f "$FILE" \
        '. += [{"id":"TODO-001","title":"TODO/FIXME comment found","severity":"info","file_path":$f,"line_start":($ln|tonumber),"evidence":$c}]')
done < <(grep -n 'TODO\|FIXME' "$FILE" | cut -d: -f1)

cat <<EOF
{
  "plugin_name": "todo-scanner",
  "version": "1.0.0",
  "findings": $FINDINGS,
  "scanned_files": 1
}
EOF
```

```bash
chmod +x ~/.config/securegit/plugins/check-todo-fixme
```

#### Example: Python Plugin

```python
#!/usr/bin/env python3
# ~/.config/securegit/plugins/check-sql-injection
"""Detects potential SQL injection patterns."""

import json, re, sys

def scan(filepath):
    findings = []
    try:
        with open(filepath) as f:
            for i, line in enumerate(f, 1):
                if re.search(r'(execute|query)\s*\(.*%s|f".*SELECT.*\{|\.format\(.*SELECT)', line):
                    findings.append({
                        "id": "SQL-001",
                        "title": "Potential SQL injection",
                        "severity": "critical",
                        "confidence": "medium",
                        "file_path": filepath,
                        "line_start": i,
                        "evidence": line.strip(),
                        "remediation": "Use parameterized queries instead of string formatting",
                        "cwe_ids": [89]
                    })
    except (UnicodeDecodeError, PermissionError):
        pass

    print(json.dumps({
        "plugin_name": "sql-injection-scanner",
        "version": "1.0.0",
        "findings": findings,
        "scanned_files": 1
    }))

if __name__ == "__main__":
    scan(sys.argv[1])
```

```bash
chmod +x ~/.config/securegit/plugins/check-sql-injection
```

#### Plugin Requirements

- Must be an **executable file** in `~/.config/securegit/plugins/`
- Must accept a **file path** as the first argument
- Must print **valid JSON** to stdout (the format above)
- Must exit cleanly (non-zero exit with empty stdout is treated as an error)
- Runs once per file scanned, so keep execution fast
- Stderr is captured but not displayed unless the plugin fails

#### Debugging Plugins

Test your plugin manually before installing:

```bash
# Test against a single file
~/.config/securegit/plugins/my-plugin ./src/main.py | jq .

# Verify securegit discovers it
securegit scan . --verbose 2>&1 | grep "my-plugin"
```

---

## Testing

SecureGit ships with 240 tests across five categories:

| Category | Tests | Coverage |
|----------|-------|----------|
| **Auth & Security** | 49 | SecureString masking, credential store encryption, token discovery, backup backends |
| **Ops Integration** | 52 | init, status, commit, branch, tag, checkout, log, diff, stash, config, clean, staging, worktree, merge, restore |
| **Compact Output** | 22 | Truncation boundaries, token estimation, diff formatting, CLI flag/env activation |
| **Core & Tracking** | 7 | Timer accuracy, record/retrieve, summary aggregation, history limits |
| **Multi-Server** | 22 | Server registry, token resolution, response sanitizer, MCP server tools |
| **Existing** | 88 | Scanner plugins, sanitization, archive safety, CLI dispatch |

```bash
cargo test                    # Run all 240 tests
cargo test auth               # Auth & security tests only
cargo test ops_test           # Ops integration tests only
cargo test compact            # Compact output tests only
```

All ops integration tests use real temporary git repositories (via `tempfile` + `git2`) — no mocking of git operations.

---

## Security Guarantees

When using `zip-with-history` (default), securegit guarantees:

1. **No code execution** — Hooks cannot run, filters cannot execute
2. **No config exploitation** — Dangerous config keys removed
3. **No supply chain surprise** — Submodules blocked by default
4. **No LFS auto-fetch** — Binary blobs don't auto-download
5. **Integrity verified** — ZIP matches git HEAD
6. **Full functionality** — git blame, bisect, log all work

## Exit Codes

| Code | Meaning |
|------|---------|
| `0` | Success, no findings above threshold |
| `1` | Findings above threshold (security issue) |
| `2` | Configuration or argument error |
| `3` | Network or download error |
| `4` | Scan error (plugin failure, timeout) |
| `5` | Archive safety violation (zip bomb, path traversal) |
| `6` | Integrity verification failed (ZIP/git mismatch) |

## License

**Implementation** (source code): MIT OR Apache-2.0

**Specifications** (docs, architecture): [Specification Commons License v0.1 (SCL-0.1)](LICENSE-SCL)

**Tests/Scenarios**: SCL-0.1 (Restricted Scenarios)

See [LICENSING.md](LICENSING.md) for the full layered licensing details.

## Contributing

Contributions welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## Security

For security issues, please email security@armyknifelabs.com