-## `git‑mind` turns Git repositories into serverless, distributed graph databases where relationships are first‑class and move through time with your history.
+## `git‑mind` turns Git repositories into serverless, distributed graph databases where relationships are first‑class and move through time with your history
- Version your thoughts
- Travel back in time to see what you were thinking and then step forward, watching your thoughts evolve and change over time
@@ -19,6 +19,7 @@
---
Table of Contents
+
- [Overview](#overview)
- [Why git-mind](#why-git-mind)
- [How It Works](#how-it-works)
@@ -31,6 +32,7 @@ Table of Contents
- [License](#license)
## Overview
+
git‑mind lets you link code, docs, notes, experiments — anything tracked in Git — with first‑class semantic edges (e.g., “implements”, “tests”, “documents”, “refines”, “depends_on”).
These edges are stored in your repository (no servers), replicate with `git clone`, and are scoped to branches and commits. Check out an old commit and you get the semantics from that moment in time. Merge branches and the graph merges deterministically, just like your code.
@@ -38,6 +40,7 @@ These edges are stored in your repository (no servers), replicate with `git clon
In short: organize ideas and artifacts as a graph, with Git as the transport, history, and security model.
## Why git-mind
+
- Version your thoughts: track the “why” and “how” alongside the “what”.
- Serverless graph DB: your repo is the database — clone, branch, merge.
- Time‑travel semantics: branch/commit‑scoped relationships that evolve.
@@ -46,11 +49,13 @@ In short: organize ideas and artifacts as a graph, with Git as the transport, hi
- Cross‑repo, forkable semantics: share, branch, and merge understanding across clones.
Human + AI co‑thought
+
- Shared memory for people and tools: the repo holds both your links and AI‑suggested links.
- Trust and review: filter by attribution (human/AI) and lanes (e.g., suggested, verified).
- Forkable cognition: try ideas in branches, then merge deterministic edges back.
Use cases
+
- Architecture: link docs ⇄ code ⇄ tests; explore fan‑in/out and evolution.
- Notes/Zettelkasten: link ideas, excerpts, and references across a repo.
- Research: connect papers, datasets, scripts, and results with provenance.
@@ -58,6 +63,7 @@ Use cases
- Decisions: tie ADRs to impacted modules and follow their downstream effects.
## How It Works
+
- Journal (truth)
- Each edge append becomes a Git commit under `refs/gitmind/edges/` with a compact CBOR payload.
- Append‑only, branch‑scoped, time‑travel‑safe; merges behave like code.
@@ -66,6 +72,7 @@ Use cases
- Rebuildable; never merged; safe to delete.
## Core Concepts
+
- Edge: A directed link (source → target) between any two Git blobs with metadata.
- Names‑as‑truth: `type_name`/`lane_name` are stored as strings on the edge; IDs are derived only for performance.
- Attribution: Who/what created the edge (human/AI), with author/session metadata. Surfaces as filters and review signals.
@@ -73,15 +80,18 @@ Use cases
- Advice (optional): Data‑driven semantics (e.g., symmetry, implies) that merge deterministically.
## Quickstart
+
Requirements (dev): Git, Meson, Ninja, C23 compiler (gcc‑14 or clang‑20 recommended). See [DEV_SETUP](docs/DEV_SETUP.md).
Build and test
+
```bash
make # meson+ninja build in ./build
make test # runs unit tests
```
Create and query links (code, docs, notes)
+
```bash
# Link a design doc to its implementation
git mind link docs/auth-flow.md src/auth.c --type implements --lane verified
@@ -108,6 +118,7 @@ git mind list --from notes/idea.md
```
What to expect
+
- Links are stored under `refs/gitmind/edges/` and show up in history.
- Queries use the cache when available; otherwise scan the journal.
- Everything is just Git — no external servers, no hidden DBs.
@@ -120,6 +131,7 @@ What to expect
- See also: docs/operations/Environment_Variables.md for all supported env vars.
## Human + AI Co‑Thought
+
git‑mind is designed to be a shared, versioned memory for humans and AI — a place where both parties can write edges, discover connections, and converge by merging branches.
- Shared memory, no servers: the repo is the database; AI tools can read/write edges locally just like you.
@@ -129,6 +141,7 @@ git‑mind is designed to be a shared, versioned memory for humans and AI — a
- Control and safety: filter by attribution, lanes, or commit; disable advice application; keep AI ops in a branch until reviewed.
Example flows (concept)
+
```bash
# AI suggests edges into a separate branch/lane
git checkout -b ai/suggestions
@@ -147,6 +160,7 @@ git mind list --lane suggested --source ai
See: [Attribution System](docs/architecture/attribution-system.md) and [ADR 0001](docs/adr/0001-first-class-semantics.md).
## Status & Roadmap
+
Project status: early‑stage, with core primitives usable today. The vision is a shared, serverless, forkable thought‑graph for humans and AI. Today we are focused on the core that makes that vision real over time:
- Shipping now/next: journal (edges‑as‑commits), cache (fast queries), CLI (link/list/cache‑rebuild), names‑as‑truth semantics, AUGMENTS for evolution.
@@ -159,18 +173,21 @@ Expect CLI and APIs to change as we stabilize the core. See the planning docs fo
- Milestones & Sprints: [Milestones](docs/planning/Milestones.md), [Sprint Plans](docs/planning/Sprint_Plans.md)
## Architecture
+
- System overview: [System Architecture](docs/architecture/System_Architecture.md)
- Data model: edges as commits, names‑as‑truth, branch/time scoping — see [Journal Architecture Pivot](docs/architecture/journal-architecture-pivot.md)
- Cache design: [Bitmap Cache](docs/architecture/bitmap-cache-design.md)
- Semantics PRD & ADR: [PRD](docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md), [ADR 0001](docs/adr/0001-first-class-semantics.md)
## Contributing
+
- Start here: [CONTRIBUTING.md](CONTRIBUTING.md)
- Dev setup: [DEV_SETUP](docs/DEV_SETUP.md)
- Docs index: [docs/README.md](docs/README.md)
- Pre‑commit: `pre-commit install` (clang‑format, docs link/TOC checks, secrets)
Principles
+
- C23, warnings‑as‑errors; keep clang‑tidy warnings at zero in target modules.
- Names‑as‑truth for semantics; caches are derived and rebuildable.
- Small, pause‑safe increments; document decisions (ADRs) as you go.
diff --git a/TASKLIST.md b/TASKLIST.md
index 93ccb513..b662425d 100644
--- a/TASKLIST.md
+++ b/TASKLIST.md
@@ -2,15 +2,17 @@
## 💀 BRUTAL REVIEW SUMMARY
-**Grade: C+** - Good foundations but dangerous gaps
+__Grade: C+__ - Good foundations but dangerous gaps
+
+__What's Good:__
-**What's Good:**
- Error/Result system design (A-)
- UTF-8 DFA validator (A)
- Zero warnings, no magic numbers
- Clean growth logic
-**What's Broken:**
+__What's Broken:__
+
- Declared functions not implemented (F)
- Path header with no implementation (F)
- No crypto DI for testing (D)
@@ -19,11 +21,12 @@
- No CI enforcement (F)
- <60% real coverage (D)
-**Core Violation:** "If it's not done, don't merge it"
+__Core Violation:__ "If it's not done, don't merge it"
## ✅ Completed Tasks
### 3. Crypto Layer
+
- [x] Created `core/include/gitmind/crypto/sha256.h` - SHA256 abstraction
- [x] Implemented `core/src/crypto/sha256.c` - Using libsodium
- [x] Created `core/tests/unit/test_sha256.c` - NIST test vectors
@@ -34,6 +37,7 @@
- [x] All crypto tests pass! ✅
### 4. UTF-8 Validation
+
- [x] Created `core/include/gitmind/utf8/validate.h` - DFA-based validator API
- [x] Implemented `core/src/utf8/validate.c` - Björn Höhrmann's DFA
- [x] Created `core/tests/unit/test_utf8.c` - Comprehensive test suite
@@ -41,6 +45,7 @@
- [x] All UTF-8 tests pass! ✅
### 1. Error Handling System
+
- [x] Created `core/include/gitmind/result.h` - Result type with named types (no anonymous structs!)
- [x] Created `core/include/gitmind/error.h` - Error handling with chaining
- [x] Implemented `core/src/error/error.c` - Full error implementation
@@ -48,6 +53,7 @@
- [x] All error tests pass! ✅
### 2. Domain Types (Partial)
+
- [x] Created `core/include/gitmind/types/id.h` - 256-bit IDs with strong typing
- [x] Created `core/include/gitmind/types/string.h` - Owned strings vs views
- [x] Created `core/include/gitmind/types/path.h` - Path type with validation
@@ -62,17 +68,20 @@
### ✅ COMPLETED (Session 2025-06-22)
#### 1. Delete or Implement ALL Declared Functions ✅
+
- [x] Implemented `gm_string_substring()` with bounds checking
- [x] Implemented `gm_string_trim()` with whitespace handling
- [x] Added comprehensive tests for both functions
#### 2. Ship Real `gm_path.c` Immediately ✅
+
- [x] Created `core/src/types/path.c` with full implementation
- [x] Implemented `gm_path_new()`, `join()`, `canonicalize()`, `validate()`
- [x] Added comprehensive path tests (8 test functions)
- [x] Note: `gm_path_rules_t` left as forward declaration (for future extension)
#### 3. Deterministic Crypto Interface ✅
+
- [x] Created `gm_crypto_backend_t` interface in `core/include/gitmind/crypto/backend.h`
- [x] Implemented libsodium backend (default)
- [x] Implemented test backend with deterministic outputs
@@ -80,11 +89,13 @@
- [x] Added backend switching tests
#### 4. Fix ID Hashing ✅
+
- [x] Replaced `gm_id_hash()` to use SipHash-2-4 on full 256-bit digest
- [x] Added proper libsodium constants usage
- [x] Added collision resistance tests
#### 5. Fix Error Message Buffer ✅
+
- [x] Replaced fixed 256-byte buffer with SSO implementation
- [x] 48-byte small string threshold
- [x] Updated `gm_error_free()` to handle heap allocation
@@ -93,6 +104,7 @@
### ✅ COMPLETED (Session 2025-06-22 Continued)
#### 6. CI Must Enforce Lint & Sanitizers ✅
+
- [x] Created complete `.github/workflows/core-quality.yml`
- [x] Added `.clang-tidy` configuration file
- [x] CI runs clang-tidy with warnings-as-errors
@@ -100,20 +112,24 @@
- [x] Added TODO/FIXME/XXX check in CI pipeline
#### 7. Coverage Must Be ≥80% ✅
+
- [x] Updated Makefile with coverage support
- [x] Added gcovr with 80% line, 70% branch requirements
- [x] CI enforces coverage minimums
#### 8. Split `gm_string.c` By Responsibility ✅
+
- [x] Created `string_core.c` - allocation/growth
- [x] Created `string_utf8.c` - UTF-8 validation
- [x] Updated `string.c` - views/comparison only
#### 9. Ban All TODOs/FIXMEs in Pre-commit ✅
+
- [x] Created `.git/hooks/pre-commit` script
- [x] Created `scripts/setup-hooks.sh` for team
#### 10. Convert ALL Fallible Functions to GM_RESULT ✅
+
- [x] All ID functions return GM_RESULT
- [x] All random functions return GM_RESULT
- [x] All SHA256 functions return GM_RESULT
@@ -122,11 +138,13 @@
## 🔨 ZERO-BULLET REVIEW (2025-06-22 Second Pass)
### 1. Duplication Hell – Link Time Failures ✅
+
- [x] Two string modules defining same symbols - VERIFIED FALSE: string.c only has views/comparison, string_core.c has allocation
- [x] Two conflicting `gm_session_id_new` implementations - VERIFIED FALSE: only one implementation exists
- [x] Multiple Makefile variants exist but serve different purposes (main, core, src, benchmarks, legacy tests)
### 2. Path API Is Still Half-Baked ✅
+
- [x] `gm_path_make_relative()` - IMPLEMENTED: full relative path computation
- [x] `gm_path_canonicalize()` - IMPLEMENTED: proper . and .. resolution
- [x] `gm_path_validate()` - IMPLEMENTED: uses rules (max length, traversal, absolute/relative)
@@ -134,38 +152,45 @@
- [x] Cross-platform separator handling - IMPROVED: detects and preserves separator style
### 3. Error System – SSO Good, Buffer Games Bad ✅
+
- [x] `set_error_message()` - FIXED: now measures exact length with vsnprintf(NULL, 0, ...)
- [x] `gm_error_format()` - FIXED: calculates exact size needed in first pass
### 4. Hash-Table DoS Still Possible ✅
+
- [x] SipHash now uses random key generated on first use
- [x] Fallback to deterministic key if random generation fails
### 5. Result/Error Discipline Not Consistent ✅
+
- [x] All core functions now use GM_RESULT properly (verified in Order #10)
- [x] `gm_path_is_safe()` is a pure predicate, bool return is correct
- [x] `gm_node_id_from_path` and `gm_edge_id_from_triple` are forward declarations only (not implemented)
### 6. Build & CI Gaps ✅
+
- [x] clang-tidy wired into `make check` and `make lint` targets
- [x] Sanitizers enabled via `make test-sanitize` or `SANITIZE=1 make test`
- [x] TODO/FIXME grep included in CI workflow and pre-commit hook (via scripts/setup-hooks.sh)
- [x] Added `make test-all` to run full quality suite
### 7. Minor Yet Painful Cuts ✅
+
- [x] `gm_error_t` context - ADDED: context_free callback field for proper cleanup
- [x] UTF-8 streaming test - ALREADY EXISTS: test_utf8_streaming() tests multi-chunk validation
- [x] `gm_string_concat` - VERIFIED SAFE: concat only reads inputs, doesn't store pointers
-
### 1. Fix Build Issues
+
- [x] Clean local build artifacts: ~~`cd core && rm -rf build/`~~ ✅ DONE
- [x] Run tests IN DOCKER: `make test-core` from repo root ✅ DONE
- [x] Fix any remaining compilation errors ✅ DONE
- [x] Ensure all tests pass in Docker environment ✅ DONE
### ⚠️ CRITICAL: Fix Placeholder Code BEFORE Moving On
-**DO NOT proceed to new features until these are fixed:**
+
+__DO NOT proceed to new features until these are fixed:__
+
- [x] Replace fake SHA256 with libsodium crypto_hash_sha256 ✅ DONE
- [x] Replace fake random with libsodium CSPRNG ✅ DONE
- [x] Replace fake UTF-8 validation with DFA-based validator ✅ DONE
@@ -173,23 +198,25 @@
- [ ] Implement missing declared functions (substring, trim)
### 2. Fix Cut Corners in Current Code ⚠️
-- [x] **id.c**: Replaced with libsodium SHA256 ✅ DONE
+
+- [x] __id.c__: Replaced with libsodium SHA256 ✅ DONE
- Now using crypto_hash_sha256() from libsodium
- Added comprehensive test vectors
-- [x] **id.c**: Replaced with libsodium CSPRNG ✅ DONE
+- [x] __id.c__: Replaced with libsodium CSPRNG ✅ DONE
- Now using randombytes_buf() for cryptographically secure randomness
- Added entropy quality tests
-- [x] **string.c**: Implemented proper UTF-8 validation ✅ DONE
+- [x] __string.c__: Implemented proper UTF-8 validation ✅ DONE
- Using DFA-based validator (Björn Höhrmann's approach)
- Rejects overlong encodings, surrogates, invalid sequences
- Performance: >1GB/s throughput
-- [ ] **string.c**: Missing substring and trim implementations
+- [ ] __string.c__: Missing substring and trim implementations
- Functions declared in header but not implemented!
-- [ ] **path.h**: Forward declarations without implementations
+- [ ] __path.h__: Forward declarations without implementations
- Missing gm_path_rules_t definition
- Missing gm_edge_type_t definition
### 3. Complete Domain Types (Properly This Time)
+
- [x] Implement proper UTF-8 validation using DFA approach ✅ DONE
- Created `core/include/gitmind/utf8/validate.h` with error enums
- Created `core/src/utf8/validate.c` with Höhrmann's DFA
@@ -201,6 +228,7 @@
- [ ] Add missing string operations (substring, trim)
### 4. Security Primitives (Next Major Task)
+
- [ ] Create `core/include/gitmind/security/validate.h` - Validation framework
- [ ] Create `core/include/gitmind/security/path.h` - Path security
- [ ] Create `core/include/gitmind/security/sanitize.h` - String sanitization
@@ -210,12 +238,15 @@
- [ ] Create comprehensive security tests
### 4. Update CI/CD
+
- [ ] Update GitHub workflows to run `make test-core`
- [ ] Ensure Docker builds include core/ tests
- [ ] Add core/ to quality checks (should pass with 0 warnings!)
### 5. Begin Module Migration
+
Once foundations are complete:
+
- [ ] Choose first module from src/ to migrate
- [ ] Rewrite using new foundations
- [ ] Ensure ZERO warnings
@@ -224,10 +255,10 @@ Once foundations are complete:
## 📊 Migration Progress
-- **Warnings in legacy src/**: 11,951 ❌
-- **Warnings in new core/**: 0 ✅
-- **Modules migrated**: 0 / ~12
-- **Foundation components**: 3.5 / 11 complete
+- __Warnings in legacy src/__: 11,951 ❌
+- __Warnings in new core/__: 0 ✅
+- __Modules migrated__: 0 / ~12
+- __Foundation components__: 3.5 / 11 complete
- Error handling: ✅ COMPLETE (100%)
- Domain types: 🚧 PARTIAL (90% - missing string functions & path)
- Crypto: ✅ COMPLETE (100% - SHA256 & CSPRNG)
@@ -237,6 +268,7 @@ Once foundations are complete:
## 🎯 Current Focus
Building foundations in core/ with:
+
1. ✅ Error handling (DONE - 100%)
2. 🚧 Domain types (90% - missing string funcs & path)
3. ⏳ Security primitives (NEXT PRIORITY)
@@ -249,7 +281,8 @@ Building foundations in core/ with:
10. ⏳ Full domain language
11. ⏳ Metadata layer
-### 📈 Progress Summary:
+### 📈 Progress Summary
+
- ✅ All placeholder code replaced with production implementations
- ✅ All magic numbers defined as constants
- ✅ Zero compiler warnings
@@ -258,43 +291,50 @@ Building foundations in core/ with:
## ✅ Code Quality Issues FIXED
-### Magic Numbers:
+### Magic Numbers
+
- [x] ALL magic numbers now defined as constants ✅
- [x] GM_ID_SIZE, GM_ID_HEX_SIZE, GM_ID_HEX_CHARS ✅
- [x] GM_ERROR_MSG_SIZE ✅
- [x] MIN_CAPACITY, GROWTH_FACTOR ✅
-### Placeholders Replaced:
+### Placeholders Replaced
+
- [x] SHA-256: Now using libsodium crypto_hash_sha256 ✅
- [x] Random: Now using libsodium randombytes_buf ✅
- [x] UTF-8: Now using DFA-based validator ✅
-### Design Decisions (NOW INVALIDATED):
+### Design Decisions (NOW INVALIDATED)
+
- [x] SHA256 and random functions don't return errors ❌ WRONG - They MUST return GM_RESULT
- [x] Functions that can't fail return by value ❌ WRONG - They CAN fail (alloc, etc)
- [x] Only operations that can fail use Result types ✅ RIGHT - But we missed many!
-### Build Issues to Fix:
+### Build Issues to Fix
+
- [ ] Replace hardcoded `gcc` with `$(CC)` in Makefile
- [ ] Move `GROWTH_FACTOR`, `MIN_CAPACITY` to shared header
- [ ] Use `size_t` not `int` for array indexing
- [ ] Add DRY fix: make `gm_error_print()` call `gm_error_format()`
### Memory Safety Concerns
+
- [ ] No bounds checking in some ID operations
- [ ] Missing null checks in some functions
- [ ] Context pointer in error struct is void* with no type safety
## 📝 Critical Implementation Notes
-### What's Production-Ready:
+### What's Production-Ready
+
- Error handling with result types and chaining
- ID generation with real SHA-256
- Random IDs with real CSPRNG
- UTF-8 validation with DFA (>1GB/s)
- All crypto via libsodium
-### What's Still Missing:
+### What's Still Missing
+
- String substring/trim functions (declared but not implemented)
- Path type implementation (header exists, no .c file)
- Security primitives (entire module)
@@ -302,12 +342,14 @@ Building foundations in core/ with:
## 🤝 HANDOFF TO NEXT CLAUDE (2025-06-22)
-### Current State:
-- **Orders 1-5**: ✅ COMPLETE (string functions, path module, crypto DI, SipHash fix, error SSO)
-- **Order 6**: 🚧 IN PROGRESS (CI workflow started but not finished)
-- **Orders 7-10**: ⏳ NOT STARTED
+### Current State
+
+- __Orders 1-5__: ✅ COMPLETE (string functions, path module, crypto DI, SipHash fix, error SSO)
+- __Order 6__: 🚧 IN PROGRESS (CI workflow started but not finished)
+- __Orders 7-10__: ⏳ NOT STARTED
+
+### Files Created/Modified This Session
-### Files Created/Modified This Session:
1. `core/src/types/string.c` - Added substring() and trim()
2. `core/src/types/path.c` - NEW - Complete path implementation
3. `core/include/gitmind/crypto/backend.h` - NEW - Crypto DI interface
@@ -319,17 +361,20 @@ Building foundations in core/ with:
9. `core/src/error/error.c` - Implemented SSO
10. `.github/workflows/core-quality.yml` - STARTED but incomplete
-### Critical Implementation Details:
-- **Crypto Backend**: All crypto now goes through `gm_crypto_get_backend()`
-- **Error SSO**: Messages ≤47 chars use inline storage, larger use heap
-- **SipHash**: Use proper libsodium constants and function signature
-- **Path Module**: Basic implementation done, `gm_path_rules_t` left as forward decl
+### Critical Implementation Details
+
+- __Crypto Backend__: All crypto now goes through `gm_crypto_get_backend()`
+- __Error SSO__: Messages ≤47 chars use inline storage, larger use heap
+- __SipHash__: Use proper libsodium constants and function signature
+- __Path Module__: Basic implementation done, `gm_path_rules_t` left as forward decl
+
+### What Needs Immediate Attention
+
+1. __Complete Order #6__: Finish the CI workflow configuration
+2. __Order #10 is CRITICAL__: Several functions still don't return GM_RESULT when they should
-### What Needs Immediate Attention:
-1. **Complete Order #6**: Finish the CI workflow configuration
-2. **Order #10 is CRITICAL**: Several functions still don't return GM_RESULT when they should
+### Test Coverage Status
-### Test Coverage Status:
- All new code has tests
- BUT overall coverage still <60% (need measurement tools)
@@ -343,4 +388,4 @@ Building foundations in core/ with:
- Separate owned (gm_string_t) from views (gm_string_view_t)
- Strong typedefs prevent type confusion
- NO MAGIC NUMBERS - define everything!
-- NO TODOS - implement it properly or don't ship it!
\ No newline at end of file
+- NO TODOS - implement it properly or don't ship it!
diff --git a/apps/cli/link.md b/apps/cli/link.md
index 7035d042..1dd65ecd 100644
--- a/apps/cli/link.md
+++ b/apps/cli/link.md
@@ -1,22 +1,26 @@
# Link Command
## Purpose
+
Create semantic links between files in the current Git repository.
## Design Rationale
### Command Syntax
+
```bash
git-mind link [--type ]
```
Why this order?
-1. **Natural reading**: "A links to B"
-2. **Consistent with cp/mv**: source first
-3. **Type is optional**: defaults to "references"
-4. **Extensible**: Can add --confidence, --reason later
+
+1. __Natural reading__: "A links to B"
+2. __Consistent with cp/mv__: source first
+3. __Type is optional__: defaults to "references"
+4. __Extensible__: Can add --confidence, --reason later
### Relationship Types
+
```
implements - Code implements design/spec
references - Documentation cross-reference
@@ -25,15 +29,18 @@ augments - Updates/extends previous
```
Limited set because:
+
- Each type has semantic meaning
- Tools can interpret differently
- Start small, extend carefully
### Type Parsing
+
```c
strcasecmp(str, "depends_on") == 0 ||
strcasecmp(str, "depends-on") == 0
```
+
- Accept both underscore and hyphen
- Case-insensitive for usability
- Common variations handled
@@ -41,17 +48,20 @@ strcasecmp(str, "depends-on") == 0
## User Experience
### Success Case
+
```bash
$ git-mind link README.md docs/install.md --type references
Created link: REFERENCES: README.md -> docs/install.md
```
Clear feedback:
+
- Confirms action taken
- Shows interpreted type
- Uses arrow notation
### Error Cases
+
```bash
$ git-mind link missing.md README.md
Error: Not found
@@ -62,6 +72,7 @@ Types: implements, references, depends_on, augments
```
Helpful errors:
+
- Brief error message
- Usage hint when args missing
- List valid types
@@ -89,37 +100,45 @@ sequenceDiagram
## Edge Cases
### Circular Links
+
```bash
-$ git-mind link A.md B.md
-$ git-mind link B.md A.md # Allowed!
+git-mind link A.md B.md
+git-mind link B.md A.md # Allowed!
```
+
- No cycle detection
- Both directions may be valid
- Graph algorithms handle cycles
### Self-Links
+
```bash
$ git-mind link README.md README.md
Created link: REFERENCES: README.md -> README.md
```
+
- Allowed (might reference earlier section)
- Unusual but not invalid
- Let user decide
### Duplicate Links
+
```bash
-$ git-mind link A.md B.md --type implements
-$ git-mind link A.md B.md --type implements # Duplicate!
+git-mind link A.md B.md --type implements
+git-mind link A.md B.md --type implements # Duplicate!
```
+
- Currently: Creates another edge
- Same content, different ULID
- Future: Dedupe option?
### Long Paths
+
```bash
$ git-mind link very/very/very/.../long/path.md other.md
Created link: REFERENCES: very/very/very/.../lo... -> other.md
```
+
- Paths truncated in display
- Full paths stored internally
- User-friendly output
@@ -127,6 +146,7 @@ Created link: REFERENCES: very/very/very/.../lo... -> other.md
## Argument Parsing
### Current Approach
+
```c
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "--type") == 0 && i + 1 < argc) {
@@ -140,11 +160,13 @@ for (int i = 0; i < argc; i++) {
```
Simple but effective:
+
- No getopt dependency
- Position-independent flags
- First two non-flags are source/target
### Future: Rich Options
+
```bash
git-mind link README.md API.md \
--type implements \
@@ -158,6 +180,7 @@ Extensibility built in.
## Performance
### Single Link
+
```
Parse args: ~1μs
Create edge: ~25μs
@@ -169,7 +192,9 @@ Total: ~236μs
Dominated by Git commit creation.
### Bulk Operations
+
Future enhancement:
+
```bash
git-mind link --batch < links.txt
# Format: source target type
@@ -180,6 +205,7 @@ Batch multiple edges per commit.
## Error Handling
### File Not Found
+
```c
result = gm_edge_create(ctx, src_path, tgt_path, rel_type, &edge);
if (result != GM_OK) {
@@ -187,14 +213,17 @@ if (result != GM_OK) {
return result;
}
```
+
- Clear error propagation
- Human-readable messages
- Return code for scripts
### Journal Write Failure
+
```
Error: Failed to write link
```
+
- Generic message (details in stderr)
- Could be permissions, disk full, etc.
- Git errors are complex
@@ -202,14 +231,17 @@ Error: Failed to write link
## Security Considerations
### Command Injection
+
```bash
-$ git-mind link "file;rm -rf /" other.md
+git-mind link "file;rm -rf /" other.md
```
+
- No shell execution
- Paths passed directly to Git
- Safe from injection
### Path Validation
+
- Git validates paths
- No additional sanitization
- Trust Git's rules
@@ -217,6 +249,7 @@ $ git-mind link "file;rm -rf /" other.md
## Testing Strategy
### Unit Tests
+
1. Valid link creation
2. Missing source file
3. Missing target file
@@ -224,6 +257,7 @@ $ git-mind link "file;rm -rf /" other.md
5. No arguments provided
### Integration Tests
+
```bash
# Setup
git init test-repo
@@ -241,6 +275,7 @@ git-mind list | grep "IMPLEMENTS: A.md -> B.md"
```
### User Acceptance Tests
+
```gherkin
Given a repository with files README.md and API.md
When I run "git-mind link README.md API.md --type references"
@@ -251,6 +286,7 @@ And the link should be persisted in the journal
## Future Enhancements
### Interactive Mode
+
```bash
$ git-mind link -i
Source file: README.md
@@ -262,12 +298,14 @@ Create link? [Y/n]:
```
### Bulk Import
+
```bash
$ git-mind link --import links.json
Imported 1,337 links
```
### Smart Suggestions
+
```bash
$ git-mind link README.md
Suggested targets:
@@ -279,10 +317,10 @@ Select target [1-3]:
## Why This Design Rocks
-1. **Simple**: Minimal arguments, clear output
-2. **Flexible**: Extensible without breaking changes
-3. **Fast**: Near-instant for single links
-4. **Safe**: No side effects beyond journal
-5. **Scriptable**: Exit codes and parseable output
+1. __Simple__: Minimal arguments, clear output
+2. __Flexible__: Extensible without breaking changes
+3. __Fast__: Near-instant for single links
+4. __Safe__: No side effects beyond journal
+5. __Scriptable__: Exit codes and parseable output
-As Linus would say: "Make the common case fast and simple."
\ No newline at end of file
+As Linus would say: "Make the common case fast and simple."
diff --git a/apps/cli/list.md b/apps/cli/list.md
index 465bd23d..93368108 100644
--- a/apps/cli/list.md
+++ b/apps/cli/list.md
@@ -1,35 +1,41 @@
# List Command
## Purpose
+
Query and display edges from the git-mind journal, with optional filtering.
## Design Rationale
### Command Syntax
+
```bash
git-mind list [] [--branch ] [--all]
```
Options:
-- **No args**: List all edges on current branch
-- **Path filter**: Show edges involving specific file
-- **Branch**: Query different branch
-- **--all**: Include all branches (future)
+
+- __No args__: List all edges on current branch
+- __Path filter__: Show edges involving specific file
+- __Branch__: Query different branch
+- __--all__: Include all branches (future)
### Callback Architecture
+
```c
int list_edge_callback(const gm_edge_t *edge, void *userdata)
```
Why callbacks?
-1. **Streaming**: Handle millions of edges without OOM
-2. **Filtering**: Skip non-matching edges early
-3. **Flexible**: Caller controls presentation
-4. **Composable**: Can chain filters/transformations
+
+1. __Streaming__: Handle millions of edges without OOM
+2. __Filtering__: Skip non-matching edges early
+3. __Flexible__: Caller controls presentation
+4. __Composable__: Can chain filters/transformations
## Display Format
### Default Output
+
```
IMPLEMENTS: src/main.c -> include/api.h
REFERENCES: README.md -> docs/design.md
@@ -39,12 +45,14 @@ Total: 3 links
```
Design choices:
+
- Relationship type first (most important)
- Human-readable paths (not SHAs)
- Summary count at end
- Clean, parseable output
### Empty Results
+
```bash
$ git-mind list missing.md
No links found for: missing.md
@@ -77,6 +85,7 @@ flowchart TD
## Filtering Logic
### Path Filter
+
```c
if (strcmp(edge->src_path, filter) != 0 &&
strcmp(edge->tgt_path, filter) != 0) {
@@ -85,11 +94,13 @@ if (strcmp(edge->src_path, filter) != 0 &&
```
Shows edges where file is:
+
- Source of the edge
- Target of the edge
- Either direction included
### Future: Advanced Filters
+
```bash
# Type filter
git-mind list --type implements
@@ -107,6 +118,7 @@ git-mind list --type references docs/ --since yesterday
## Performance Optimization
### Early Exit
+
```c
if (callback_result != 0) {
return callback_result; // Stop iteration
@@ -114,11 +126,13 @@ if (callback_result != 0) {
```
Allows:
+
- Limit results (`--limit 10`)
- Stop after match (`--first`)
- Timeout handling
### Journal Scan Cost
+
```
1K edges: ~5ms
10K edges: ~50ms
@@ -130,6 +144,7 @@ Linear scan acceptable up to ~100K edges.
Beyond that, need cache layer.
### Memory Usage
+
```
Stack: ~1KB (edge struct + locals)
Heap: 0 (no allocations)
@@ -140,41 +155,49 @@ Constant memory regardless of edge count.
## Edge Cases
### No Journal
+
```bash
$ git init new-repo
$ cd new-repo
$ git-mind list
No links found
```
+
- Fresh repo has no edges
- Handle gracefully
- Don't show errors
### Renamed Files
+
```
Original: README.md -> docs/api.md
After rename: README-old.md -> docs/api.md
```
+
- List shows current paths
- Historical SHAs still valid
- Path is for human context
### Concurrent Modifications
+
```
Process 1: git-mind list (reading)
Process 2: git-mind link A B (writing)
Result: New edge may or may not appear
```
+
- Read commits at snapshot
- No live updates
- Consistent view
### Unicode Display
+
```bash
$ git-mind list
IMPLEMENTS: 你好.c -> 世界.h
REFERENCES: café.md -> naïve.md
```
+
- UTF-8 passed through
- Terminal handles display
- No transliteration
@@ -182,11 +205,13 @@ REFERENCES: café.md -> naïve.md
## Output Formats
### Current: Human-readable
+
```
IMPLEMENTS: src/main.c -> include/api.h
```
### Future: Machine-readable
+
```bash
$ git-mind list --format=json
{"type":"implements","src":"src/main.c","tgt":"include/api.h",...}
@@ -201,6 +226,7 @@ digraph G {
```
### Future: Grouped Display
+
```bash
$ git-mind list --group-by=type
IMPLEMENTS (5):
@@ -217,6 +243,7 @@ REFERENCES (12):
## Error Handling
### Journal Read Errors
+
```c
result = gm_journal_read(ctx, branch, callback, &lctx);
if (result == GM_NOT_FOUND) {
@@ -226,15 +253,18 @@ if (result == GM_NOT_FOUND) {
```
Distinguish:
+
- Empty journal (normal)
- Read failure (error)
- No matches (normal)
### Invalid Branch
+
```bash
$ git-mind list --branch nonexistent
No links found
```
+
- Treated as empty branch
- No scary errors
- User-friendly
@@ -242,6 +272,7 @@ No links found
## Testing Strategy
### Unit Tests
+
1. Empty journal
2. Single edge
3. Filter matching source
@@ -250,6 +281,7 @@ No links found
6. Multiple edges
### Integration Tests
+
```bash
# Create test data
git-mind link A B
@@ -263,6 +295,7 @@ test $(git-mind list D | wc -l) -eq 1 # 0 + message
```
### Performance Tests
+
```bash
# Generate 10K edges
./generate-edges.sh 10000 | git-mind link --batch
@@ -275,6 +308,7 @@ time git-mind list > /dev/null
## Future Features
### Graph Traversal
+
```bash
# Find all dependencies of main.c
git-mind list main.c --traverse=depends_on
@@ -284,6 +318,7 @@ git-mind list design.md --traverse=implements --reverse
```
### Statistics
+
```bash
$ git-mind list --stats
Total edges: 1,337
@@ -298,6 +333,7 @@ Most connected:
```
### Watch Mode
+
```bash
$ git-mind list --watch
IMPLEMENTS: src/main.c -> include/api.h
@@ -307,10 +343,10 @@ NEW: REFERENCES: README.md -> CHANGELOG.md
## Why This Design Wins
-1. **Streaming**: Handles arbitrary scale
-2. **Flexible**: Filters compose naturally
-3. **Fast**: Minimal overhead per edge
-4. **Scriptable**: Clean, parseable output
-5. **Extensible**: Format/filter options ready
+1. __Streaming__: Handles arbitrary scale
+2. __Flexible__: Filters compose naturally
+3. __Fast__: Minimal overhead per edge
+4. __Scriptable__: Clean, parseable output
+5. __Extensible__: Format/filter options ready
-As Linus would appreciate: "Do one thing well. Listing is not analyzing."
\ No newline at end of file
+As Linus would appreciate: "Do one thing well. Listing is not analyzing."
diff --git a/apps/cli/main.md b/apps/cli/main.md
index 98ab4760..cd611f79 100644
--- a/apps/cli/main.md
+++ b/apps/cli/main.md
@@ -1,22 +1,26 @@
# Main CLI Entry Point
## Purpose
+
Parse commands, initialize Git context, dispatch to subcommands, and handle errors gracefully.
## Design Rationale
### Simple Command Structure
+
```bash
git-mind [args...]
```
Not using getopt or argparse because:
-1. **Minimal dependencies**: C23
-2. **Clear flow**: Easy to trace execution
-3. **Subcommand pattern**: Like Git itself
-4. **Future-proof**: Can add complex parsing later
+
+1. __Minimal dependencies__: C23
+2. __Clear flow__: Easy to trace execution
+3. __Subcommand pattern__: Like Git itself
+4. __Future-proof__: Can add complex parsing later
### Context Initialization
+
```c
typedef struct {
void *git_repo;
@@ -26,6 +30,7 @@ typedef struct {
```
Dependency injection from the start:
+
- Testable (mock Git operations)
- Flexible (different storage backends)
- Clean (no globals)
@@ -56,6 +61,7 @@ flowchart TD
## Error Handling Philosophy
### User-Friendly Messages
+
```c
if (error < 0) {
fprintf(stderr, "Error: Not in a git repository\n");
@@ -66,15 +72,18 @@ if (error < 0) {
```
Two-level errors:
+
1. Simple message for users
2. Technical details if available
### Exit Codes
+
```c
return (result == GM_OK) ? 0 : 1;
```
Simple binary:
+
- 0 = Success
- 1 = Any error
@@ -83,6 +92,7 @@ Future: Specific codes for different failures.
## Context Management
### Initialization
+
```c
git_libgit2_init(); // Global init
git_repository_open(&repo, "."); // Find .git
@@ -91,18 +101,21 @@ ctx.log_fn = gm_log_default;
```
Clean sequence:
+
1. Initialize libgit2 once
2. Open repository in current dir
3. Set up function pointers
4. Pass context everywhere
### Cleanup
+
```c
git_repository_free(repo);
git_libgit2_shutdown();
```
RAII-style cleanup:
+
- Always free repository
- Shutdown libgit2 last
- No resource leaks
@@ -110,6 +123,7 @@ RAII-style cleanup:
## Command Dispatch
### Current Design
+
```c
if (strcmp(cmd, "link") == 0) {
result = gm_cmd_link(&ctx, argc - 2, argv + 2);
@@ -119,11 +133,13 @@ if (strcmp(cmd, "link") == 0) {
```
Simple string comparison:
+
- No hash table needed (few commands)
- Clear control flow
- Easy to add commands
### Future: Command Table
+
```c
typedef struct {
const char *name;
@@ -143,6 +159,7 @@ When we have 10+ commands.
## Usage Display
### Current Format
+
```
Usage: git-mind [args...]
@@ -158,12 +175,14 @@ Relationship types:
```
Design principles:
+
- Examples in command list
- Common options documented
- Relationship types explained
- Compact but complete
### Future: Man Page Generation
+
```c
if (strcmp(argv[1], "--generate-man") == 0) {
generate_man_page();
@@ -176,17 +195,20 @@ Auto-generate from help text.
## Platform Considerations
### Repository Discovery
+
```c
git_repository_open(&repo, ".");
```
libgit2 handles:
+
- Walking up to find .git
- Worktree detection
- Submodule boundaries
- Case-insensitive filesystems
### Path Separators
+
- libgit2 normalizes to forward slashes
- We inherit this behavior
- No platform-specific code needed
@@ -194,6 +216,7 @@ libgit2 handles:
## Security Hardening
### No Command Injection
+
```c
// We never do this:
system(user_input); // ❌
@@ -203,14 +226,17 @@ gm_cmd_link(&ctx, argc, argv); // ✅
```
### Argument Validation
+
- Commands validate their own args
- Main only routes to commands
- No preprocessing of user input
### Signal Handling
+
Currently: None (default behavior)
Future considerations:
+
```c
signal(SIGINT, cleanup_handler);
signal(SIGTERM, cleanup_handler);
@@ -221,12 +247,15 @@ For long-running operations.
## Testing Approach
### Unit Testing Challenges
+
Main is hard to unit test. Instead:
+
- Keep main thin
- Test command functions directly
- Integration tests for full flow
### Integration Tests
+
```bash
#!/bin/bash
# Test not in git repo
@@ -241,6 +270,7 @@ git-mind bogus 2>&1 | grep -q "Unknown command"
```
### Memory Testing
+
```bash
valgrind --leak-check=full git-mind list
# Should show: All heap blocks were freed
@@ -249,6 +279,7 @@ valgrind --leak-check=full git-mind list
## Performance Notes
### Startup Cost
+
```
git_libgit2_init(): ~1ms
git_repository_open(): ~5ms
@@ -259,6 +290,7 @@ Total overhead: ~6ms
Acceptable for CLI tool.
### Memory Usage
+
```
libgit2 init: ~2MB
Repository open: ~500KB
@@ -271,6 +303,7 @@ Reasonable for modern systems.
## Future Enhancements
### Plugin Architecture
+
```c
if (is_plugin_command(cmd)) {
exec_plugin(cmd, args);
@@ -280,6 +313,7 @@ if (is_plugin_command(cmd)) {
Allow git-mind-* executables.
### Configuration
+
```c
git_config_get_string(&value, config, "gitmind.editor");
```
@@ -287,6 +321,7 @@ git_config_get_string(&value, config, "gitmind.editor");
Read from .git/config.
### Daemon Mode
+
```bash
git-mind daemon --port 8080
```
@@ -294,6 +329,7 @@ git-mind daemon --port 8080
For web UI or API server.
### Shell Completion
+
```bash
# Bash completion
_git_mind() {
@@ -304,10 +340,10 @@ complete -F _git_mind git-mind
## Why This Design Wins
-1. **Simple**: Main does minimal work
-2. **Extensible**: Easy to add commands
-3. **Testable**: Dependency injection
-4. **Robust**: Proper cleanup always
-5. **Fast**: Minimal startup overhead
+1. __Simple__: Main does minimal work
+2. __Extensible__: Easy to add commands
+3. __Testable__: Dependency injection
+4. __Robust__: Proper cleanup always
+5. __Fast__: Minimal startup overhead
-As Linus would say: "The main() function should be so simple that it's obviously correct."
\ No newline at end of file
+As Linus would say: "The main() function should be so simple that it's obviously correct."
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 592fa20d..3f3d13e0 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -4,11 +4,12 @@
> "Long live the king!" - Scar, moments before disaster
-### What is this?
+### What is this
Just as Disney invented AI flocking algorithms for The Lion King's wildebeest stampede scene, we use Roaring Bitmaps to handle massive edge queries in git-mind.
This benchmark simulates Mufasa's worst day:
+
- Thousands of wildebeest (edges) stampeding
- Half running TO Mufasa, half running FROM
- Can our cache help him survive? (Spoiler: Yes!)
@@ -49,4 +50,4 @@ No TODOs were harmed in the making of this benchmark.
---
-*"Remember who you are..." - A developer with a working cache!* 🦁
\ No newline at end of file
+_"Remember who you are..." - A developer with a working cache!_ 🦁
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index f3947768..9e666c22 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -7,22 +7,25 @@ This document serves as the master index for all architectural documentation and
## 🏗️ Current Architecture Status
-**Status**: Library‑first architecture in progress; CLI and tooling evolving
-**Focus**: Journal (edges‑as‑commits), cache (Roaring Bitmaps), CLI (link/list/cache‑rebuild)
-**Target**: Single‑header C library with optional frontends (CLI, MCP, hooks)
+__Status__: Library‑first architecture in progress; CLI and tooling evolving
+__Focus__: Journal (edges‑as‑commits), cache (Roaring Bitmaps), CLI (link/list/cache‑rebuild)
+__Target__: Single‑header C library with optional frontends (CLI, MCP, hooks)
## 📚 Architecture Documents
### Core Design
+
- [Modular Restructure Plan](docs/architecture/MODULAR_RESTRUCTURE_PLAN.md) — plan for modular system and single‑header direction
- Memory Architecture (TODO) — custom allocators and memory pooling design
- Single Header Design (TODO) — how the amalgamated `gitmind.h` works
### API Design
+
- Core Library API (TODO) — Public API for `gitmind.h`
- MCP Service (Optional, TODO) — Local‑only tools integration for co‑thought
### Implementation Details
+
- CBOR Encoding Format — see [PRD](docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md)
- Git Storage Model — see [Journal Architecture Pivot](docs/architecture/journal-architecture-pivot.md)
- Cache Architecture — see [Bitmap Cache](docs/architecture/bitmap-cache-design.md)
@@ -41,11 +44,11 @@ git-mind/
## 🔧 Key Design Decisions
-1. **Single‑header library (direction)** — core functionality under one include
-2. **Lean dependencies** — libgit2 + CRoaring for cache (vendor or pin in CI)
-3. **Custom allocators** — pool allocation for performance (planned)
-4. **CBOR encoding** — compact binary format for edges
-5. **Git as database** — serverless; no external storage needed
+1. __Single‑header library (direction)__ — core functionality under one include
+2. __Lean dependencies__ — libgit2 + CRoaring for cache (vendor or pin in CI)
+3. __Custom allocators__ — pool allocation for performance (planned)
+4. __CBOR encoding__ — compact binary format for edges
+5. __Git as database__ — serverless; no external storage needed
## 🚀 Migration Status
@@ -58,6 +61,7 @@ git-mind/
| CLI App | In progress | link/list/cache‑rebuild stabilized first |
### Migration Philosophy
+
See [MIGRATION_PHILOSOPHY](docs/architecture/MIGRATION_PHILOSOPHY.md). During migration, we prioritize correctness and clarity; post‑migration we focus effort on real issues and developer velocity.
## 📋 Quick Links
diff --git a/docs/CI_STRATEGY.md b/docs/CI_STRATEGY.md
index cbf61609..b77196c8 100644
--- a/docs/CI_STRATEGY.md
+++ b/docs/CI_STRATEGY.md
@@ -1,7 +1,9 @@
# CI/CD Strategy
## Overview
+
This repository enforces high correctness and portability while centering on modern C23. CI is split into:
+
- Gating jobs that must pass for merges
- Canary jobs that provide early portability signals but do not block
- Static analysis (clang-tidy) with a strict baseline
@@ -10,14 +12,14 @@ This repository enforces high correctness and portability while centering on mod
## Compiler Matrix
### Gating (C23 focus)
-
+
- `gcc-14` — first broadly usable GCC with C23 support
- `clang-20` — latest LLVM with strong C23 + clang-tidy 20
Rationale: These represent the C23 target surface we care about. They block the PR when they fail.
### Canaries (non‑blocking)
-
+
- `gcc-12`, `gcc-13` — older GCCs common on LTS distros
- `clang-18`, `clang-19` — earlier LLVMs
@@ -34,29 +36,29 @@ flowchart LR
```
## Static Analysis
-
+
- `clang-tidy` 20 with `quality/.clang-tidy`; warnings-as-errors.
- Baseline file `tools/baseline_count.txt` enforces no regressions.
- CI builds a deterministic LLVM 20 environment in Docker.
- CRoaring is installed from apt when available, or built from source in CI to stabilize aarch64 and older runners.
## Builds & Tests
-
+
- Meson + Ninja builds and runs unit tests.
- Cache artifacts are not pushed; they are derived and may be uploaded only for debugging.
## Docker Hygiene
-
+
- Images are namespaced and labeled for safe cleanup: `gitmind/ci:clang-20`, `gitmind/gauntlet:`; label `com.gitmind.project=git-mind`.
- Local helper: `make docker-clean` removes only project images/containers and builder cache.
## Time & Cost
-
+
- Gating jobs run in parallel and should complete under a few minutes.
- Canaries may be slower; they are non‑blocking and primarily diagnostic.
## Future Enhancements
-
+
- Add cohesion-report to CI to summarize semantic (advice) changes across merges.
- Nightly long‑matrix (more compilers/OSes) as a separate scheduled workflow.
- Cache Docker layers to reduce cold start times.
diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md
index b3937798..14620aa9 100644
--- a/docs/DEV_SETUP.md
+++ b/docs/DEV_SETUP.md
@@ -4,23 +4,26 @@
### LLVM / clang-tidy
-We standardize on **LLVM 20.x**.
+We standardize on __LLVM 20.x__.
+
+#### macOS (Homebrew)
-#### macOS (Homebrew):
```bash
brew install llvm
echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
-#### Ubuntu / Debian:
+#### Ubuntu / Debian
+
```bash
wget -O - https://apt.llvm.org/llvm.sh | sudo bash -s -- 20
sudo apt-get install -y clang-tidy-20
sudo ln -sf /usr/bin/clang-tidy-20 /usr/local/bin/clang-tidy
```
-#### Verify installation:
+#### Verify installation
+
```bash
clang-tidy --version # LLVM version 20.1.x
```
@@ -28,6 +31,7 @@ clang-tidy --version # LLVM version 20.1.x
## Pre-commit Hooks
Install pre-commit hooks to ensure code quality:
+
```bash
pre-commit install
```
@@ -35,6 +39,7 @@ pre-commit install
## Docker Development
For consistent development environment:
+
```bash
make dev # Opens a shell in the Docker container
```
@@ -42,7 +47,8 @@ make dev # Opens a shell in the Docker container
## Building
Always build in Docker to match CI:
+
```bash
make test-core # Run core tests
make check # Run quality checks
-```
\ No newline at end of file
+```
diff --git a/docs/PRDs/PRD-co-thought-mcp-service.md b/docs/PRDs/PRD-co-thought-mcp-service.md
index bc239311..729c1fa5 100644
--- a/docs/PRDs/PRD-co-thought-mcp-service.md
+++ b/docs/PRDs/PRD-co-thought-mcp-service.md
@@ -1,6 +1,7 @@
# PRD: Co‑Thought MCP Service (Local Tools Integration)
Table of Contents
+
- Summary
- Goals
- Non‑Goals
@@ -14,20 +15,24 @@ Table of Contents
- Rollout Plan
## Summary
+
Define a small, local‑only service that tools/agents can use to read/write git‑mind edges and query the journal/cache via a stable interface. This enables human + AI co‑thought: AI suggests edges into a `suggested` lane; humans review and promote to `verified`.
## Goals
+
- Provide a stable, local interface for edge CRUD and queries (no network dependence).
- Respect branch/time semantics: all operations target an explicit repo + ref.
- Enforce lane/attribution conventions for co‑thought workflows.
- Remain an optional module that does not gate core releases.
## Non‑Goals
+
- Remote/cloud service, authentication with external identity providers.
- Cross‑repo federation or long‑lived daemon management.
- Plugin runtime inside the service; keep core policies minimal.
## Scope and Assumptions
+
- Local‑only transport (Unix domain socket on POSIX; Named Pipe on Windows). Optional loopback HTTP for dev mode.
- Runs in the same workspace as the Git repo; reads/writes via libgitmind.
- No external network calls; all data remains local.
@@ -36,13 +41,16 @@ Define a small, local‑only service that tools/agents can use to read/write git
## Interface Design
Transport
+
- Default: Unix domain socket at `.gitmind/mcp.sock` (repo‑relative) or `\\.\pipe\gitmind-mcp` on Windows.
- Dev mode: `localhost:8765` (opt‑in), for easy testing.
Resource: Edge
+
- POST `/v1/edges`
- Creates an edge (journal append) with names‑as‑truth fields.
- Body (JSON):
+
```json
{
"repo": "/path/to/repo",
@@ -55,6 +63,7 @@ Resource: Edge
"confidence": 0.85
}
```
+
- Response: `{ "ulid": "01H...", "commit": "" }`
- GET `/v1/edges`
@@ -69,18 +78,22 @@ Resource: Edge
- Tombstone/remove by ULID (append a negative confidence or dedicated tombstone record per policy).
Health
+
- GET `/v1/health` → `{ "status": "ok", "repo": "...", "head": "..." }`
Errors
+
- JSON problem details: `{ "error": "invalid_argument", "message": "...", "field": "..." }`
## Data Model
+
- Edge record aligns with libgitmind’s attributed edge (names‑as‑truth + attribution + lane + paths + SHAs + ULID + timestamp + confidence).
- Derived IDs (`type_id`, `lane_id`) are never persisted across repos; computed on the fly for cache access.
## Flows
Suggest Edge (AI)
+
```mermaid
sequenceDiagram
participant Tool
@@ -93,6 +106,7 @@ sequenceDiagram
```
Review and Promote (Human)
+
```mermaid
sequenceDiagram
participant Human
@@ -107,15 +121,18 @@ sequenceDiagram
```
## Security and Privacy
+
- Local‑only by default (UDS/Named Pipe); loopback HTTP is for dev/testing only.
- No remote endpoints; no data leaves the machine unless the user explicitly exports.
- Rate limiting and simple allowlist of repos to avoid accidental cross‑workspace access.
## Performance Targets
+
- Edge append: < 5ms per request (excluding disk flush) in typical local repos.
- Query: median < 10ms for common filters with cache on 100k edges; graceful fallback to journal scan if cache absent.
## Acceptance Criteria
+
- Service starts/stops locally and serves `/v1/health`.
- Can append edges with names‑as‑truth, attribution, and lanes to the journal.
- Can query edges with filters for `--source` and `--lane` parity with CLI.
@@ -124,6 +141,7 @@ sequenceDiagram
- Tests cover happy paths and error handling; docs include examples.
## Rollout Plan
+
1) Stub service with UDS/Named Pipe transport and `/v1/health`.
2) Implement POST `/v1/edges` (append), GET `/v1/edges` (query minimal).
3) Add promotion and tombstone endpoints; harden filters.
diff --git a/docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md b/docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md
index de028d12..d3e64673 100644
--- a/docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md
+++ b/docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md
@@ -1,6 +1,7 @@
# PRD: First‑Class, Time‑Travel‑Safe Semantics for git‑mind
Table of Contents
+
- [Summary](#summary)
- [Goals](#goals)
- [Non‑Goals](#non-goals)
@@ -18,9 +19,11 @@ Table of Contents
- [Rollout Plan](#rollout-plan)
## Summary
+
This PRD proposes making user‑defined relationship semantics (type, lane) first‑class in git‑mind while preserving branch/time‑travel correctness and conflict‑free merging. Edges store names (strings) as ground truth; stable numeric IDs are derived from names at runtime for cache/index performance. Optional “Semantics Advice” records (committed like edges) allow richer behavior (e.g., symmetry, transitivity) without hard‑coding policies in core. Plugins can propose/normalize semantics via safe hooks.
## Goals
+
- First‑class semantics: accept any `type_name` and `lane_name`; no “custom” bucket.
- Time‑travel safe: semantics and behavior follow the commit/branch you view.
- Conflict‑free: merges converge without textual conflicts (append‑only data; CRDT‑like).
@@ -28,11 +31,13 @@ This PRD proposes making user‑defined relationship semantics (type, lane) firs
- Extensible: optional advice and plugins; core remains minimal and deterministic.
## Non‑Goals
+
- Global registries or centralized config not tied to Git history.
- Forcing a canonical vocabulary across repos.
- Shipping a full plugin runtime in this milestone (define hooks and data).
## Background (Current Architecture)
+
- Journal (truth): CBOR‑encoded edges under `refs/gitmind/edges/`; push/pull with code; time‑travel friendly.
- Cache (speed): Roaring bitmaps under `refs/gitmind/cache/`; rebuildable; never merged.
- Evolution: AUGMENTS edges maintain relationships across blob changes.
@@ -40,6 +45,7 @@ This PRD proposes making user‑defined relationship semantics (type, lane) firs
## Proposed Design
### Data Model (edge)
+
- Persist on every edge:
- `type_name: string`, `lane_name: string` (UTF‑8; normalized)
- Existing fields unchanged: `src_sha`, `tgt_sha`, `timestamp`, `ulid`, `confidence`, `src_path`, `tgt_path`, `attribution {source_type, author, session}`
@@ -65,6 +71,7 @@ classDiagram
```
### Semantics Advice (optional, committed)
+
- Small records committed alongside edges (append‑only), scoped to branch/time:
- Example fields (all optional):
- `type_name: string`, `aliases: [string]`, `symmetric: bool`, `transitive: bool`, `implies: [string]`, `color: string`, `icon: string`
@@ -88,6 +95,7 @@ erDiagram
```
### Entity Vocabulary (Nodes) and Relationship Types (Examples)
+
- Nodes are repo artifacts and concepts; edges link them semantically. The core stays file/blob-centric for identity but higher-level entities are resolvable overlays.
- Canonical examples (non-exhaustive, all stored as names):
- Nodes: `File`, `Function`, `RPC`, `Test`, `Feature`, `Migration`, `Issue`, `Component`, `Doc`.
@@ -113,12 +121,14 @@ erDiagram
Resolution note: In the C core, identity is via `src_sha`/`tgt_sha` (blob nodes). Higher-level entities are resolved by tooling (e.g., symbol index, SQL parser) and written as edges between the blobs that define them; names capture semantics.
### Deterministic IDs for Cache
+
- IDs are derived at runtime from names; used as bitmap keys:
- `type_id = fnv1a64("gm_type:" + nfc(type_name))`
- `lane_id = fnv1a64("gm_lane:" + nfc(lane_name))`
- Names are always kept with edges; IDs are never the source of truth.
### Plugins / Hooks (phaseable)
+
- `edge.pre_append`: normalize/validate names; map aliases.
- `edge.post_append`: derive edges (e.g., tests ⇒ references) by emitting additional journal entries.
- `cache.plan`: suggest index combinations (by derived IDs).
@@ -128,6 +138,7 @@ Resolution note: In the C core, identity is via `src_sha`/`tgt_sha` (blob nodes)
## Flows
### Edge Append (write path)
+
```mermaid
sequenceDiagram
participant CLI as git mind link
@@ -146,6 +157,7 @@ sequenceDiagram
```
### Query via Cache
+
```mermaid
flowchart LR
A[Filter: type=implements, lane=verified] --> B[Compute IDs]
@@ -156,6 +168,7 @@ E --> F[Return results]
```
### Branch/Timeline Safety
+
```mermaid
gitGraph
commit id: "init"
@@ -172,7 +185,9 @@ gitGraph
```
### Merge Semantics for Advice (CRDT choices)
+
We must deterministically merge advice from multiple branches. Recommended hybrid strategy:
+
- Scalars (bool/enum/number/color): Last‑Write‑Wins (LWW) per property; tie‑break by (logical_clock||timestamp, actor_id, ulid).
- Collections (aliases, implies, tags): Observed‑Remove Set (OR‑Set) union with tombstones (removes beat prior adds; later adds can re‑introduce).
- Maps: OR‑Set of keys, then per‑key LWW for values.
@@ -187,6 +202,7 @@ flowchart LR
```
Table (examples):
+
- symmetric: true vs false → winner by LWW.
- aliases: {calls, invokes} vs {uses} → OR‑Set union {calls, invokes, uses}.
- aliases: add "calls" vs remove "calls" → tombstone removes earlier add; later add re‑introduces with new tag.
@@ -194,7 +210,9 @@ Table (examples):
Optional policy advice (later): allow field‑level override (LWW vs OR_SET) committed in history; default remains hybrid.
### Cohesion Report (after merge)
+
Provide a deterministic summary of semantic changes post‑merge.
+
- CLI: `git mind cohesion-report [--since ] [--until ] [--branch ]`
- Outputs (machine + human):
- Scalar flips per type/lane advice with winner metadata
@@ -212,6 +230,7 @@ sequenceDiagram
```
## API Surfaces (C, minimal)
+
- New helpers (header‑only or core):
- `uint64_t gm_sem_type_id(const char* type_name_utf8)`
- `uint64_t gm_sem_lane_id(const char* lane_name_utf8)`
@@ -220,31 +239,37 @@ sequenceDiagram
- Advice parser (optional this milestone): validate and expose typed views.
## CBOR Notes (edge)
+
- Append two string entries (nfc normalized):
- `type_name: tstr`, `lane_name: tstr`
- Backward compatibility: decoder tolerates missing (treat as empty/"primary").
## Performance & Memory
+
- Name→ID hash cost: O(len(name)), negligible relative to I/O.
- Bitmap keys: 64‑bit IDs; no global tables; perfect for roaring bitmaps.
- Advice retrieval: optional; map by name/ID with in‑memory cache keyed per commit.
## Security
+
- Plugins out‑of‑process or WASM sandbox in future; no network/filesystem by default.
- Advice is data; core treats it as hints. Validation prevents pathological expansions.
## Migration & Compatibility
+
- Edges written without names remain valid; readers infer defaults and warn.
- Zero changes to refs layout.
- Importers/exporters operate on names; deterministic ID functions ensure cache stability.
## Risks & Mitigations
+
- Risk: Divergent semantics across branches complicate queries.
- Mitigation: Explicit branch scoping and advice commits; UI indicates branch semantics.
- Risk: Plugin abuse / perf.
- Mitigation: Optional plugins; timeouts; safe mode.
## Acceptance Criteria
+
- Edges persist and read `type_name`/`lane_name` strings.
- Cache uses derived type/lane IDs; query by name matches IDs.
- Merge two branches with different edges/advice yields union without textual conflicts.
@@ -252,11 +277,13 @@ sequenceDiagram
- Cohesion report implemented for merges; deterministic hybrid advice merge rules documented and covered by tests.
## Open Questions
+
- Advice CRDT flavor: LWW per property vs OR‑Set of facts — pick one for v1.
- Reserved lanes? e.g., `meta` lane for advice vs separate advice ref.
- Hash algorithm: FNV‑1a‑64 vs a SipHash variant (doc the exact function).
## Rollout Plan
+
1) Implement deterministic ID helpers + NFC normalization.
2) Extend edge CBOR with `type_name`/`lane_name` (readers tolerant).
3) Update cache builder to accept name filters → IDs.
diff --git a/docs/README.md b/docs/README.md
index 46fb6938..3355a83f 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,11 +1,13 @@
# docs/ (Index and Structure)
Table of Contents
+
- [Overview](#overview)
- [Planned Structure](#planned-structure)
- [Quick Map of Existing Docs](#quick-map-of-existing-docs)
## Overview
+
This index organizes documentation with stable links so the project can be paused and resumed without confusion.
- Start here if you’re new: [Journal Architecture Pivot](architecture/journal-architecture-pivot.md)
diff --git a/docs/TECHNICAL.md.md b/docs/TECHNICAL.md.md
index ff4c950e..1154fb84 100644
--- a/docs/TECHNICAL.md.md
+++ b/docs/TECHNICAL.md.md
@@ -7,10 +7,11 @@ This document covers the implementation details of git-mind. For user documentat
## System Overview
git-mind stores semantic edges as Git objects, enabling:
-- **Serverless operation** — Git is the database
-- **Branch-scoped semantics** — Edges exist per branch
-- **Deterministic merging** — Edges merge like code
-- **Time-travel queries** — Checkout = point-in-time graph
+
+- __Serverless operation__ — Git is the database
+- __Branch-scoped semantics__ — Edges exist per branch
+- __Deterministic merging__ — Edges merge like code
+- __Time-travel queries__ — Checkout = point-in-time graph
---
@@ -61,11 +62,11 @@ Properties:
### Query Pipeline
-1. **Parse** — Convert natural language or structured query
-2. **Plan** — Choose between cache (fast) or journal scan (complete)
-3. **Execute** — Bitmap operations or journal traversal
-4. **Filter** — Apply attribution, lane, time-range filters
-5. **Rank** — Sort by relevance, recency, or trust
+1. __Parse__ — Convert natural language or structured query
+2. __Plan__ — Choose between cache (fast) or journal scan (complete)
+3. __Execute__ — Bitmap operations or journal traversal
+4. __Filter__ — Apply attribution, lane, time-range filters
+5. __Rank__ — Sort by relevance, recency, or trust
### Query Examples
@@ -98,24 +99,24 @@ edges_at_commit("abc123def")
### Optimization Strategies
-1. **Lazy cache building** — Build on first query
-2. **Incremental updates** — Only process new edges
-3. **Bloom filters** — Quick negative lookups
-4. **Memory mapping** — Zero-copy bitmap access
+1. __Lazy cache building__ — Build on first query
+2. __Incremental updates__ — Only process new edges
+3. __Bloom filters__ — Quick negative lookups
+4. __Memory mapping__ — Zero-copy bitmap access
---
## Core Concepts
-**Edge** — Directed link (source → target) between any two Git blobs with metadata
+__Edge__ — Directed link (source → target) between any two Git blobs with metadata
-**Names-as-truth** — Type/lane names stored as strings on the edge; IDs derived only for performance
+__Names-as-truth__ — Type/lane names stored as strings on the edge; IDs derived only for performance
-**Attribution** — Who/what created the edge (human/AI), with author/session metadata
+__Attribution__ — Who/what created the edge (human/AI), with author/session metadata
-**AUGMENTS** — Evolution links (old blob → new blob) created on edits to preserve meaning through change
+__AUGMENTS__ — Evolution links (old blob → new blob) created on edits to preserve meaning through change
-**Advice (optional)** — Data-driven semantics (e.g., symmetry, implies) that merge deterministically
+__Advice (optional)__ — Data-driven semantics (e.g., symmetry, implies) that merge deterministically
---
@@ -174,11 +175,11 @@ git-mind/
## Key Design Decisions
-1. **Names as truth** — Types/lanes are strings, not IDs
-2. **ULID for edges** — Time-sortable, globally unique
-3. **CBOR encoding** — Compact, schema-evolution friendly
-4. **Roaring Bitmaps** — Best-in-class compressed bitsets
-5. **C23 core** — Modern C with _BitInt, typeof, auto
+1. __Names as truth__ — Types/lanes are strings, not IDs
+2. __ULID for edges__ — Time-sortable, globally unique
+3. __CBOR encoding__ — Compact, schema-evolution friendly
+4. __Roaring Bitmaps__ — Best-in-class compressed bitsets
+5. __C23 core__ — Modern C with _BitInt, typeof, auto
---
diff --git a/docs/adr/0001-first-class-semantics.md b/docs/adr/0001-first-class-semantics.md
index 366fd2be..d85d16c1 100644
--- a/docs/adr/0001-first-class-semantics.md
+++ b/docs/adr/0001-first-class-semantics.md
@@ -2,6 +2,7 @@
# ADR 0001: First‑Class, Time‑Travel‑Safe Semantics (Names as Truth)
Table of Contents
+
- [Status](#status)
- [Date](#date)
- [Related](#related)
@@ -18,11 +19,13 @@ Table of Contents
- Related: docs/PRDs/PRD-git-mind-semantics-time-travel-prototype.md
## Context
+
- git‑mind stores semantic edges as Git commits under `refs/gitmind/edges/` and maintains optional bitmap caches under `refs/gitmind/cache/`.
- Users need to define arbitrary relationship types and lanes (e.g., `CALLS`, `TESTS`, `verified`, `draft`) while preserving Git’s guarantees: branch isolation, time‑travel, conflict‑free merges.
- Prior designs with enums or global registries cause drift and merge conflicts, breaking time‑travel.
## Decision
+
- Treat `type_name` and `lane_name` (UTF‑8 strings) as the ground truth on every edge. Do not compress user types into a generic/custom bucket.
- Derive stable 64‑bit IDs from the normalized names (e.g., `fnv1a64("gm_type:" + nfc(type_name))`) only for cache/index performance. Names remain with edges; IDs are derived, never authoritative.
- Optional “Semantics Advice” is stored as append‑only records in the journal to express behavior (e.g., aliases, symmetry, transitivity, implies, colors). Advice is branch/commit scoped and time‑travel safe.
@@ -33,12 +36,14 @@ Table of Contents
- Caches remain derived per (branch, commit) shard; never merged; rebuild on demand.
## Rationale
+
- Names‑as‑truth ensures semantics time‑travel and merge like code; there is no global registry to drift or conflict.
- Derived IDs preserve roaring bitmap performance without sacrificing user vocabulary.
- Advice‑as‑data allows richer semantics without baking policy into core; it’s auditable and branch‑scoped.
- Hybrid CRDT rules deliver deterministic merges while minimizing loss of information.
## Consequences
+
- Pros
- First‑class, user‑defined semantics with no “custom” fallback.
- Deterministic behavior across clones/branches; time‑travel correct.
@@ -49,6 +54,7 @@ Table of Contents
- Advice parsing required for advanced behaviors; must cap expansion and detect cycles.
## Alternatives Considered
+
- Global registry of types/lanes with IDs
- Rejected: non‑Git state, merge conflicts, time‑travel breakage.
- Hard‑coded enums
@@ -57,12 +63,14 @@ Table of Contents
- Rejected: slower caches and queries at scale.
## Implementation Notes
+
- Extend edge CBOR with `type_name` and `lane_name` (NFC normalized). Readers tolerate missing fields for backward compatibility.
- Add helper functions `gm_sem_type_id(const char*)` and `gm_sem_lane_id(const char*)` (documented hash).
- Define advice object format; implement minimal reader; apply only when present.
- Provide a “cohesion‑report” CLI to summarize advice/semantics changes after merges.
## Rollout
+
1. Implement deterministic ID helpers + normalization.
2. Extend CBOR encoder/decoder; migrate writers.
3. Update cache/query to accept names → IDs.
diff --git a/docs/adr/0002-docs-reorganization.md b/docs/adr/0002-docs-reorganization.md
index 50785a2c..246cdb44 100644
--- a/docs/adr/0002-docs-reorganization.md
+++ b/docs/adr/0002-docs-reorganization.md
@@ -1,6 +1,7 @@
# ADR 0002: Documentation Reorganization and Planning Structure
Table of Contents
+
- [Status](#status)
- [Context](#context)
- [Decision](#decision)
@@ -8,12 +9,15 @@ Table of Contents
- [Related Documents](#related-documents)
## Status
+
- Accepted
## Context
+
The `docs/` directory had grown organically with mixed audiences and no single entry point, making it hard to pause and resume work. Planning content (roadmaps, releases, sprints) did not exist in a cohesive place, and cross-document links were inconsistent.
## Decision
+
1. Establish a non-destructive structure with clear hubs:
- Planning: `docs/planning/` (roadmap, releases, milestones, sprints)
- Architecture: `docs/architecture/` (unchanged, now linked by a central index)
@@ -23,10 +27,12 @@ The `docs/` directory had grown organically with mixed audiences and no single e
4. Introduce a `.legacy/` archive for historical planning/notes, and a `.trash/` quarantine for removed or superseded docs (with rationale in `.trash/README.md`).
## Consequences
+
- Pros: Easier navigation; project can be paused/resumed without loss of context; consistent links; planning is first-class alongside architecture/specs.
- Cons: Some existing deep links may need updates if/when files are moved into new folders. The `.trash/` process adds a minor maintenance step.
## Related Documents
+
- [docs/README.md](../README.md)
- [Product Roadmap](../planning/Product_Roadmap.md)
- [Release Plans](../planning/Release_Plans.md)
diff --git a/docs/adult_swim.md b/docs/adult_swim.md
index 7756fff6..37305172 100644
--- a/docs/adult_swim.md
+++ b/docs/adult_swim.md
@@ -3,11 +3,12 @@
# 🏊 Adult Swim: Deep End Memory Pool Opportunities
-*"No floaties allowed - this is where we optimize HARD"*
+_"No floaties allowed - this is where we optimize HARD"_
## Memory Pool Opportunities Discovered During Migration
### 1. Edge Creation Pool (edge.c)
+
```c
/* Current: Every edge creation allocates */
int gm_edge_create(...) {
@@ -17,10 +18,12 @@ int gm_edge_create(...) {
// - Often created in batches (augment operations)
}
```
-**Pool Design**: Pre-allocate 1000 edge structs, reuse via free list
-**Expected Win**: 10x faster edge creation in bulk operations
+
+__Pool Design__: Pre-allocate 1000 edge structs, reuse via free list
+__Expected Win__: 10x faster edge creation in bulk operations
### 2. String Interning for Paths (edge.c)
+
```c
/* Current: Paths copied into every edge */
safe_string_copy(edge->src_path, src_path, GM_PATH_MAX);
@@ -30,10 +33,12 @@ safe_string_copy(edge->tgt_path, tgt_path, GM_PATH_MAX);
// "src/main.c" might be in 100+ edges
// "refs/heads/main" appears everywhere
```
-**Pool Design**: Hash table of interned strings, edges store pointers
-**Expected Win**: 80% memory reduction, faster string comparisons
+
+__Pool Design__: Hash table of interned strings, edges store pointers
+__Expected Win__: 80% memory reduction, faster string comparisons
### 3. Temporary Buffer Pool (edge.c)
+
```c
/* Current: Format buffer allocated by caller */
int gm_edge_format(const gm_edge_t *edge, char *buffer, size_t len);
@@ -42,10 +47,12 @@ int gm_edge_format(const gm_edge_t *edge, char *buffer, size_t len);
// Avoid repeated stack allocations
// Reuse buffers for formatting operations
```
-**Pool Design**: Per-thread circular buffer pool
-**Expected Win**: Zero allocation for transient strings
+
+__Pool Design__: Per-thread circular buffer pool
+__Expected Win__: Zero allocation for transient strings
### 4. SHA Pool (implicit in edge.c)
+
```c
/* Current: SHA arrays in every edge */
uint8_t src_sha[GM_SHA1_SIZE];
@@ -54,10 +61,12 @@ uint8_t tgt_sha[GM_SHA1_SIZE];
/* Observation: Same SHAs repeated across edges */
// If file has 50 relationships, SHA copied 50 times
```
-**Pool Design**: SHA interning table, edges store indices
-**Expected Win**: 20-byte SHA → 4-byte index
+
+__Pool Design__: SHA interning table, edges store indices
+__Expected Win__: 20-byte SHA → 4-byte index
### 5. ULID Generation Pool (edge.c)
+
```c
/* Current: ULID generated per edge */
gm_ulid_generate(edge->ulid);
@@ -65,16 +74,17 @@ gm_ulid_generate(edge->ulid);
/* Observation: ULIDs generated in sequence */
// Could pre-generate batch during idle time
```
-**Pool Design**: Background ULID generator with ring buffer
-**Expected Win**: Amortize timestamp/random costs
+
+__Pool Design__: Background ULID generator with ring buffer
+__Expected Win__: Amortize timestamp/random costs
## Implementation Priority
-1. **String Interning** - Biggest memory win, simplest to implement
-2. **Edge Object Pool** - High frequency allocation point
-3. **SHA Deduplication** - Significant memory savings
-4. **Buffer Pools** - Eliminate transient allocations
-5. **ULID Pregenerator** - Nice-to-have optimization
+1. __String Interning__ - Biggest memory win, simplest to implement
+2. __Edge Object Pool__ - High frequency allocation point
+3. __SHA Deduplication__ - Significant memory savings
+4. __Buffer Pools__ - Eliminate transient allocations
+5. __ULID Pregenerator__ - Nice-to-have optimization
## Architecture Notes
@@ -86,6 +96,7 @@ gm_ulid_generate(edge->ulid);
## Memory Budget Targets
For a repository with 100k edges:
+
- Current: ~50MB heap allocation
- With pools: ~10MB heap allocation
- Cache efficiency: 5x improvement
@@ -93,4 +104,4 @@ For a repository with 100k edges:
---
-*"Come to the deep end... the water's fine!"* 🏊♂️
\ No newline at end of file
+_"Come to the deep end... the water's fine!"_ 🏊♂️
diff --git a/docs/api/gitmind-api-reference.md b/docs/api/gitmind-api-reference.md
index 07e2bc99..abcf4cd8 100644
--- a/docs/api/gitmind-api-reference.md
+++ b/docs/api/gitmind-api-reference.md
@@ -73,11 +73,13 @@ gm_context_t* gm_create_context(void);
Creates a new git-mind context. All operations require a context.
-**Returns:**
+__Returns:__
+
- Valid pointer on success
- NULL on failure (out of memory)
-**Example:**
+__Example:__
+
```c
gm_context_t* ctx = gm_create_context();
if (!ctx) {
@@ -94,10 +96,12 @@ void gm_destroy_context(gm_context_t* ctx);
Frees a context and all associated resources.
-**Parameters:**
+__Parameters:__
+
- `ctx` - Context to destroy (can be NULL)
-**Example:**
+__Example:__
+
```c
gm_destroy_context(ctx);
ctx = NULL; // Good practice
@@ -111,11 +115,13 @@ void gm_set_output_mode(gm_context_t* ctx, gm_output_mode_t mode);
Sets the output mode for operations.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `mode` - Output mode (silent, verbose, or porcelain)
-**Example:**
+__Example:__
+
```c
gm_set_output_mode(ctx, GM_OUTPUT_VERBOSE); // Enable detailed output
```
@@ -130,16 +136,19 @@ int gm_init(gm_context_t* ctx);
Initializes git-mind in the current repository by creating the orphan ref `refs/gitmind/graph`.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
-**Returns:**
+__Returns:__
+
- `GM_OK` - Successfully initialized
- `GM_ERR_NOT_REPO` - Not in a Git repository
- `GM_ERR_ALREADY_EXISTS` - Already initialized
- `GM_ERR_GIT` - Git operation failed
-**Example:**
+__Example:__
+
```c
int ret = gm_init(ctx);
if (ret == GM_ERR_ALREADY_EXISTS) {
@@ -160,26 +169,30 @@ int gm_link_create(gm_context_t* ctx, const char* source,
Creates a semantic link between two files.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `source` - Path to source file (must exist)
- `target` - Path to target file (must exist)
- `type` - Relationship type (e.g., "implements", "references", "tests")
-**Returns:**
+__Returns:__
+
- `GM_OK` - Link created successfully
- `GM_ERR_NOT_REPO` - Not initialized
- `GM_ERR_NOT_FOUND` - Source or target file not found
- `GM_ERR_INVALID_ARG` - Invalid path or type
- `GM_ERR_GIT` - Git operation failed
-**Notes:**
+__Notes:__
+
- Files must exist in the working directory
- Paths must be relative (no absolute paths)
- Type is case-insensitive and normalized internally
- Creates a CBOR edge in the Git object database
-**Example:**
+__Example:__
+
```c
int ret = gm_link_create(ctx, "src/main.c", "docs/api.md", "implements");
if (ret != GM_OK) {
@@ -196,24 +209,28 @@ int gm_link_list(gm_context_t* ctx, gm_link_set_t** out_set,
Lists links, optionally filtered by source and/or target.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `out_set` - Output parameter for the link set (must be freed)
- `filter_source` - Optional source filter (NULL for all)
- `filter_target` - Optional target filter (NULL for all)
-**Returns:**
+__Returns:__
+
- `GM_OK` - Success (even if no links found)
- `GM_ERR_NOT_REPO` - Not initialized
- `GM_ERR_MEMORY` - Memory allocation failed
- `GM_ERR_GIT` - Git operation failed
-**Notes:**
+__Notes:__
+
- Tombstoned links (negative confidence) are automatically filtered
- Caller must free the link set with `gm_link_set_free()`
- Empty repository returns empty set, not an error
-**Example:**
+__Example:__
+
```c
gm_link_set_t* links = NULL;
@@ -245,24 +262,28 @@ int gm_link_unlink(gm_context_t* ctx, const char* source, const char* target);
Removes a link between two files by creating a tombstone.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `source` - Source file path
- `target` - Target file path
-**Returns:**
+__Returns:__
+
- `GM_OK` - Link removed (tombstone created)
- `GM_ERR_NOT_REPO` - Not initialized
- `GM_ERR_NOT_FOUND` - Link doesn't exist
- `GM_ERR_GIT` - Git operation failed
-**Notes:**
+__Notes:__
+
- Creates a tombstone edge with confidence = -1.0
- Original edge is preserved for history
- Link will no longer appear in listings
- Can be "resurrected" by creating a new positive edge
-**Example:**
+__Example:__
+
```c
int ret = gm_link_unlink(ctx, "README.md", "docs/setup.md");
if (ret == GM_ERR_NOT_FOUND) {
@@ -285,31 +306,36 @@ int gm_traverse(gm_context_t* ctx, const char* start_file, int depth,
Traverses the link graph from a starting point using breadth-first search.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `start_file` - Starting file for traversal
- `depth` - Maximum depth (0 = use default of 3, max = 10)
- `callback` - Function called for each discovered link (can be NULL)
- `userdata` - Passed to callback
-**Returns:**
+__Returns:__
+
- `GM_OK` - Traversal completed
- `GM_ERR_NOT_REPO` - Not initialized
- `GM_ERR_INVALID_ARG` - Invalid arguments or depth > 10
- `GM_ERR_MEMORY` - Memory allocation failed
-**Callback Parameters:**
+__Callback Parameters:__
+
- `link` - The discovered link
- `level` - Depth level (1 = direct link, 2 = second level, etc.)
- `userdata` - User-provided data
-**Notes:**
+__Notes:__
+
- Uses breadth-first search with cycle detection
- Visits each node at most once
- Tombstoned links are automatically skipped
- Callback is not called for the starting node
-**Example:**
+__Example:__
+
```c
void print_tree(const gm_link_t* link, int level, void* userdata) {
for (int i = 0; i < level; i++) {
@@ -331,15 +357,18 @@ int gm_get_status(gm_context_t* ctx, int* out_total_links);
Gets repository status information.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `out_total_links` - Output parameter for total link count (can be NULL)
-**Returns:**
+__Returns:__
+
- `GM_OK` - Success
- `GM_ERR_NOT_REPO` - Not initialized
-**Example:**
+__Example:__
+
```c
int total_links = 0;
if (gm_get_status(ctx, &total_links) == GM_OK) {
@@ -355,21 +384,25 @@ int gm_check(gm_context_t* ctx, int fix);
Checks repository integrity and finds broken links.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
- `fix` - If non-zero, attempt to fix issues (not fully implemented)
-**Returns:**
+__Returns:__
+
- `GM_OK` - No issues found
- `GM_ERR_NOT_REPO` - Not initialized
- Other - Number of issues found
-**Notes:**
+__Notes:__
+
- Identifies links to non-existent files
- Fix mode is not fully implemented in current version
- Reports issues based on output mode setting
-**Example:**
+__Example:__
+
```c
gm_set_output_mode(ctx, GM_OUTPUT_VERBOSE);
int issues = gm_check(ctx, 0);
@@ -388,18 +421,22 @@ const char* gm_last_error(gm_context_t* ctx);
Gets the last error message as a human-readable string.
-**Parameters:**
+__Parameters:__
+
- `ctx` - The context
-**Returns:**
+__Returns:__
+
- Error message string (never NULL)
- "Unknown error" if no context
-**Notes:**
+__Notes:__
+
- String is owned by context, do not free
- Valid until next operation on context
-**Example:**
+__Example:__
+
```c
if (gm_init(ctx) != GM_OK) {
fprintf(stderr, "Error: %s\n", gm_last_error(ctx));
@@ -416,7 +453,8 @@ gm_link_set_t* gm_link_set_new(void);
Creates a new empty link set.
-**Returns:**
+__Returns:__
+
- Valid pointer on success
- NULL on memory allocation failure
@@ -428,7 +466,8 @@ void gm_link_set_free(gm_link_set_t* set);
Frees a link set and all its links.
-**Parameters:**
+__Parameters:__
+
- `set` - Link set to free (can be NULL)
### gm_link_set_add
@@ -439,11 +478,13 @@ int gm_link_set_add(gm_link_set_t* set, const gm_link_t* link);
Adds a link to a link set.
-**Parameters:**
+__Parameters:__
+
- `set` - The link set
- `link` - Link to add (copied)
-**Returns:**
+__Returns:__
+
- `GM_OK` - Added successfully
- `GM_ERR_MEMORY` - Memory allocation failed
@@ -484,17 +525,17 @@ typedef struct gm_backend_ops {
### Available Backends
-1. **libgit2** - Production backend using libgit2
-2. **test** - Mock backend for unit testing
+1. __libgit2__ - Production backend using libgit2
+2. __test__ - Mock backend for unit testing
## Best Practices
-1. **Always check return values** - Every function can fail
-2. **Free resources** - Use `gm_link_set_free()` and `gm_destroy_context()`
-3. **Use filters wisely** - Filter at query time, not after
-4. **Handle tombstones** - Unlinked items won't appear in lists
-5. **Respect depth limits** - Traverse depth is capped at 10
-6. **Use appropriate output modes** - Verbose for humans, porcelain for scripts
+1. __Always check return values__ - Every function can fail
+2. __Free resources__ - Use `gm_link_set_free()` and `gm_destroy_context()`
+3. __Use filters wisely__ - Filter at query time, not after
+4. __Handle tombstones__ - Unlinked items won't appear in lists
+5. __Respect depth limits__ - Traverse depth is capped at 10
+6. __Use appropriate output modes__ - Verbose for humans, porcelain for scripts
## Thread Safety
@@ -515,4 +556,4 @@ const char* gm_version_string(void); // Returns "0.1.0"
---
-*For implementation details and architecture, see [Architecture Overview](../architecture/README.md)*
\ No newline at end of file
+_For implementation details and architecture, see [Architecture Overview](../architecture/README.md)_
diff --git a/docs/architecture/MIGRATION_PHILOSOPHY.md b/docs/architecture/MIGRATION_PHILOSOPHY.md
index bac5cb19..91173eb3 100644
--- a/docs/architecture/MIGRATION_PHILOSOPHY.md
+++ b/docs/architecture/MIGRATION_PHILOSOPHY.md
@@ -4,6 +4,7 @@
# Migration Philosophy: From Chaos to Excellence
Table of Contents
+
- [The Two-Phase Approach](#the-two-phase-approach)
- [The Rationale](#the-rationale)
@@ -11,15 +12,17 @@ Table of Contents
### 🔥 Phase 1: PEDANTIC PURGE (During Migration)
-**Goal**: Achieve ABSOLUTE ZERO warnings on migrated code.
+__Goal__: Achieve ABSOLUTE ZERO warnings on migrated code.
+
+__Why__:
-**Why**:
- Forces us to understand every line
- Breaks bad habits completely
- Creates muscle memory for quality
- Proves it CAN be done
-**Rules**:
+__Rules__:
+
- ✅ Every `i` → `_i__`
- ✅ Every `memcpy` → `gm_memcpy`
- ✅ Every function ≤ 25 lines
@@ -27,19 +30,21 @@ Table of Contents
- ✅ Every magic number → constant
- ✅ Every warning → FIXED
-**Motto**: "If clang-tidy sees it, we fix it!"
+__Motto__: "If clang-tidy sees it, we fix it!"
### 🌱 Phase 2: SUSTAINABLE EXCELLENCE (Post-Migration)
-**Goal**: Maintain quality without stifling innovation.
+__Goal__: Maintain quality without stifling innovation.
+
+__Why__:
-**Why**:
- Pedantic mode is exhausting long-term
- Focus on REAL issues that matter
- Allow pragmatic trade-offs
- Encourage contribution
-**Rules**:
+__Rules__:
+
- ✅ No buffer overflows
- ✅ No NULL pointer disasters
- ✅ No security vulnerabilities
@@ -47,25 +52,28 @@ Table of Contents
- ⚠️ Style issues → warnings only
- 💡 Complexity → measure, don't mandate
-**Motto**: "Would Linus flame us for this?"
+__Motto__: "Would Linus flame us for this?"
## The Rationale
-### During Migration We're STRICT Because:
-1. **Clean slate mentality** - Do it right while we're touching it
-2. **Learning experience** - See what "perfect" looks like
-3. **Prove it's possible** - No excuses, it CAN be clean
-4. **Set the bar high** - Start from excellence
+### During Migration We're STRICT Because
+
+1. __Clean slate mentality__ - Do it right while we're touching it
+2. __Learning experience__ - See what "perfect" looks like
+3. __Prove it's possible__ - No excuses, it CAN be clean
+4. __Set the bar high__ - Start from excellence
-### After Migration We RELAX Because:
-1. **Sustainable pace** - Can't maintain pedantic mode forever
-2. **Real bugs matter** - Focus on actual problems
-3. **Innovation friendly** - Let people experiment
-4. **Pragmatic quality** - Good enough IS good enough
+### After Migration We RELAX Because
+
+1. __Sustainable pace__ - Can't maintain pedantic mode forever
+2. __Real bugs matter__ - Focus on actual problems
+3. __Innovation friendly__ - Let people experiment
+4. __Pragmatic quality__ - Good enough IS good enough
## Examples
### Migration Mode (Phase 1)
+
```c
/* REJECTED - variable name too short */
for (int i = 0; i < count; i++) { }
@@ -75,6 +83,7 @@ for (int index = 0; index < count; index++) { }
```
### Sustainable Mode (Phase 2)
+
```c
/* ACCEPTED - Linus uses 'i' in loops too */
for (int i = 0; i < count; i++) { }
@@ -86,22 +95,24 @@ strcpy(dest, src); /* NO! Real security issue */
## Test Strategy Matches Philosophy
### Migration Tests (What We Built)
+
- `test_edge_quality.c` - STRICT structure checks
- `test_edge_clang_tidy.sh` - ZERO warnings enforced
### Sustainable Tests (What We'll Use Long-term)
+
- `test_edge_quality_v2.c` - Safety and principles
- `check_edge_health.sh` - Health score, not pass/fail
## The Promise
-**During Migration**: We'll endure the pain of perfection.
-**After Migration**: We'll maintain excellence pragmatically.
+__During Migration__: We'll endure the pain of perfection.
+__After Migration__: We'll maintain excellence pragmatically.
-**Result**: Code that's both HIGH QUALITY and MAINTAINABLE!
+__Result__: Code that's both HIGH QUALITY and MAINTAINABLE!
---
-*"Perfection is achieved not when there is nothing more to add,
-but when there is nothing left to take away...
-except during migration, where we're pedantic AF!"* 😄
+_"Perfection is achieved not when there is nothing more to add,
+but when there is nothing left to take away...
+except during migration, where we're pedantic AF!"_ 😄
diff --git a/docs/architecture/MODULAR_RESTRUCTURE_PLAN.md b/docs/architecture/MODULAR_RESTRUCTURE_PLAN.md
index 46fcef91..8bf6abf4 100644
--- a/docs/architecture/MODULAR_RESTRUCTURE_PLAN.md
+++ b/docs/architecture/MODULAR_RESTRUCTURE_PLAN.md
@@ -4,16 +4,19 @@
# Modular Architecture Restructure Plan
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Goals](#goals)
- [Plan](#plan)
- [Milestones](#milestones)
- [Compatibility](#compatibility)
+
## Executive Summary
Transform git-mind from a monolithic CLI application into a modular, library-first architecture with a true single-header core library and clean separation of concerns.
-**Key Goals:**
+__Key Goals:__
+
1. Create a single-header `gitmind.h` core library
2. Fix 11,000+ code quality issues during migration
3. Enable multiple frontends (CLI, MCP, Web)
@@ -22,14 +25,16 @@ Transform git-mind from a monolithic CLI application into a modular, library-fir
## Current Problems
### 1. Architecture Issues
-- **No clear separation** between core logic and UI
-- **Not a single-header library** despite original goal (9+ headers)
-- **Tight coupling** between components
-- **Difficult to embed** in other applications
+
+- __No clear separation__ between core logic and UI
+- __Not a single-header library__ despite original goal (9+ headers)
+- __Tight coupling__ between components
+- __Difficult to embed__ in other applications
### 2. Code Quality Issues (NOW RESOLVED FOR CORE)
-- **Started with 11,951 clang-tidy warnings**
-- **Now: ZERO warnings in migrated core modules**
+
+- __Started with 11,951 clang-tidy warnings__
+- __Now: ZERO warnings in migrated core modules__
- Achieved through systematic migration:
- Functions refactored to reasonable size
- All magic numbers → named constants
@@ -38,6 +43,7 @@ Transform git-mind from a monolithic CLI application into a modular, library-fir
- Self-contained headers
### 3. Maintenance Challenges
+
- Hard to test components in isolation
- Changes ripple across entire codebase
- Can't reuse core logic in new contexts
@@ -76,6 +82,7 @@ git-mind/
## Core Library Design
### What Goes in Core
+
- Edge/link data structures
- CBOR encoding/decoding
- Attribution system
@@ -83,6 +90,7 @@ git-mind/
- Pure algorithms (no I/O)
### What Stays Out
+
- Command-line parsing
- Output formatting
- Network operations
@@ -90,6 +98,7 @@ git-mind/
- UI of any kind
### Single Header Strategy
+
```c
/* gitmind.h - Single header git-mind library */
#ifndef GITMIND_H
@@ -110,7 +119,9 @@ git-mind/
## Migration Strategy ("3 Birds, 1 Stone")
### Phase 1: Core Extraction (Weeks 1-4)
+
For each module (edge, cbor, attribution):
+
1. Move to `core/src/`
2. Fix ALL clang-tidy warnings
3. Split functions exceeding size limits
@@ -119,12 +130,14 @@ For each module (edge, cbor, attribution):
6. Update migration tracker
### Phase 2: Application Separation (Weeks 5-6)
+
1. Move CLI to `apps/cli/`
2. Update to use only `gitmind.h`
3. Fix quality issues in CLI code
4. Separate UI logic from business logic
### Phase 3: New Applications (Week 7+)
+
1. Create `apps/mcp/` with clean implementation
2. All new code follows strict quality standards
3. Share only through core library
@@ -132,6 +145,7 @@ For each module (edge, cbor, attribution):
## Quality Enforcement
### Regression Prevention
+
```bash
# quality/snapshots/{file}.quality
function-size: 0 warnings (was: 23)
@@ -140,11 +154,13 @@ naming: 0 warnings (was: 67)
```
### Automated Testing
+
- Generate regression tests for each fix
- Quality snapshots prevent backsliding
- CI enforces improvements
### Progressive Standards
+
```yaml
# .github/workflows/quality-gate.yml
- core/**: Must pass strict .clang-tidy
@@ -157,6 +173,7 @@ naming: 0 warnings (was: 67)
Taking `edge.c` as an example:
### Before Migration
+
```c
// src/edge/edge.c
void gm_edge_create(...) {
@@ -166,6 +183,7 @@ void gm_edge_create(...) {
```
### After Migration
+
```c
// core/src/edge/edge.c
#define MAX_EDGE_TYPE 10
@@ -185,16 +203,19 @@ int gm_edge_create(...) {
## Success Metrics
### Week 1
+
- [ ] Core directory structure created
- [ ] First module (edge) migrated and clean
- [ ] Automated quality tracking in place
### Week 4
+
- [ ] All core modules migrated
- [ ] Single header amalgamation working
- [ ] 50% reduction in total warnings
### Week 8
+
- [ ] CLI fully separated and using core
- [ ] MCP server implemented
- [ ] 100% of core code passes strict quality checks
@@ -202,36 +223,38 @@ int gm_edge_create(...) {
## Backwards Compatibility
### For Users
+
- `git-mind` CLI commands unchanged
- Git hooks continue working
- Existing `.gitmind/` data compatible
### For Developers
+
- Old `#include "gitmind/*.h"` → `#include "gitmind.h"`
- Function signatures preserved
- Behavior unchanged (only quality improved)
## Open Questions
-1. **Version during migration?**
+1. __Version during migration?__
- Stay on 0.x to indicate instability?
- Jump to 2.0 when complete?
-2. **Breaking changes acceptable?**
+2. __Breaking changes acceptable?__
- Can we rename poorly-named functions?
- Standardize return codes?
-3. **Migration timeline?**
+3. __Migration timeline?__
- Aggressive 8-week plan realistic?
- Do incrementally over months?
## Next Steps
-1. **Create proof-of-concept**: Migrate edge module
-2. **Set up quality automation**: Snapshot and tracking tools
-3. **Get feedback**: Open discussion on approach
-4. **Begin systematic migration**: Module by module
+1. __Create proof-of-concept__: Migrate edge module
+2. __Set up quality automation__: Snapshot and tracking tools
+3. __Get feedback__: Open discussion on approach
+4. __Begin systematic migration__: Module by module
---
-*This is a living document. Updates will be tracked in git history.*
+_This is a living document. Updates will be tracked in git history._
diff --git a/docs/architecture/README.md b/docs/architecture/README.md
index 653dc6fc..1197813b 100644
--- a/docs/architecture/README.md
+++ b/docs/architecture/README.md
@@ -4,6 +4,7 @@
# git-mind Architecture Documentation
Table of Contents
+
- [Core Systems](#core-systems)
- [Design Decisions](#design-decisions)
- [Diagrams](#diagrams)
@@ -14,28 +15,34 @@ This directory contains the technical architecture documentation for git-mind.
## Core Systems
### [Attribution System](attribution-system.md)
+
The foundation for human-AI collaboration. Tracks who created each edge (human or AI) and enables filtered views, review workflows, and consensus building.
- [Integration Guide](attribution-integration-guide.md) - How to add attribution to existing code
- [Use Cases](attribution-use-cases.md) - Real-world collaboration scenarios
### [Journal System](journal-architecture-pivot.md)
+
Git-native storage using commits as the source of truth for semantic edges.
### [Bitmap Cache](bitmap-cache-design.md)
+
High-performance cache layer using Roaring Bitmaps for O(log N) query performance.
### [AUGMENTS System](augments-system.md)
+
Automatic tracking of file evolution through Git commits.
## Design Decisions
### [Journal Architecture Pivot](journal-architecture-pivot.md)
+
The radical rebuild that transformed git-mind from orphan refs to journal commits.
## Diagrams
Key architectural diagrams are embedded throughout the documentation using Mermaid:
+
- Attribution system class hierarchy
- Data flow sequences
- Human-AI collaboration workflows
@@ -43,13 +50,13 @@ Key architectural diagrams are embedded throughout the documentation using Merma
## Integration Points
-1. **CLI Commands** - How commands interact with core systems
-2. **Web UI** - Real-time updates via WebSocket
-3. **MCP Integration** - AI tools for semantic graph manipulation
-4. **Git Hooks** - Automatic edge creation on commits
+1. __CLI Commands__ - How commands interact with core systems
+2. __Web UI__ - Real-time updates via WebSocket
+3. __MCP Integration__ - AI tools for semantic graph manipulation
+4. __Git Hooks__ - Automatic edge creation on commits
---
-*"Architecture is about the important stuff. Whatever that is."* - Ralph Johnson
+_"Architecture is about the important stuff. Whatever that is."_ - Ralph Johnson
In git-mind, the important stuff is enabling humans and AI to build understanding together.
diff --git a/docs/architecture/System_Architecture.md b/docs/architecture/System_Architecture.md
index a6d19b48..bf6bf46d 100644
--- a/docs/architecture/System_Architecture.md
+++ b/docs/architecture/System_Architecture.md
@@ -1,6 +1,7 @@
# System Architecture
Table of Contents
+
- [Executive Summary](#executive-summary)
- [High-Level Design](#high-level-design)
- [Components and Technology Stack](#components-and-technology-stack)
@@ -8,6 +9,7 @@ Table of Contents
- [Scaling Strategy and Performance Targets](#scaling-strategy-and-performance-targets)
## Executive Summary
+
git-mind is a Git-native semantic graph system. The journal (source of truth) stores edges as CBOR payloads under branch-scoped refs; the cache (performance layer) stores Roaring Bitmaps for fast queries. Semantics are first-class names; stable numeric IDs are derived solely for cache keys. See also: [Journal Pivot](journal-architecture-pivot.md), [Bitmap Cache Design](bitmap-cache-design.md), and [ADR 0001](../adr/0001-first-class-semantics.md).
## High-Level Design
@@ -28,6 +30,7 @@ graph TD
```
## Components and Technology Stack
+
- Language: C (C23), Meson + Ninja
- Git Integration: libgit2
- Serialization: CBOR (custom lightweight impl under `core/src/cbor/`)
@@ -38,6 +41,7 @@ graph TD
## Data Flows and Storage
Edge Append
+
```mermaid
sequenceDiagram
participant U as User
@@ -51,6 +55,7 @@ sequenceDiagram
```
Query via Cache
+
```mermaid
flowchart LR
N[type/lane names] --> H[derive IDs]
@@ -60,10 +65,12 @@ flowchart LR
```
Storage Layout
+
- Journal: `refs/gitmind/edges/` parent-linked commits with CBOR message
- Cache: `refs/gitmind/cache//` bitmap trees; never merged
## Scaling Strategy and Performance Targets
+
- Scaling knobs
- Shard caches by leading byte(s) of IDs
- Incremental rebuilds based on journal tip
diff --git a/docs/architecture/attribution-integration-guide.md b/docs/architecture/attribution-integration-guide.md
index 53c5664f..e092e32e 100644
--- a/docs/architecture/attribution-integration-guide.md
+++ b/docs/architecture/attribution-integration-guide.md
@@ -4,6 +4,7 @@
# Attribution System Integration Guide
Table of Contents
+
- [Quick Start](#quick-start)
- [For CLI Commands](#for-cli-commands)
- [For Filtering](#for-filtering)
@@ -47,7 +48,7 @@ if (gm_filter_match(&filter, &edge)) {
### 1. Update `git mind link` Command
-**File**: `src/cli/link.c`
+__File__: `src/cli/link.c`
```c
// Add to link_cmd():
@@ -69,9 +70,10 @@ gm_edge_attributed_encode_cbor(&edge, buffer, &len);
### 2. Update `git mind list` Command
-**File**: `src/cli/list.c`
+__File__: `src/cli/list.c`
Add new options:
+
```c
--source Filter by source
--min-confidence Minimum confidence
@@ -81,6 +83,7 @@ Add new options:
```
Example implementation:
+
```c
// Parse filter options
gm_filter_t filter;
@@ -103,7 +106,7 @@ while (read_next_edge(&edge)) {
### 3. Update Journal Reader
-**File**: `src/journal/reader.c`
+__File__: `src/journal/reader.c`
```c
// Update edge callback to handle attributed edges
@@ -128,7 +131,7 @@ int process_edge(const uint8_t *cbor_data, size_t len, void *userdata) {
### 4. Update Journal Writer
-**File**: `src/journal/writer.c`
+__File__: `src/journal/writer.c`
```c
// Use attributed edges
@@ -147,7 +150,7 @@ int gm_journal_append_attributed(gm_context_t *ctx,
### 5. Add Review Command (New)
-**File**: `src/cli/review.c`
+__File__: `src/cli/review.c`
```c
int review_cmd(int argc, char **argv) {
@@ -164,12 +167,14 @@ int review_cmd(int argc, char **argv) {
## Environment Variables
### For Humans (Default)
+
```bash
# Nothing needed - defaults to human
git mind link src/main.c docs/api.md --type implements
```
### For AI Systems
+
```bash
# Claude via MCP
export GIT_MIND_SOURCE=claude
@@ -182,6 +187,7 @@ export GIT_MIND_AUTHOR=gpt4@openai
```
### For System/Hooks
+
```bash
# AUGMENTS hook
export GIT_MIND_SOURCE=system
@@ -191,11 +197,13 @@ export GIT_MIND_AUTHOR=augments@git-mind
## Display Formatting
### Basic Display
+
```
src/main.c ──implements──> docs/design.md
```
### With Attribution
+
```
src/main.c ──implements──> docs/design.md [human: user@example.com]
src/parser.c ──depends_on──> lib/ast.c [ai: claude@anthropic, conf: 0.85]
@@ -203,6 +211,7 @@ src/test.c ──tests──> src/main.c [consensus: human+ai]
```
### Pending Review Display
+
```
PENDING: src/auth.c ──likely_depends_on──> config/oauth.json
Source: claude@anthropic
@@ -214,6 +223,7 @@ PENDING: src/auth.c ──likely_depends_on──> config/oauth.json
## Testing
### Unit Tests
+
```c
void test_attribution_filtering() {
gm_edge_attributed_t human_edge = {0};
@@ -232,6 +242,7 @@ void test_attribution_filtering() {
```
### Integration Tests
+
```bash
# Test human edges
git mind link src/a.c src/b.c --type depends_on
@@ -248,16 +259,19 @@ git mind list --source ai --min-confidence 0.6
## Migration Path
### Phase 1: Soft Launch
+
- Attribution system available but optional
- Legacy edges get default attribution
- New edges use attribution if environment set
### Phase 2: Default On
+
- All new edges get attribution
- Add migration command for old edges
- Web UI shows attribution
### Phase 3: Full Integration
+
- MCP tools create attributed edges
- Review workflow enabled
- Analytics on human vs AI contributions
@@ -265,6 +279,7 @@ git mind list --source ai --min-confidence 0.6
## Common Patterns
### AI Batch Analysis
+
```python
# Claude analyzing codebase
for file_pair in analyze_coupling():
@@ -283,6 +298,7 @@ for file_pair in analyze_coupling():
```
### Human Review Session
+
```bash
# Review all pending
git mind review --pending
@@ -295,6 +311,7 @@ git mind review --pending --type coupled_with --reject-all
```
### Consensus Building
+
```sql
-- Find where human and AI agree
SELECT * FROM edges e1
@@ -306,24 +323,30 @@ WHERE e1.source_type = 'human'
## Troubleshooting
-### Edge Not Showing Up?
+### Edge Not Showing Up
+
Check filters:
+
```bash
git mind list --source all --no-filter
```
-### Attribution Not Set?
+### Attribution Not Set
+
Check environment:
+
```bash
env | grep GIT_MIND
```
-### Legacy Edges?
+### Legacy Edges
+
Migrate them:
+
```bash
git mind migrate --add-attribution
```
---
-*With attribution integrated, git-mind becomes a platform for human-AI collaboration, not just a tool for storing connections.*
+_With attribution integrated, git-mind becomes a platform for human-AI collaboration, not just a tool for storing connections._
diff --git a/docs/architecture/attribution-system.md b/docs/architecture/attribution-system.md
index ebab0f98..5c584e50 100644
--- a/docs/architecture/attribution-system.md
+++ b/docs/architecture/attribution-system.md
@@ -4,6 +4,7 @@
# Attribution System Architecture
Table of Contents
+
- [Overview](#overview)
- [Quickstart: Lanes & Filters](#quickstart-lanes--filters)
- [Core Concepts](#core-concepts)
@@ -13,6 +14,7 @@ Table of Contents
- [Filter System](#filter-system)
- [Usage Patterns](#usage-patterns)
- [Collaboration Workflows](#collaboration-workflows)
+
## Overview
The attribution system is the foundation for human-AI collaboration in git-mind. It tracks who created each semantic edge (human or AI), enabling filtered views, collaborative workflows, and consensus building.
@@ -30,6 +32,7 @@ Use lanes and attribution to separate AI suggestions from human‑curated edges,
- `--source human` limits to human‑created edges
- CLI filters (examples)
+
```bash
# Review AI suggestions
git mind list --lane suggested --source ai
@@ -42,10 +45,12 @@ git mind list --lane suggested --source ai --type implements --from notes/idea.m
```
Promotion workflow (concept)
+
- Write suggestions to `suggested` (source=ai), review them, then promote selected edges to `verified`.
- Promotion can be implemented via a CLI helper or the MCP service (see PRD: Co‑Thought MCP) to re‑append the edge in the new lane while preserving attribution.
Privacy note
+
- Co‑thought remains local by default. Keep tools and MCP local‑only and avoid sending repo content off‑machine unless you explicitly export it.
## Core Concepts
@@ -194,6 +199,7 @@ Array(13) [
### Backward Compatibility
The decoder can handle legacy 8-element arrays by setting defaults:
+
- `source_type` = GM_SOURCE_HUMAN
- `author` = "legacy@unknown"
- `session_id` = ""
@@ -287,14 +293,17 @@ graph LR
## Implementation Files
### Headers
+
- `include/gitmind/attribution.h` - Main attribution types and functions
### Source
+
- `src/attribution/attribution.c` - Core attribution functions
- `src/attribution/cbor.c` - CBOR encoding/decoding for attributed edges
- `src/attribution/attribution.md` - Implementation notes
### Integration Points
+
- `src/cli/link.c` - Set attribution when creating edges
- `src/cli/list.c` - Filter edges by attribution
- `src/journal/writer.c` - Store attributed edges
@@ -336,37 +345,41 @@ int gm_edge_attributed_decode_cbor(const uint8_t *buffer, size_t len,
## Future Enhancements
-1. **Bulk Review Interface** - Review multiple AI suggestions at once
-2. **Attribution Analytics** - Show contribution breakdown by source
-3. **Trust Scores** - Track AI accuracy over time
-4. **Team Attribution** - Multiple humans with individual attribution
-5. **Audit Trail** - Full history of edge modifications
+1. __Bulk Review Interface__ - Review multiple AI suggestions at once
+2. __Attribution Analytics__ - Show contribution breakdown by source
+3. __Trust Scores__ - Track AI accuracy over time
+4. __Team Attribution__ - Multiple humans with individual attribution
+5. __Audit Trail__ - Full history of edge modifications
## Design Rationale
-### Why Source Attribution?
+### Why Source Attribution
Human and AI contributors think differently:
-- **Humans**: High intent, sporadic, certain
-- **AIs**: Pattern-based, systematic, probabilistic
+
+- __Humans__: High intent, sporadic, certain
+- __AIs__: Pattern-based, systematic, probabilistic
By tracking source, we can:
+
- Show appropriate views for different users
- Build trust in AI suggestions gradually
- Maintain human intent while benefiting from AI insights
-### Why Lanes?
+### Why Lanes
Different workflows need different edge sets:
+
- Architecture documentation vs implementation details
- Test coverage analysis vs refactoring plans
- AI exploration vs human curation
Lanes let these coexist without interference.
-### Why Review Flags?
+### Why Review Flags
AI suggestions need human oversight:
+
- Not all patterns are meaningful
- Context matters more than correlation
- Human judgment validates AI insights
@@ -375,4 +388,4 @@ The review system creates a feedback loop that improves both human understanding
---
-*The attribution system transforms git-mind from a single-user tool into a collaborative platform where humans and AI build understanding together.*
+_The attribution system transforms git-mind from a single-user tool into a collaborative platform where humans and AI build understanding together._
diff --git a/docs/architecture/attribution-use-cases.md b/docs/architecture/attribution-use-cases.md
index 3104ee08..471a31f8 100644
--- a/docs/architecture/attribution-use-cases.md
+++ b/docs/architecture/attribution-use-cases.md
@@ -4,6 +4,7 @@
# Attribution System Use Cases
Table of Contents
+
- [Use Case 1: AI-Assisted Code Review](#use-case-1-ai-assisted-code-review)
Real-world scenarios showing how the attribution system enables human-AI collaboration.
@@ -11,6 +12,7 @@ Real-world scenarios showing how the attribution system enables human-AI collabo
## Use Case 1: AI-Assisted Code Review
### Scenario
+
A developer asks Claude to analyze their codebase for hidden dependencies.
### Flow
@@ -43,6 +45,7 @@ sequenceDiagram
```
### Result
+
- Developer sees AI discoveries visually
- Can accept obvious ones (high confidence)
- Investigate surprising ones
@@ -51,9 +54,11 @@ sequenceDiagram
## Use Case 2: Onboarding New Developer
### Scenario
+
New team member needs to understand a complex codebase.
### Human-Only View
+
```bash
# New dev starts with human-curated edges
git mind list --source human --from src/core/*
@@ -64,6 +69,7 @@ src/core/engine.c ──depends_on──> config/engine.yaml [human]
```
### AI-Enhanced View
+
```bash
# Then explores AI insights
git mind list --source ai --min-confidence 0.8
@@ -74,7 +80,9 @@ src/core/engine.c ──performance_critical──> benchmarks/engine.c [ai: 0.8
```
### Combined Understanding
+
The new developer gets:
+
- Explicit architectural knowledge (human)
- Hidden patterns and relationships (AI)
- Confidence levels to gauge reliability
@@ -82,9 +90,11 @@ The new developer gets:
## Use Case 3: Architecture Documentation
### Scenario
+
Team lead wants to document system architecture with AI help.
### Step 1: Human Documents Key Relationships
+
```bash
# Team lead creates high-level edges
git mind link src/api/* docs/api-design.md --type implements
@@ -92,6 +102,7 @@ git mind link src/auth/* security/auth-spec.md --type implements
```
### Step 2: AI Fills in Details
+
```python
# Claude analyzes and adds detailed edges
for module in ['api', 'auth', 'core']:
@@ -100,6 +111,7 @@ for module in ['api', 'auth', 'core']:
```
### Step 3: Collaborative Review
+
```bash
# Team reviews AI additions
git mind explore
@@ -112,7 +124,9 @@ git mind explore
```
### Result
+
Complete architecture map combining:
+
- Human strategic vision
- AI detailed analysis
- Team consensus
@@ -120,9 +134,11 @@ Complete architecture map combining:
## Use Case 4: Test Coverage Analysis
### Scenario
+
QA engineer + Claude ensure complete test coverage.
### Lane-Based Organization
+
```bash
# Human creates testing lane
export GIT_MIND_LANE=testing
@@ -135,6 +151,7 @@ export GIT_MIND_LANE=testing
```
### Coverage Report
+
```bash
git mind coverage --lane testing
@@ -154,9 +171,11 @@ Missing coverage (AI confidence):
## Use Case 5: Refactoring Planning
### Scenario
+
Team plans major refactoring with AI assistance.
### Identify Tightly Coupled Code
+
```sql
-- Claude's analysis query
SELECT source, target, COUNT(*) as change_frequency
@@ -167,6 +186,7 @@ HAVING change_frequency > 10
```
### Create Refactoring Edges
+
```bash
# Claude creates edges for coupled files
export GIT_MIND_SOURCE=claude
@@ -177,6 +197,7 @@ git mind link src/old_api.c src/old_impl.c \
```
### Human Validates
+
```bash
# Developer reviews coupling
git mind list --lane refactor --pending
@@ -192,25 +213,29 @@ git mind link src/old_api.c docs/refactor-plan.md \
## Use Case 6: Knowledge Persistence
### Scenario
+
Senior developer leaving, needs to transfer knowledge.
### Collaborative Knowledge Capture
-1. **Senior Dev Session**
+1. __Senior Dev Session__
+
```bash
# Senior dev explains critical paths
git mind link src/payment.c docs/payment-critical.md \
--type critical_knowledge
```
-2. **Claude Interviews**
+2. __Claude Interviews__
+
```
Claude: "I see payment.c is marked critical. What makes it critical?"
Senior: "It handles all transaction validation..."
Claude: *creates detailed edges based on explanation*
```
-3. **Knowledge Graph**
+3. __Knowledge Graph__
+
```mermaid
graph LR
A[payment.c] -->|critical_knowledge| B[payment-critical.md]
@@ -225,9 +250,11 @@ graph LR
## Use Case 7: Continuous AI Learning
### Scenario
+
Claude improves recommendations over time.
### Feedback Loop
+
```mermaid
flowchart LR
A[Claude Suggests] -->|flags=PENDING| B[Human Reviews]
@@ -241,6 +268,7 @@ flowchart LR
```
### Metrics Dashboard
+
```bash
git mind ai-stats --source claude
@@ -260,9 +288,11 @@ Improving areas:
## Use Case 8: Merge Conflict for Ideas
### Scenario
+
Two developers + AI have different views on architecture.
### The Conflict
+
```yaml
Alice's View:
src/cache.c --depends_on--> src/memory.c
@@ -279,6 +309,7 @@ Claude's Analysis:
```
### Resolution Process
+
```bash
git mind conflicts --resolve
@@ -293,7 +324,9 @@ Opening discussion thread...
```
### Outcome
+
Team discusses, reaches consensus:
+
- Cache is loosely coupled (Claude was right)
- Add interface documentation
- Both devs learned from AI perspective
@@ -301,23 +334,29 @@ Team discusses, reaches consensus:
## Best Practices
### 1. Start with Human Edges
+
Build foundation with explicit knowledge first.
### 2. Let AI Explore
+
Use AI for discovery, not just validation.
### 3. Review Regularly
+
Don't let pending suggestions pile up.
### 4. Use Lanes
+
Organize different types of analysis.
### 5. Track Metrics
+
Monitor AI accuracy to build trust.
### 6. Document Decisions
+
When rejecting AI suggestions, document why.
---
-*These use cases show how attribution transforms git-mind from a single-user tool into a platform for collective intelligence.*
+_These use cases show how attribution transforms git-mind from a single-user tool into a platform for collective intelligence._
diff --git a/docs/architecture/augments-system.md b/docs/architecture/augments-system.md
index 2edbbf7f..069205ec 100644
--- a/docs/architecture/augments-system.md
+++ b/docs/architecture/augments-system.md
@@ -1,6 +1,7 @@
# AUGMENTS System Architecture
Table of Contents
+
- [Overview](#overview)
- [Core Concepts](#core-concepts)
- [How It Works](#how-it-works)
@@ -12,13 +13,14 @@ The AUGMENTS system automatically tracks file evolution by creating edges betwee
## Core Concepts
-### What is an AUGMENTS Edge?
+### What is an AUGMENTS Edge
An AUGMENTS edge represents the evolution of content:
-- **Source**: The old blob SHA (previous version)
-- **Target**: The new blob SHA (current version)
-- **Semantics**: "old content AUGMENTS INTO new content"
-- **Automatic**: Created by post-commit hook, never manually
+
+- __Source__: The old blob SHA (previous version)
+- __Target__: The new blob SHA (current version)
+- __Semantics__: "old content AUGMENTS INTO new content"
+- __Automatic__: Created by post-commit hook, never manually
```mermaid
graph LR
@@ -180,10 +182,10 @@ int post_commit_hook(int argc, char **argv);
### Performance Considerations
-1. **Lookback Window**: Only scan last 100-200 edges
-2. **Skip Large Commits**: If >50 files changed, skip
-3. **Timeout**: Abort if taking >500ms
-4. **Async Option**: Queue for background processing
+1. __Lookback Window__: Only scan last 100-200 edges
+2. __Skip Large Commits__: If >50 files changed, skip
+3. __Timeout__: Abort if taking >500ms
+4. __Async Option__: Queue for background processing
### Edge Cases
@@ -247,16 +249,19 @@ IMPLEMENTS: README.md@v1 -> API.md # Before augmentation
## Testing Strategy
### Unit Tests
+
- Blob SHA extraction from commits
- Edge search algorithms
- AUGMENTS edge creation
### Integration Tests
+
- Post-commit hook triggering
- Multi-file commits
- Edge case handling
### E2E Tests
+
```bash
# Test full workflow
1. Create initial edge
@@ -268,10 +273,10 @@ IMPLEMENTS: README.md@v1 -> API.md # Before augmentation
## Future Enhancements
-1. **Rename Detection**: Use git's rename detection to track moved files
-2. **Bulk Import**: Create AUGMENTS for existing git history
-3. **Visualization**: Show evolution graph in web UI
-4. **Metrics**: Track how often files change together
+1. __Rename Detection__: Use git's rename detection to track moved files
+2. __Bulk Import__: Create AUGMENTS for existing git history
+3. __Visualization__: Show evolution graph in web UI
+4. __Metrics__: Track how often files change together
## Summary
diff --git a/docs/architecture/bitmap-cache-design.md b/docs/architecture/bitmap-cache-design.md
index b6603490..cfcbb085 100644
--- a/docs/architecture/bitmap-cache-design.md
+++ b/docs/architecture/bitmap-cache-design.md
@@ -1,15 +1,17 @@
# Bitmap Cache Design 🦁⚡
+
## High-Performance Query Layer for git-mind
Table of Contents
+
- [Overview](#overview)
- [Storage Design](#storage-design)
- [Cache Structure](#cache-structure)
- [Query Path](#overview)
-**Date**: June 2025
-**Status**: IN PROGRESS
-**Goal**: O(log N) queries on millions of edges
+__Date__: June 2025
+__Status__: IN PROGRESS
+__Goal__: O(log N) queries on millions of edges
---
@@ -40,15 +42,18 @@ graph TD
## Storage Design
### Cache Structure
+
```
refs/gitmind/cache//
```
Each cache commit contains:
-- **Tree**: Organized by SHA prefix for sharding
-- **Message**: Cache metadata (CBOR encoded)
+
+- __Tree__: Organized by SHA prefix for sharding
+- __Message__: Cache metadata (CBOR encoded)
### Tree Layout
+
```
/00/
/00a1b2c3.forward # Edges where src starts with 00a1b2c3
@@ -65,6 +70,7 @@ Each cache commit contains:
### Bitmap Format
Each `.forward` and `.reverse` file contains:
+
```
[Header (16 bytes)]
- Magic: "GMCACHE\0" (8 bytes)
@@ -78,6 +84,7 @@ Each `.forward` and `.reverse` file contains:
## Edge ID Assignment
Edge IDs are assigned sequentially as we walk the journal:
+
1. Start at 0 for the oldest edge
2. Increment for each edge encountered
3. Store mapping in memory during cache build
@@ -86,6 +93,7 @@ Edge IDs are assigned sequentially as we walk the journal:
## Cache Metadata
Stored in commit message (CBOR):
+
```c
typedef struct {
uint64_t journal_tip; // Last processed journal commit
@@ -99,6 +107,7 @@ typedef struct {
## Query Algorithm
### Forward Query (fanout from source)
+
```c
edges = gm_query_fanout(src_sha) {
// 1. Check cache
@@ -122,6 +131,7 @@ edges = gm_query_fanout(src_sha) {
## Build Algorithm
### Incremental Build
+
```c
gm_cache_rebuild() {
// 1. Load existing cache metadata
@@ -163,22 +173,26 @@ gm_cache_rebuild() {
## Performance Characteristics
### Space Complexity
+
- Roaring bitmaps: ~2-4 bytes per edge (compressed)
- Sharding: 256 directories × 2 files each
- Total: ~200-400MB for 100M edges
### Time Complexity
+
- Query: O(log N) bitmap operations
- Build: O(E) where E = new edges since last cache
- Rebuild: O(E_total) for full rebuild
### Memory Usage
+
- Build: O(unique_shas) for hashmaps
- Query: O(1) - only load needed bitmaps
## Cache Invalidation
Cache becomes stale when:
+
1. New edges added to journal
2. Branch pointer moves
3. Journal rewritten (rebase/amend)
@@ -187,19 +201,22 @@ Solution: Compare journal tip with cache metadata
## Implementation Notes
-### Why Roaring Bitmaps?
+### Why Roaring Bitmaps
+
- Excellent compression (2-4 bytes/edge)
- Fast operations (unions, intersections)
- Proven in production (Lucene, Druid, ClickHouse)
- Single header C library
-### Why SHA Prefix Sharding?
+### Why SHA Prefix Sharding
+
- Limits directory size (4096 files max)
- Enables parallel builds
- Natural load distribution
- Easy to increase shard depth later
-### Why Not Use Git's Pack Format?
+### Why Not Use Git's Pack Format
+
- Pack format optimized for object storage
- We need set operations, not object retrieval
- Roaring gives us bitmap-specific optimizations
@@ -207,11 +224,11 @@ Solution: Compare journal tip with cache metadata
## Future Optimizations
-1. **Bloom Filters**: Quick negative lookups
-2. **Hot/Cold Split**: Recent edges in separate cache
-3. **Compression**: Zstd on bitmap files
-4. **Parallel Build**: Shard processing in threads
-5. **Distributed Cache**: Share via CI artifacts
+1. __Bloom Filters__: Quick negative lookups
+2. __Hot/Cold Split__: Recent edges in separate cache
+3. __Compression__: Zstd on bitmap files
+4. __Parallel Build__: Shard processing in threads
+5. __Distributed Cache__: Share via CI artifacts
---
@@ -224,4 +241,4 @@ Solution: Compare journal tip with cache metadata
---
-*"Make it work, make it right, make it ROAR!"* 🦁
+_"Make it work, make it right, make it ROAR!"_ 🦁
diff --git a/docs/architecture/journal-architecture-pivot.md b/docs/architecture/journal-architecture-pivot.md
index cec8c5a0..08628325 100644
--- a/docs/architecture/journal-architecture-pivot.md
+++ b/docs/architecture/journal-architecture-pivot.md
@@ -1,7 +1,9 @@
# Project: No Tux Given 🐧⚡
+
## The git-mind Final Architecture
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Core Design Principles](#core-design-principles)
- [The Two-Layer Architecture](#the-two-layer-architecture)
@@ -14,15 +16,15 @@ Table of Contents
- [The Payoff](#the-payoff)
- [Next Steps](#next-steps)
-**Date**: June 16, 2025
-**Status**: BLANK SLATE - LET'S GO HARD
-**Motto**: "Keep code in files, truth in commits, speed in shards"
+__Date__: June 16, 2025
+__Status__: BLANK SLATE - LET'S GO HARD
+__Motto__: "Keep code in files, truth in commits, speed in shards"
---
## Executive Summary
-After 3 days of exploration, we're abandoning the Holy Grail orphan ref approach and pivoting to the **Ultimate Design**: edge-journal commits with branch-aware graphs that actually work with Git's model.
+After 3 days of exploration, we're abandoning the Holy Grail orphan ref approach and pivoting to the __Ultimate Design__: edge-journal commits with branch-aware graphs that actually work with Git's model.
```mermaid
graph TD
@@ -45,32 +47,36 @@ graph TD
## Core Design Principles
-1. **Immutable content is the only true identity** - Every file version (blob SHA) is its own node
-2. **Branches are parallel universes** - Links live in the branch that created them
-3. **The graph is first-class history** - You can `git bisect` semantics like code
-4. **Push/pull must Just Work™** - No exotic refs, no special servers
-5. **Hot queries are O(log N)** - AI can answer in <10ms with 100M edges
+1. __Immutable content is the only true identity__ - Every file version (blob SHA) is its own node
+2. __Branches are parallel universes__ - Links live in the branch that created them
+3. __The graph is first-class history__ - You can `git bisect` semantics like code
+4. __Push/pull must Just Work™__ - No exotic refs, no special servers
+5. __Hot queries are O(log N)__ - AI can answer in <10ms with 100M edges
---
## The Two-Layer Architecture
### Layer 0: Edge Journal (Source of Truth)
+
```
refs/gitmind/edges/main # Commits with CBOR edge data
refs/gitmind/edges/feature-x # Per-branch isolation
```
Each edge operation creates a commit:
-- **Empty tree** (storage efficient)
-- **CBOR message** containing edge data
-- **Parent chain** preserves order
-- **Standard ref** that GitHub accepts
+
+- __Empty tree__ (storage efficient)
+- __CBOR message__ containing edge data
+- __Parent chain__ preserves order
+- __Standard ref__ that GitHub accepts
### Layer 1: Speed Cache (Optional)
+
```
refs/gitmind/cache/main///bitmaps
```
+
- Roaring bitmaps for O(log N) queries
- Rebuilt from journal anytime
- Never pushed (local optimization)
@@ -81,6 +87,7 @@ refs/gitmind/cache/main///bitmaps
## Implementation Details
### Edge Structure
+
```c
typedef struct {
uint8_t src_sha[20]; // Source blob SHA-1
@@ -94,6 +101,7 @@ typedef struct {
```
### CBOR Encoding
+
```
[
src_sha, // 20 bytes
@@ -108,6 +116,7 @@ Total: ~100-300 bytes per edge
```
### Creating an Edge
+
```c
int gm_link_create(repo, source_path, target_path, rel_type) {
// 1. Resolve paths to blob SHAs
@@ -141,6 +150,7 @@ int gm_link_create(repo, source_path, target_path, rel_type) {
## Solving the Hard Problems
### 1. File Identity Crisis ✅
+
```yaml
# Edge tracks both content AND path
edge:
@@ -152,6 +162,7 @@ AUGMENTS: old_blob -> new_blob
```
### 2. Branch Awareness ✅
+
```bash
# Each branch has its own journal
git checkout main
@@ -165,6 +176,7 @@ git merge feature # Journals merge too!
```
### 3. Push/Pull ✅
+
```bash
# Just push both refs!
git push origin main refs/gitmind/edges/main
@@ -177,6 +189,7 @@ git push # Everything goes!
```
### 4. Performance ✅
+
- Journal scan: O(new commits) not O(all edges)
- Cache lookup: O(log N) via roaring bitmaps
- Rebuild cache: O(edges) but async/incremental
@@ -186,18 +199,21 @@ git push # Everything goes!
## Migration Plan (Fresh Start)
### Weekend 1: Core Journal
+
- [ ] Edge CBOR encoder/decoder
- [ ] Journal commit writer
- [ ] Journal reader/scanner
- [ ] Basic CLI (link, list via scan)
### Weekend 2: Identity & Branches
+
- [ ] Blob SHA resolution from paths
- [ ] Branch-aware ref naming
- [ ] AUGMENTS edge for edits
- [ ] Post-commit hook
### Weekend 3: Speed Layer
+
- [ ] Roaring bitmap integration
- [ ] Cache builder (incremental)
- [ ] Fast queries via cache
@@ -206,6 +222,7 @@ git push # Everything goes!
---
## Code Structure
+
```
src/
├── core/
@@ -228,18 +245,21 @@ src/
## Why This Wins
### vs Holy Grail (Current)
+
- ✅ Pushable to any Git host
- ✅ Branch-aware by design
- ✅ No orphan ref magic
- ✅ Works with Git workflows
### vs Simple Files
+
- ✅ No merge conflicts
- ✅ Immutable history
- ✅ Content-addressable
- ✅ O(log N) performance
### vs Everything Else
+
- ✅ Pure Git (commits are native)
- ✅ Simple implementation (~2K LOC)
- ✅ Future-proof (can always rebuild)
@@ -262,6 +282,7 @@ src/
## The Payoff
In 3 weekends, we'll have:
+
- 🚀 Branch-aware semantic graphs
- 📤 GitHub/GitLab/Bitbucket compatible
- ⚡ Millisecond queries on millions of edges
@@ -277,18 +298,18 @@ Just pure, elegant, Git-native knowledge graphs.
## Next Steps
-1. **Archive current code** as `holy-grail-attempt`
-2. **Start fresh** with journal-based design
-3. **Build MVP** in one weekend
-4. **Test push/pull** on GitHub
-5. **Celebrate** 🍺
+1. __Archive current code__ as `holy-grail-attempt`
+2. __Start fresh__ with journal-based design
+3. __Build MVP__ in one weekend
+4. __Test push/pull__ on GitHub
+5. __Celebrate__ 🍺
---
-*"Sometimes the best code is the code you throw away."*
+_"Sometimes the best code is the code you throw away."_
Let's build something that actually works with Git, not against it.
-**Project: No Tux Given** - Because we're not asking permission, we're shipping excellence.
+__Project: No Tux Given__ - Because we're not asking permission, we're shipping excellence.
🐧⚡ Let's. Fucking. Go.
diff --git a/docs/architecture/tombstone-visual.md b/docs/architecture/tombstone-visual.md
index cb22883e..d9144a66 100644
--- a/docs/architecture/tombstone-visual.md
+++ b/docs/architecture/tombstone-visual.md
@@ -1,6 +1,7 @@
# Visual Guide: How Tombstones Work
Table of Contents
+
- [The Problem: Traditional Deletion](#the-problem-traditional-deletion)
- [The Solution: Tombstones](#the-solution-tombstones)
@@ -185,11 +186,12 @@ sequenceDiagram
## Summary
-Tombstones are edges with **negative confidence** that:
+Tombstones are edges with __negative confidence__ that:
+
- 📜 Preserve complete history
- 👻 Make links "disappear" from user view
- 🔄 Allow clean distributed merges
- ♻️ Enable future resurrection
- 🔍 Provide audit trails
-The user sees the **behavior** (link gone) without knowing the **implementation** (tombstone edge)!
+The user sees the __behavior__ (link gone) without knowing the __implementation__ (tombstone edge)!
diff --git a/docs/audits/vision-drift.md b/docs/audits/vision-drift.md
index 2b21d779..7d2d140f 100644
--- a/docs/audits/vision-drift.md
+++ b/docs/audits/vision-drift.md
@@ -1,6 +1,7 @@
# Vision Alignment / Drift Audit
Table of Contents
+
- Executive Summary
- Scope and Method
- Findings by Document
@@ -8,61 +9,75 @@ Table of Contents
- Remediation Plan
## Executive Summary
+
The vision is: version your thoughts — a serverless, distributed, forkable thought‑graph for humans and AI built on Git. The core path is journal (edges‑as‑commits), cache (fast queries), names‑as‑truth, attribution/lanes, AUGMENTS, and optional advice; co‑thought (MCP + review lanes) is optional.
Overall, top‑level docs now mostly align. Two documents showed notable drift (ARCHITECTURE.md, MIGRATION_STATUS.md). Minor terminology and status misalignments remain in a few places.
## Scope and Method
-- Reviewed: README.md, ARCHITECTURE.md, docs/architecture/*, PRD/ADR, planning/*, requirements, risk, deployment, AGENTS.md, MIGRATION_STATUS.md.
+
+- Reviewed: README.md, ARCHITECTURE.md, docs/architecture/_, PRD/ADR, planning/_, requirements, risk, deployment, AGENTS.md, MIGRATION_STATUS.md.
- Compared to current direction as captured in README + Product Roadmap.
## Findings by Document
1) README.md — Aligned
+
- Vision captured (“version your thoughts”, co‑thought, serverless DB). Quickstart includes code+notes examples. Added stub outputs.
- Action: None.
2) ARCHITECTURE.md — Was drifted, UPDATED
+
- Outdated progress metrics and dependency claims (said “only libgit2”); now corrected to reflect CRoaring and current focus. Status table modernized.
- Action: Keep as index; avoid duplicating status numbers.
3) docs/architecture/* — Partially aligned
+
- Journal/Cache docs align; attribution docs match filters/lanes direction.
- Action: Add a short note on “names‑as‑truth” to attribution docs in a future pass.
4) PRD (Semantics) and ADR 0001 — Aligned
+
- Names‑as‑truth, advice via hybrid CRDT, cache IDs derived at runtime.
- Action: Specify final hash choice (FNV‑1a‑64 vs SipHash) and add test vectors (later).
5) Planning (Product_Roadmap, Release_Plans, Milestones, Sprint_Plans) — UPDATED
+
- Now includes optional Co‑Thought MCP and review lanes as post‑core.
- Action: Track MCP tasks behind a feature flag in issues.
6) Requirements — UPDATED
+
- Added optional co‑thought requirements (attribution filters, lanes, MCP, promote/demote).
- Action: None.
7) Risk Register — UPDATED
+
- Added AI precision/privacy risks; mitigations noted (lanes, local‑only MCP).
- Action: None.
8) Deployment — Aligned
+
- CI gates, packaging, rollback, monitoring; no server dependencies.
- Action: Add MCP runbook when implemented.
9) AGENTS.md — UPDATED
+
- Added vision snapshot and docs linter guidance; removed internal Neo4j guidance.
- Action: Keep co‑thought/MCP marked as optional.
10) MIGRATION_STATUS.md — Drifted
+
- Contradictory statuses (Attribution both “Complete” and “Next Action”).
- Action: Replace ad‑hoc metrics with links to planning milestones; simplify to “what’s next”.
## Summary of Drift
+
- Primary drift: stale status/progress numbers; dependency claims (libgit2‑only) ignoring cache dependency; unclear optionality of MCP.
- Secondary drift: terminology duplication and minor inconsistencies across architecture subpages.
## Remediation Plan
+
- Short term (this PR):
- ARCHITECTURE.md modernized (done).
- Planning/requirements/risk updated with co‑thought optional track (done).
diff --git a/docs/charter/Project_Charter.md b/docs/charter/Project_Charter.md
index cdb66ec2..4345e0c1 100644
--- a/docs/charter/Project_Charter.md
+++ b/docs/charter/Project_Charter.md
@@ -1,15 +1,18 @@
# Project Charter
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Goals and Objectives](#goals-and-objectives)
- [Stakeholders and RACI](#stakeholders-and-raci)
- [Success Metrics](#success-metrics)
## Executive Summary
+
Build a Git-native semantic graph tool that is deterministic, fast, and friendly to a solo maintainer workflow. Favor small, pauseable increments and auditable decisions. Related: [Product Roadmap](../planning/Product_Roadmap.md).
## Goals and Objectives
+
- G1: First-class semantics (names-as-truth) with deterministic IDs for cache keys
- G2: Fast local queries using Roaring Bitmaps; rebuildable, branch-scoped caches
- G3: Optional advice system with deterministic merges; minimal application
@@ -25,6 +28,7 @@ Build a Git-native semantic graph tool that is deterministic, fast, and friendly
Notes: One-person operation. “Consulted” and “Informed” reflect future-self/change logs and commit messages.
## Success Metrics
+
- S1: Query median < 10ms on 100k-edge sample; P95 < 50ms
- S2: clang-tidy zero warnings in cache/journal/cbor modules
- S3: Deterministic hash vectors green across platforms
diff --git a/docs/cli/README.md b/docs/cli/README.md
index 45f36773..8a092aed 100644
--- a/docs/cli/README.md
+++ b/docs/cli/README.md
@@ -3,9 +3,10 @@
# git-mind Command Reference
-> *"The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."* - Mufasa
+> _"The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."_ - Mufasa
Table of Contents
+
- [Overview](#overview)
- [Core Commands](#core-commands)
- [Performance Commands](#performance-commands)
@@ -19,41 +20,50 @@ Welcome to the git-mind command reference. These guides will teach you not just
## Core Commands
### [git-mind](gitmind.md)
+
The main command and your entry into semantic version control. Start here to understand the vision.
### [git-mind link](gitmind-link.md)
+
Create meaningful connections between files. This is the heart of git-mind - where understanding becomes permanent.
### [git-mind list](gitmind-list.md)
+
Query and explore your semantic web. Your window into the relationships that bind your code.
## Performance Commands
### [git-mind cache-rebuild](gitmind-cache-rebuild.md)
+
Harness the power of Roaring Bitmaps for lightning-fast queries. When your semantic web grows large, this command keeps it fast.
## Evolution Commands
### [git-mind install-hooks](gitmind-install-hooks.md)
+
Install automatic evolution tracking. Let git-mind follow your files as they change and grow.
## Coming Soon
### git-mind traverse
+
Follow connection paths through your codebase. Like `git log` but for relationships.
### git-mind unlink
+
Remove connections gracefully with tombstone edges.
### git-mind status
+
See statistics about your semantic graph.
### git-mind gc
+
Compress old journal entries for long-lived repositories.
## The Philosophy
-*"Look beyond what you see."* - Rafiki
+_"Look beyond what you see."_ - Rafiki
These aren't just commands. They're tools for encoding understanding. Every link you create, every query you run, adds to the collective wisdom of your codebase.
@@ -68,10 +78,10 @@ Traditional documentation tells you what the code does. Semantic version control
## Remember
-*"The past can hurt. But the way I see it, you can either run from it or learn from it."*
+_"The past can hurt. But the way I see it, you can either run from it or learn from it."_
Every command in git-mind helps you learn from your code's past and build a better future.
---
-*Welcome to the Pride Lands of semantic version control.*
+_Welcome to the Pride Lands of semantic version control._
diff --git a/docs/cli/combined_markdown.md b/docs/cli/combined_markdown.md
index dde760bc..7feb5d1f 100644
--- a/docs/cli/combined_markdown.md
+++ b/docs/cli/combined_markdown.md
@@ -4,9 +4,10 @@
# git-mind Command Reference
-> *"The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."* - Mufasa
+> _"The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."_ - Mufasa
Table of Contents
+
- [Overview](#overview)
- [Core Commands](#core-commands)
- [Performance Commands](#performance-commands)
@@ -20,41 +21,50 @@ Welcome to the git-mind command reference. These guides will teach you not just
## Core Commands
### [git-mind](gitmind.md)
+
The main command and your entry into semantic version control. Start here to understand the vision.
### [git-mind link](gitmind-link.md)
+
Create meaningful connections between files. This is the heart of git-mind - where understanding becomes permanent.
### [git-mind list](gitmind-list.md)
+
Query and explore your semantic web. Your window into the relationships that bind your code.
## Performance Commands
### [git-mind cache-rebuild](gitmind-cache-rebuild.md)
+
Harness the power of Roaring Bitmaps for lightning-fast queries. When your semantic web grows large, this command keeps it fast.
## Evolution Commands
### [git-mind install-hooks](gitmind-install-hooks.md)
+
Install automatic evolution tracking. Let git-mind follow your files as they change and grow.
## Coming Soon
### git-mind traverse
+
Follow connection paths through your codebase. Like `git log` but for relationships.
### git-mind unlink
+
Remove connections gracefully with tombstone edges.
### git-mind status
+
See statistics about your semantic graph.
### git-mind gc
+
Compress old journal entries for long-lived repositories.
## The Philosophy
-*"Look beyond what you see."* - Rafiki
+_"Look beyond what you see."_ - Rafiki
These aren't just commands. They're tools for encoding understanding. Every link you create, every query you run, adds to the collective wisdom of your codebase.
@@ -69,14 +79,13 @@ Traditional documentation tells you what the code does. Semantic version control
## Remember
-*"The past can hurt. But the way I see it, you can either run from it or learn from it."*
+_"The past can hurt. But the way I see it, you can either run from it or learn from it."_
Every command in git-mind helps you learn from your code's past and build a better future.
---
-*Welcome to the Pride Lands of semantic version control.*
-
+_Welcome to the Pride Lands of semantic version control._
# gitmind-cache-rebuild.md
@@ -84,9 +93,10 @@ Every command in git-mind helps you learn from your code's past and build a bett
# git-mind cache-rebuild
-> *"Look at the stars. The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."* - Mufasa
+> _"Look at the stars. The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."_ - Mufasa
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -112,16 +122,20 @@ This command rebuilds the performance cache for the current (or specified) branc
## HOW IT WORKS
### The Journal: Source of Truth
+
Your semantic links live as CBOR-encoded Git commits in `refs/gitmind/edges/`. This is the permanent record - like the stars themselves.
### The Cache: Speed of Light
+
The cache creates two Roaring Bitmap indices:
-- **Forward index**: source SHA → edge IDs (who depends on this?)
-- **Reverse index**: target SHA → edge IDs (what does this depend on?)
+
+- __Forward index__: source SHA → edge IDs (who depends on this?)
+- __Reverse index__: target SHA → edge IDs (what does this depend on?)
These are stored as Git tree objects under `refs/gitmind/cache/`, sharded into 256 buckets using the first byte of each SHA.
### The Magic: Roaring Bitmaps
+
Roaring Bitmaps compress sequences of integers with supernatural efficiency. A million edges might compress to just kilobytes. It's the same technology that powers modern databases and search engines.
## OPTIONS
@@ -138,6 +152,7 @@ Roaring Bitmaps compress sequences of integers with supernatural efficiency. A m
## EXAMPLES
### Basic rebuild for current branch
+
```bash
$ git mind cache-rebuild
Rebuilding cache for branch 'main'...
@@ -147,6 +162,7 @@ Cache rebuilt successfully!
```
### Rebuild after heavy development
+
```bash
$ git mind link src/parser.c docs/parsing.md --type implements
$ git mind link src/lexer.c src/parser.c --type feeds
@@ -157,6 +173,7 @@ Cache updated incrementally!
```
### Force rebuild when things seem wrong
+
```bash
$ git mind cache-rebuild --force --verbose
Force rebuilding cache for branch 'main'...
@@ -173,29 +190,32 @@ Cache rebuilt: refs/gitmind/cache/main -> 3a7f9b2
## PERFORMANCE
Without cache (journal scan):
+
- 1,000 edges: ~50ms
- 10,000 edges: ~500ms
- 100,000 edges: ~5000ms
With cache (bitmap query):
+
- 1,000 edges: ~2ms
- 10,000 edges: ~5ms
- 100,000 edges: ~10ms
-*"It's the Circle of Life, and it moves us all!"* The cache makes git-mind scale to repositories with millions of semantic connections.
+_"It's the Circle of Life, and it moves us all!"_ The cache makes git-mind scale to repositories with millions of semantic connections.
## WHEN TO REBUILD
The cache automatically detects when it's stale by comparing the journal tip with the cached tip. However, you should manually rebuild when:
-1. **After bulk operations** - Added many links at once
-2. **After merging branches** - Cache is branch-specific
-3. **Performance degrades** - Queries feel slow
-4. **Something seems wrong** - Use `--force` to ensure consistency
+1. __After bulk operations__ - Added many links at once
+2. __After merging branches__ - Cache is branch-specific
+3. __Performance degrades__ - Queries feel slow
+4. __Something seems wrong__ - Use `--force` to ensure consistency
## TECHNICAL DETAILS
### Storage Format
+
```
refs/gitmind/cache/main
└── tree
@@ -211,12 +231,15 @@ refs/gitmind/cache/main
```
### Bitmap Serialization
+
Each bitmap file contains:
+
1. 16-byte header with magic number and version
2. Compressed Roaring Bitmap data
3. CRC32 checksum
### Incremental Updates
+
The cache tracks the last processed journal commit. On rebuild, it only processes new commits, making updates extremely fast.
## DIAGNOSTICS
@@ -224,9 +247,10 @@ The cache tracks the last processed journal commit. On rebuild, it only processe
The cache-rebuild command returns 0 on success, non-zero on failure.
Common issues:
-- **"Permission denied"**: Ensure you have write access to `.git/`
-- **"No journal found"**: Create some links first with `git mind link`
-- **"Invalid journal format"**: Corrupted journal - seek help
+
+- __"Permission denied"__: Ensure you have write access to `.git/`
+- __"No journal found"__: Create some links first with `git mind link`
+- __"Invalid journal format"__: Corrupted journal - seek help
## SEE ALSO
@@ -236,7 +260,7 @@ Common issues:
## PHILOSOPHY
-*"Remember who you are."*
+_"Remember who you are."_
The cache is not the truth - it's a performance optimization. The journal commits are the permanent record. If the cache is ever lost or corrupted, it can always be rebuilt from the journal.
@@ -244,8 +268,7 @@ This design ensures that git-mind scales from personal note-taking to massive co
---
-*In the great Circle of Life, every query begins with a search, and every search begins with hope. The cache ensures that hope is never disappointed.*
-
+_In the great Circle of Life, every query begins with a search, and every search begins with hope. The cache ensures that hope is never disappointed._
# gitmind-install-hooks.md
@@ -253,9 +276,10 @@ This design ensures that git-mind scales from personal note-taking to massive co
# git-mind install-hooks
-> *"The past can hurt. But the way I see it, you can either run from it or learn from it."* - Rafiki
+> _"The past can hurt. But the way I see it, you can either run from it or learn from it."_ - Rafiki
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -304,6 +328,7 @@ Now when you query connections to main.c, git-mind knows to follow the AUGMENTS
## EXAMPLES
### First time installation
+
```bash
$ git mind install-hooks
Installing git-mind hooks...
@@ -314,6 +339,7 @@ Your commits will now track file evolution automatically.
```
### With existing hooks
+
```bash
$ git mind install-hooks
Found existing post-commit hook
@@ -325,6 +351,7 @@ Both your existing hook and git-mind will run after commits.
```
### Force installation
+
```bash
$ git mind install-hooks --force --no-backup
Installing git-mind hooks...
@@ -335,6 +362,7 @@ Installing git-mind hooks...
## HOW IT WORKS
### The Hook Script
+
The installed hook is a simple shell script that calls the git-mind-hook binary:
```bash
@@ -352,7 +380,9 @@ fi
```
### The Magic Moment
+
After every commit, the hook:
+
1. Gets the list of modified files
2. For each file, finds its old blob SHA (before commit)
3. Searches recent edges (last 200) for links to that blob
@@ -360,7 +390,9 @@ After every commit, the hook:
5. Updates the semantic graph silently in the background
### Performance
+
The hook is blazing fast:
+
- Typical commit: <10ms overhead
- Large commit (50+ files): <50ms overhead
- Massive refactor (500+ files): <200ms overhead
@@ -370,11 +402,13 @@ It runs asynchronously and never blocks your workflow.
## WHEN AUGMENTS HAPPEN
AUGMENTS edges are created when:
+
- You modify a file that has incoming semantic links
- You rename a file (old path AUGMENTS to new path)
- You split a file (original AUGMENTS to both pieces)
AUGMENTS edges are NOT created for:
+
- New files (no history to track)
- Deleted files (use tombstone edges instead)
- Merge commits (too complex for v1)
@@ -410,7 +444,7 @@ Your semantic links remain intact - only automatic tracking stops.
## PHILOSOPHY
-*"Oh yes, the past can hurt. But you can either run from it or learn from it."*
+_"Oh yes, the past can hurt. But you can either run from it or learn from it."_
Code evolution is natural. Files grow, split, merge, and transform. The AUGMENTS system doesn't fight this change - it embraces it. Every commit becomes a checkpoint in your code's journey.
@@ -419,7 +453,9 @@ Traditional version control tracks what changed. Semantic version control tracks
## TECHNICAL DETAILS
### Edge Format
+
AUGMENTS edges have a special format:
+
```
{
src_sha: "abc123...", // Old blob SHA
@@ -432,10 +468,13 @@ AUGMENTS edges have a special format:
```
### Search Window
+
The hook searches the last 200 edges for performance. This covers several days of typical development. Older links won't auto-update but can be manually linked.
### Conflict Resolution
+
AUGMENTS edges never conflict because they:
+
- Use ULID-based edge IDs (time-ordered, unique)
- Are append-only (no modifications)
- Are branch-specific (isolated evolution)
@@ -449,7 +488,7 @@ AUGMENTS edges never conflict because they:
## THE LESSON
-*"Change is good."* - Rafiki
+_"Change is good."_ - Rafiki
But change without memory is chaos. The AUGMENTS system ensures that every transformation is recorded, every evolution is traceable, and every connection persists through change.
@@ -457,8 +496,7 @@ Install the hooks. Let your code's journey document itself.
---
-*Asante sana, squash banana! Your semantic links now travel through time!* 🐒
-
+_Asante sana, squash banana! Your semantic links now travel through time!_ 🐒
# gitmind-link.md
@@ -466,9 +504,10 @@ Install the hooks. Let your code's journey document itself.
# git-mind link
-> *"Everything the light touches is our kingdom... But a king's time as ruler rises and falls like the sun."* - Mufasa
+> _"Everything the light touches is our kingdom... But a king's time as ruler rises and falls like the sun."_ - Mufasa
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -506,22 +545,24 @@ From this moment forward, anyone who checks out your code can discover this rela
## OPTIONS
`--type `
-: **Required.** The type of semantic relationship. Common types:
- - `implements` - Source implements design/spec in target
- - `references` - Source references or mentions target
- - `depends_on` - Source requires target to function
- - `tests` - Source tests the functionality in target
- - `documents` - Source documents how target works
- - `inspires` - Source inspired the creation of target
- - `refactors` - Source is refactored version of target
- - *...or any relationship that captures your understanding*
+: __Required.__ The type of semantic relationship. Common types:
+
+- `implements` - Source implements design/spec in target
+- `references` - Source references or mentions target
+- `depends_on` - Source requires target to function
+- `tests` - Source tests the functionality in target
+- `documents` - Source documents how target works
+- `inspires` - Source inspired the creation of target
+- `refactors` - Source is refactored version of target
+- _...or any relationship that captures your understanding_
`--confidence `
: Confidence level from 0.0 to 1.0 (default: 1.0)
- - `1.0` - Certain (default)
- - `0.8` - Highly confident
- - `0.5` - Somewhat confident
- - `0.2` - Speculative
+
+- `1.0` - Certain (default)
+- `0.8` - Highly confident
+- `0.5` - Somewhat confident
+- `0.2` - Speculative
`--note `
: Add a note explaining the connection (stored in commit message)
@@ -535,6 +576,7 @@ From this moment forward, anyone who checks out your code can discover this rela
## EXAMPLES
### Basic usage - The daily workflow
+
```bash
# Implementation tracks design
$ git mind link src/auth.c docs/auth-design.md --type implements
@@ -547,6 +589,7 @@ $ git mind link src/auth.c config/auth.yaml --type depends_on
```
### With confidence - Encoding uncertainty
+
```bash
# Human creating a confident link (confidence defaults to 1.0)
$ git mind link src/parser.c rfc/grammar.txt --type implements
@@ -562,6 +605,7 @@ $ git mind link src/algorithm.c papers/dijkstra62.pdf --type references --confid
```
### Bidirectional links - Symmetric relationships
+
```bash
# These files are peers that reference each other
$ git mind link src/client.c src/server.c --type references --bidirectional
@@ -570,6 +614,7 @@ Created edge: src/server.c ──references──> src/client.c
```
### Human-AI Collaboration - Attribution System
+
```bash
# Human creates edge (default behavior)
$ git mind link README.md src/main.c --type documents
@@ -590,14 +635,18 @@ $ git mind link old_file.c new_file.c --type augments
## HOW IT WORKS
### Git-Native Storage
+
Each link is stored as a Git commit in `refs/gitmind/edges/`. The commit contains:
+
- CBOR-encoded edge data in the commit message
- Empty tree (git's null tree: 4b825dc...)
- Author/committer from your Git config
- Timestamp of creation
### Content Addressing
+
Links connect specific versions of files using their blob SHAs:
+
```
source_sha: 8a9f3b2c... # SHA of design.md's content
target_sha: 7c4d5e6f... # SHA of parser.c's content
@@ -606,13 +655,15 @@ target_sha: 7c4d5e6f... # SHA of parser.c's content
This means links point to exact versions. When files change, the AUGMENTS system (see `git-mind-install-hooks(1)`) tracks their evolution.
### Branch Isolation
+
Links are branch-specific. Create different connections on different branches:
+
```bash
-$ git checkout -b feature/auth
-$ git mind link src/auth.c new-auth-api.md --type implements
+git checkout -b feature/auth
+git mind link src/auth.c new-auth-api.md --type implements
-$ git checkout main
-$ git mind list # Won't show the feature branch link
+git checkout main
+git mind list # Won't show the feature branch link
```
## RELATIONSHIP TYPES
@@ -620,24 +671,28 @@ $ git mind list # Won't show the feature branch link
While you can use any string as a relationship type, these conventions help maintain consistency:
### Structural Relations
+
- `implements` - Code implements a design/specification
- `depends_on` - Requires target to function correctly
- `extends` - Builds upon target's functionality
- `replaces` - Newer version replacing target
### Documentation Relations
+
- `documents` - Explains how target works
- `references` - Mentions or links to target
- `examples` - Shows usage of target
- `tutorials` - Teaches concepts in target
### Development Relations
+
- `tests` - Validates target's behavior
- `benchmarks` - Measures target's performance
- `fixes` - Resolves issues in target
- `refactors` - Restructured version of target
### Inspiration Relations
+
- `inspires` - Target inspired this implementation
- `adapts` - Modified version of target's approach
- `conflicts` - Incompatible with target
@@ -646,6 +701,7 @@ While you can use any string as a relationship type, these conventions help main
## BEST PRACTICES
### Be Specific
+
```bash
# Too vague
$ git mind link src/parser.c docs/ --type references # Which doc?
@@ -655,18 +711,22 @@ $ git mind link src/parser.c docs/parser-design.md --type implements
```
### Use Conventional Types
+
Stick to common relationship types when possible. This makes queries more powerful:
+
```bash
# Find all tests easily
$ git mind list --type tests
```
### Link at the Right Granularity
+
- Link files, not directories (unless the directory is the unit)
- Link to specific documents, not entire folders
- Link the most specific relevant files
### Document Non-Obvious Links
+
```bash
# Why does the parser depend on the logger config?
$ git mind link src/parser.c config/logger.yaml --type depends_on \
@@ -675,9 +735,10 @@ $ git mind link src/parser.c config/logger.yaml --type depends_on \
## PERMANENCE & EVOLUTION
-*"Remember who you are."*
+_"Remember who you are."_
Every link you create becomes part of your repository's permanent history. Future developers can:
+
- See what you connected and why
- Travel back to see historical connections
- Understand the evolution of architectural decisions
@@ -688,16 +749,19 @@ This is why git-mind exists: to encode not just what your code is, but what it m
Common errors and solutions:
-**"File not found"**
+__"File not found"__
+
- Ensure both source and target exist in the repository
- Use paths relative to repository root
- Check for typos in filenames
-**"Not in a git repository"**
+__"Not in a git repository"__
+
- Run from within a Git repository
- Initialize with `git init` if needed
-**"Invalid confidence value"**
+__"Invalid confidence value"__
+
- Use a float between 0.0 and 1.0
- Default is 1.0 if not specified
@@ -710,7 +774,7 @@ Common errors and solutions:
## THE PHILOSOPHY
-*"There's more to being a king than getting your way."*
+_"There's more to being a king than getting your way."_
Creating links is an act of documentation, but more than that - it's an act of teaching. Every link you create teaches future readers (including future you) about the relationships that matter.
@@ -718,8 +782,7 @@ The power isn't in the tool. It's in the understanding you encode with it.
---
-*"You are more than what you have become. Remember."* - Your semantic links remember for you.
-
+_"You are more than what you have become. Remember."_ - Your semantic links remember for you.
# gitmind-list.md
@@ -727,9 +790,10 @@ The power isn't in the tool. It's in the understanding you encode with it.
# git-mind list
-> *"Look beyond what you see."* - Rafiki
+> _"Look beyond what you see."_ - Rafiki
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -754,6 +818,7 @@ This is your window into understanding. Use it to discover dependencies, trace i
## THE POWER OF SEEING
Without git-mind:
+
```bash
# Where is this implemented?
$ grep -r "auth flow" docs/
@@ -764,6 +829,7 @@ $ # ...good luck
```
With git-mind:
+
```bash
# All connections at a glance
$ git mind list --from src/parser.c
@@ -795,10 +861,11 @@ $ git mind list
`--format `
: Output format (default: human)
- - `human` - Readable format with arrows
- - `json` - Machine-parseable JSON
- - `tsv` - Tab-separated values
- - `dot` - Graphviz DOT format
+
+- `human` - Readable format with arrows
+- `json` - Machine-parseable JSON
+- `tsv` - Tab-separated values
+- `dot` - Graphviz DOT format
`--show-sha`
: Display blob SHAs (default: hide)
@@ -830,6 +897,7 @@ $ git mind list
### Basic Queries
Show all connections:
+
```bash
$ git mind list
README.md ──references──> docs/quickstart.md
@@ -842,6 +910,7 @@ src/parser.c ──depends_on──> config/grammar.yaml
### Focused Queries
What does this file connect to?
+
```bash
$ git mind list --from src/auth.c
src/auth.c ──implements──> docs/auth-design.md
@@ -850,6 +919,7 @@ src/auth.c ──references──> lib/crypto.c
```
What connects to this file?
+
```bash
$ git mind list --to src/parser.c
tests/test_parser.c ──tests──> src/parser.c
@@ -861,6 +931,7 @@ src/compiler.c ──depends_on──> src/parser.c
### Filtered Queries
Find all test files:
+
```bash
$ git mind list --type tests
tests/test_auth.c ──tests──> src/auth.c
@@ -869,6 +940,7 @@ tests/integration/test_flow.c ──tests──> src/flow.c
```
Find uncertain connections:
+
```bash
$ git mind list --min-confidence 0.8
src/auth.c ──depends_on──> config/oauth.json [claude: claude@anthropic, conf: 0.85]
@@ -878,6 +950,7 @@ src/parser.c ──implements──> specs/grammar.md [gpt: gpt4@openai, conf: 0
### Attribution Filtering
Show only human-created edges:
+
```bash
$ git mind list --source human
README.md ──documents──> src/main.c
@@ -886,6 +959,7 @@ tests/test_auth.c ──tests──> src/auth.c
```
Show only AI-suggested edges:
+
```bash
$ git mind list --source ai
src/parser.c ──depends_on──> lib/lexer.h [claude: claude@anthropic, conf: 0.78]
@@ -893,6 +967,7 @@ src/crypto.c ──references──> papers/aes.pdf [gpt: gpt4@openai, conf: 0.9
```
Show attribution for all edges:
+
```bash
$ git mind list --show-attribution
README.md ──documents──> src/main.c [human: user@example.com]
@@ -901,6 +976,7 @@ src/test.c ──tests──> src/main.c [human: developer@team.com]
```
High-confidence AI insights only:
+
```bash
$ git mind list --source ai --min-confidence 0.9
src/crypto.c ──references──> papers/aes.pdf [gpt: gpt4@openai, conf: 0.91]
@@ -910,6 +986,7 @@ src/algorithm.c ──implements──> papers/dijkstra.pdf [claude: claude@anth
### Time Travel Queries
See historical connections:
+
```bash
# What did we understand 50 commits ago?
$ git mind list --at HEAD~50
@@ -924,6 +1001,7 @@ $ git mind list --branch feature/new-auth
### Evolution Tracking
See how files evolved:
+
```bash
$ git mind list --show-augments
src/auth.c:8a9f3b ──AUGMENTS──> src/auth.c:7c4d5e
@@ -934,6 +1012,7 @@ docs/api.md:3f2a1b ──AUGMENTS──> docs/api.md:current
### Machine-Readable Output
JSON for tooling:
+
```bash
$ git mind list --format json
{
@@ -950,19 +1029,22 @@ $ git mind list --format json
```
DOT for visualization:
+
```bash
-$ git mind list --format dot > graph.dot
-$ dot -Tpng graph.dot -o graph.png
+git mind list --format dot > graph.dot
+dot -Tpng graph.dot -o graph.png
```
## UNDERSTANDING THE OUTPUT
### Human Format (default)
+
```
────> [metadata]
```
Metadata may include:
+
- `(confidence: 0.8)` - Less than certain connections
- `(SHA: abc123)` - When --show-sha is used
- `(AUGMENTED)` - When file has evolved
@@ -983,14 +1065,15 @@ Use `--no-follow-augments` to see historical links.
The list command uses the Roaring Bitmap cache for O(log N) queries:
-- **With cache**: <10ms for 100K edges
-- **Without cache**: ~5 seconds for 100K edges
-- **Cache miss**: Automatically falls back to journal scan
-- **Stale cache**: Detects and warns (run `git mind cache-rebuild`)
+- __With cache__: <10ms for 100K edges
+- __Without cache__: ~5 seconds for 100K edges
+- __Cache miss__: Automatically falls back to journal scan
+- __Stale cache__: Detects and warns (run `git mind cache-rebuild`)
## ADVANCED PATTERNS
### Dependency Analysis
+
```bash
# What does my module depend on?
$ git mind list --from "src/mymodule/**" --type depends_on
@@ -1000,6 +1083,7 @@ $ git mind list --to config/database.yaml --type depends_on
```
### Test Coverage Discovery
+
```bash
# What files lack tests?
$ comm -23 \
@@ -1008,6 +1092,7 @@ $ comm -23 \
```
### Architecture Visualization
+
```bash
# Generate architecture diagram
$ git mind list --format dot --type implements > arch.dot
@@ -1015,6 +1100,7 @@ $ dot -Tsvg arch.dot -o architecture.svg
```
### Change Impact Analysis
+
```bash
# What might break if I change this?
$ git mind list --to src/core-api.h --type depends_on
@@ -1022,7 +1108,7 @@ $ git mind list --to src/core-api.h --type depends_on
## PHILOSOPHY
-*"The question is: Who are you?"* - Rafiki
+_"The question is: Who are you?"_ - Rafiki
Your code is more than files and functions. It's a living system of relationships, dependencies, and meanings. The `list` command doesn't just show you connections - it reveals the hidden structure of your understanding.
@@ -1033,6 +1119,7 @@ Every query is a question about your code's nature. Every result is an answer th
Returns 0 on success, non-zero on failure.
Common warnings:
+
- `Cache stale, using journal scan` - Run `git mind cache-rebuild`
- `No edges found` - No links match your query
- `Following AUGMENTS chain` - File has evolved (use --no-follow-augments for original)
@@ -1046,14 +1133,13 @@ Common warnings:
## THE LESSON
-*"Oh, the past can hurt. But the way I see it, you can either run from it or learn from it."*
+_"Oh, the past can hurt. But the way I see it, you can either run from it or learn from it."_
Every list query teaches you something about your codebase. The more you look, the more you see. The more you see, the more you understand.
---
-*"It is time."* - Time to see what connects your kingdom.
-
+_"It is time."_ - Time to see what connects your kingdom.
# gitmind.md
@@ -1061,9 +1147,10 @@ Every list query teaches you something about your codebase. The more you look, t
# git-mind
-> *"Remember who you are."* - Mufasa
+> _"Remember who you are."_ - Mufasa
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -1086,16 +1173,18 @@ In the great Circle of Development, code is written, connections form, understan
git-mind adds a semantic layer to Git, allowing you to create, query, and explore meaningful relationships between files. These connections travel through time with your code, creating a permanent record of your understanding.
-*"Everything the light touches has been connected by git-mind."*
+_"Everything the light touches has been connected by git-mind."_
## THE VISION
You're deep in a codebase. Instead of asking:
+
- "Where is this implemented?" (grep)
- "What depends on this?" (hope)
- "Where are the tests?" (find)
You ask:
+
- "Show me all implementations of this design"
- "What breaks if I change this?"
- "How has our understanding evolved?"
@@ -1113,10 +1202,10 @@ And git-mind answers, instantly, accurately, with the wisdom of everyone who cam
: Query and explore connections
`traverse [--depth N]`
-: Follow connection paths from starting point *(coming soon)*
+: Follow connection paths from starting point _(coming soon)_
`unlink `
-: Remove connection (adds tombstone) *(coming soon)*
+: Remove connection (adds tombstone) _(coming soon)_
### Management Commands
@@ -1127,10 +1216,10 @@ And git-mind answers, instantly, accurately, with the wisdom of everyone who cam
: Install Git hooks for automatic evolution tracking
`status`
-: Show semantic graph statistics *(coming soon)*
+: Show semantic graph statistics _(coming soon)_
`gc [--aggressive]`
-: Compress old journal entries *(coming soon)*
+: Compress old journal entries _(coming soon)_
### Utility Commands
@@ -1143,21 +1232,27 @@ And git-mind answers, instantly, accurately, with the wisdom of everyone who cam
## HOW IT WORKS
### The Journal Layer (Truth)
+
Every semantic link is stored as a Git commit in refs/gitmind/edges/. These commits:
+
- Contain CBOR-encoded edge data
- Are branch-specific
- Push/pull with your code
- Survive forever in Git history
### The Cache Layer (Speed)
+
For repositories with thousands of connections, git-mind builds Roaring Bitmap indices:
+
- O(log N) query performance
- Sharded by SHA prefix
- Stored in refs/gitmind/cache/
- Rebuilt on demand
### The Evolution System (AUGMENTS)
+
When files change, their blob SHAs change. The AUGMENTS system:
+
- Tracks file evolution automatically
- Preserves connections through changes
- Installed via post-commit hook
@@ -1249,22 +1344,23 @@ Rebuilding cache for branch 'main'...
## PHILOSOPHY
-### Why Journal Commits?
+### Why Journal Commits
-*"It's the Circle of Life, and it moves us all"*
+_"It's the Circle of Life, and it moves us all"_
Traditional metadata systems fight Git's nature. They store data outside the history, create merge conflicts, and lose synchronization. git-mind embraces Git's design:
-- **Commits are immutable** - Your connections can't be lost
-- **Branches isolate changes** - Different understanding on different branches
-- **History is permanent** - Travel through time to see past understanding
-- **Merging is managed** - Git handles conflicts naturally
+- __Commits are immutable__ - Your connections can't be lost
+- __Branches isolate changes__ - Different understanding on different branches
+- __History is permanent__ - Travel through time to see past understanding
+- __Merging is managed__ - Git handles conflicts naturally
-### Why Semantic Connections?
+### Why Semantic Connections
-*"There's more to being king than getting your way"*
+_"There's more to being king than getting your way"_
Code without context is just syntax. Understanding comes from relationships:
+
- Why was this built?
- What does it implement?
- What depends on it?
@@ -1272,11 +1368,12 @@ Code without context is just syntax. Understanding comes from relationships:
git-mind makes these relationships first-class citizens of your repository.
-### Why Performance Matters?
+### Why Performance Matters
-*"Life's not fair, is it?"*
+_"Life's not fair, is it?"_
A tool unused is worthless. git-mind stays fast through:
+
- Pure C implementation
- Roaring Bitmap indices
- O(log N) query complexity
@@ -1298,7 +1395,8 @@ git config --add remote.origin.fetch '+refs/gitmind/*:refs/gitmind/*'
### Editor Integration
-*(Coming soon)* Plugins for:
+_(Coming soon)_ Plugins for:
+
- VS Code - See connections in sidebar
- Vim - Query connections with :GitMindList
- Emacs - Semantic navigation with git-mind-mode
@@ -1316,25 +1414,31 @@ git config --add remote.origin.fetch '+refs/gitmind/*:refs/gitmind/*'
## THE DEEPER MAGIC
### For Individuals
-*"Look inside yourself. You are more than what you have become."*
+
+*"Look inside yourself. You are more than what you have become."_
Your understanding is valuable. git-mind preserves it, letting you:
+
- Remember why you made decisions
- Navigate by meaning, not just files
- Build on your past insights
### For Teams
-*"We are one."*
+
+*"We are one."_
Shared understanding is your competitive advantage:
+
- Onboard faster with visible relationships
- Preserve knowledge through transitions
- Build collective intelligence
### For the Future
-*"It is time."*
+
+*"It is time."_
What starts as a CLI becomes:
+
- Infrastructure for AI agents
- Foundation for semantic IDEs
- Bridge between human and machine understanding
@@ -1378,12 +1482,14 @@ What starts as a CLI becomes:
## SEE ALSO
Individual command documentation:
+
- `git-mind-link(1)` - Create connections
- `git-mind-list(1)` - Query connections
- `git-mind-cache-rebuild(1)` - Rebuild performance cache
- `git-mind-install-hooks(1)` - Setup evolution tracking
Git documentation:
+
- `git(1)` - The stupid content tracker
- `gitglossary(7)` - Git glossary
@@ -1392,6 +1498,7 @@ Git documentation:
git-mind emerged from a simple observation: we spend enormous effort understanding code, then throw that understanding away. What if we could capture it?
The journey from idea to implementation taught us:
+
- Simple is powerful (just Git commits)
- Performance enables adoption (Roaring Bitmaps)
- Evolution is inevitable (AUGMENTS system)
@@ -1401,11 +1508,11 @@ The journey from idea to implementation taught us:
Created by J. Kirby Ross and the Neuroglyph Collective.
-*"Hakuna Matata"* - No worries, your semantic connections are safe.
+_"Hakuna Matata"_ - No worries, your semantic connections are safe.
## THE PROMISE
-*"Remember who you are."*
+_"Remember who you are."_
Your code tells a story. git-mind helps you remember it, share it, and build upon it. In the great Circle of Development, no understanding is lost, no connection forgotten, no wisdom wasted.
@@ -1413,8 +1520,6 @@ Welcome to semantic version control. Welcome to git-mind.
---
-*"Oh yes, the past can hurt. But the way I see it, you can either run from it or learn from it."*
-
-**Choose to learn. Choose git-mind.**
-
+_"Oh yes, the past can hurt. But the way I see it, you can either run from it or learn from it."_
+__Choose to learn. Choose git-mind.__
diff --git a/docs/cli/gitmind-cache-rebuild.md b/docs/cli/gitmind-cache-rebuild.md
index 95f3bc41..02b4a006 100644
--- a/docs/cli/gitmind-cache-rebuild.md
+++ b/docs/cli/gitmind-cache-rebuild.md
@@ -3,9 +3,10 @@
# git-mind cache-rebuild
-> *"Look at the stars. The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."* - Mufasa
+> _"Look at the stars. The great kings of the past look down on us from those stars... So whenever you feel alone, just remember that those kings will always be there to guide you, and so will I."_ - Mufasa
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -31,16 +32,20 @@ This command rebuilds the performance cache for the current (or specified) branc
## HOW IT WORKS
### The Journal: Source of Truth
+
Your semantic links live as CBOR-encoded Git commits in `refs/gitmind/edges/`. This is the permanent record - like the stars themselves.
### The Cache: Speed of Light
+
The cache creates two Roaring Bitmap indices:
-- **Forward index**: source SHA → edge IDs (who depends on this?)
-- **Reverse index**: target SHA → edge IDs (what does this depend on?)
+
+- __Forward index__: source SHA → edge IDs (who depends on this?)
+- __Reverse index__: target SHA → edge IDs (what does this depend on?)
These are stored as Git tree objects under `refs/gitmind/cache/`, sharded into 256 buckets using the first byte of each SHA.
### The Magic: Roaring Bitmaps
+
Roaring Bitmaps compress sequences of integers with supernatural efficiency. A million edges might compress to just kilobytes. It's the same technology that powers modern databases and search engines.
## OPTIONS
@@ -57,6 +62,7 @@ Roaring Bitmaps compress sequences of integers with supernatural efficiency. A m
## EXAMPLES
### Basic rebuild for current branch
+
```bash
$ git mind cache-rebuild
Rebuilding cache for branch 'main'...
@@ -66,6 +72,7 @@ Cache rebuilt successfully!
```
### Rebuild after heavy development
+
```bash
$ git mind link src/parser.c docs/parsing.md --type implements
$ git mind link src/lexer.c src/parser.c --type feeds
@@ -76,6 +83,7 @@ Cache updated incrementally!
```
### Force rebuild when things seem wrong
+
```bash
$ git mind cache-rebuild --force --verbose
Force rebuilding cache for branch 'main'...
@@ -92,29 +100,32 @@ Cache rebuilt: refs/gitmind/cache/main -> 3a7f9b2
## PERFORMANCE
Without cache (journal scan):
+
- 1,000 edges: ~50ms
- 10,000 edges: ~500ms
- 100,000 edges: ~5000ms
With cache (bitmap query):
+
- 1,000 edges: ~2ms
- 10,000 edges: ~5ms
- 100,000 edges: ~10ms
-*"It's the Circle of Life, and it moves us all!"* The cache makes git-mind scale to repositories with millions of semantic connections.
+_"It's the Circle of Life, and it moves us all!"_ The cache makes git-mind scale to repositories with millions of semantic connections.
## WHEN TO REBUILD
The cache automatically detects when it's stale by comparing the journal tip with the cached tip. However, you should manually rebuild when:
-1. **After bulk operations** - Added many links at once
-2. **After merging branches** - Cache is branch-specific
-3. **Performance degrades** - Queries feel slow
-4. **Something seems wrong** - Use `--force` to ensure consistency
+1. __After bulk operations__ - Added many links at once
+2. __After merging branches__ - Cache is branch-specific
+3. __Performance degrades__ - Queries feel slow
+4. __Something seems wrong__ - Use `--force` to ensure consistency
## TECHNICAL DETAILS
### Storage Format
+
```
refs/gitmind/cache/main
└── tree
@@ -130,12 +141,15 @@ refs/gitmind/cache/main
```
### Bitmap Serialization
+
Each bitmap file contains:
+
1. 16-byte header with magic number and version
2. Compressed Roaring Bitmap data
3. CRC32 checksum
### Incremental Updates
+
The cache tracks the last processed journal commit. On rebuild, it only processes new commits, making updates extremely fast.
## DIAGNOSTICS
@@ -143,9 +157,10 @@ The cache tracks the last processed journal commit. On rebuild, it only processe
The cache-rebuild command returns 0 on success, non-zero on failure.
Common issues:
-- **"Permission denied"**: Ensure you have write access to `.git/`
-- **"No journal found"**: Create some links first with `git mind link`
-- **"Invalid journal format"**: Corrupted journal - seek help
+
+- __"Permission denied"__: Ensure you have write access to `.git/`
+- __"No journal found"__: Create some links first with `git mind link`
+- __"Invalid journal format"__: Corrupted journal - seek help
## SEE ALSO
@@ -155,7 +170,7 @@ Common issues:
## PHILOSOPHY
-*"Remember who you are."*
+_"Remember who you are."_
The cache is not the truth - it's a performance optimization. The journal commits are the permanent record. If the cache is ever lost or corrupted, it can always be rebuilt from the journal.
@@ -163,4 +178,4 @@ This design ensures that git-mind scales from personal note-taking to massive co
---
-*In the great Circle of Life, every query begins with a search, and every search begins with hope. The cache ensures that hope is never disappointed.*
+_In the great Circle of Life, every query begins with a search, and every search begins with hope. The cache ensures that hope is never disappointed._
diff --git a/docs/cli/gitmind-install-hooks.md b/docs/cli/gitmind-install-hooks.md
index c0238b57..242e338b 100644
--- a/docs/cli/gitmind-install-hooks.md
+++ b/docs/cli/gitmind-install-hooks.md
@@ -3,9 +3,10 @@
# git-mind install-hooks
-> *"The past can hurt. But the way I see it, you can either run from it or learn from it."* - Rafiki
+> _"The past can hurt. But the way I see it, you can either run from it or learn from it."_ - Rafiki
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -54,6 +55,7 @@ Now when you query connections to main.c, git-mind knows to follow the AUGMENTS
## EXAMPLES
### First time installation
+
```bash
$ git mind install-hooks
Installing git-mind hooks...
@@ -64,6 +66,7 @@ Your commits will now track file evolution automatically.
```
### With existing hooks
+
```bash
$ git mind install-hooks
Found existing post-commit hook
@@ -75,6 +78,7 @@ Both your existing hook and git-mind will run after commits.
```
### Force installation
+
```bash
$ git mind install-hooks --force --no-backup
Installing git-mind hooks...
@@ -85,6 +89,7 @@ Installing git-mind hooks...
## HOW IT WORKS
### The Hook Script
+
The installed hook is a simple shell script that calls the git-mind-hook binary:
```bash
@@ -102,7 +107,9 @@ fi
```
### The Magic Moment
+
After every commit, the hook:
+
1. Gets the list of modified files
2. For each file, finds its old blob SHA (before commit)
3. Searches recent edges (last 200) for links to that blob
@@ -110,7 +117,9 @@ After every commit, the hook:
5. Updates the semantic graph silently in the background
### Performance
+
The hook is blazing fast:
+
- Typical commit: <10ms overhead
- Large commit (50+ files): <50ms overhead
- Massive refactor (500+ files): <200ms overhead
@@ -120,11 +129,13 @@ It runs asynchronously and never blocks your workflow.
## WHEN AUGMENTS HAPPEN
AUGMENTS edges are created when:
+
- You modify a file that has incoming semantic links
- You rename a file (old path AUGMENTS to new path)
- You split a file (original AUGMENTS to both pieces)
AUGMENTS edges are NOT created for:
+
- New files (no history to track)
- Deleted files (use tombstone edges instead)
- Merge commits (too complex for v1)
@@ -160,7 +171,7 @@ Your semantic links remain intact - only automatic tracking stops.
## PHILOSOPHY
-*"Oh yes, the past can hurt. But you can either run from it or learn from it."*
+_"Oh yes, the past can hurt. But you can either run from it or learn from it."_
Code evolution is natural. Files grow, split, merge, and transform. The AUGMENTS system doesn't fight this change - it embraces it. Every commit becomes a checkpoint in your code's journey.
@@ -169,7 +180,9 @@ Traditional version control tracks what changed. Semantic version control tracks
## TECHNICAL DETAILS
### Edge Format
+
AUGMENTS edges have a special format:
+
```
{
src_sha: "abc123...", // Old blob SHA
@@ -182,10 +195,13 @@ AUGMENTS edges have a special format:
```
### Search Window
+
The hook searches the last 200 edges for performance. This covers several days of typical development. Older links won't auto-update but can be manually linked.
### Conflict Resolution
+
AUGMENTS edges never conflict because they:
+
- Use ULID-based edge IDs (time-ordered, unique)
- Are append-only (no modifications)
- Are branch-specific (isolated evolution)
@@ -199,7 +215,7 @@ AUGMENTS edges never conflict because they:
## THE LESSON
-*"Change is good."* - Rafiki
+_"Change is good."_ - Rafiki
But change without memory is chaos. The AUGMENTS system ensures that every transformation is recorded, every evolution is traceable, and every connection persists through change.
@@ -207,4 +223,4 @@ Install the hooks. Let your code's journey document itself.
---
-*Asante sana, squash banana! Your semantic links now travel through time!* 🐒
+_Asante sana, squash banana! Your semantic links now travel through time!_ 🐒
diff --git a/docs/cli/gitmind-link.md b/docs/cli/gitmind-link.md
index 2eef2480..ff771e9b 100644
--- a/docs/cli/gitmind-link.md
+++ b/docs/cli/gitmind-link.md
@@ -3,9 +3,10 @@
# git-mind link
-> *"Everything the light touches is our kingdom... But a king's time as ruler rises and falls like the sun."* - Mufasa
+> _"Everything the light touches is our kingdom... But a king's time as ruler rises and falls like the sun."_ - Mufasa
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -43,22 +44,24 @@ From this moment forward, anyone who checks out your code can discover this rela
## OPTIONS
`--type `
-: **Required.** The type of semantic relationship. Common types:
- - `implements` - Source implements design/spec in target
- - `references` - Source references or mentions target
- - `depends_on` - Source requires target to function
- - `tests` - Source tests the functionality in target
- - `documents` - Source documents how target works
- - `inspires` - Source inspired the creation of target
- - `refactors` - Source is refactored version of target
- - *...or any relationship that captures your understanding*
+: __Required.__ The type of semantic relationship. Common types:
+
+- `implements` - Source implements design/spec in target
+- `references` - Source references or mentions target
+- `depends_on` - Source requires target to function
+- `tests` - Source tests the functionality in target
+- `documents` - Source documents how target works
+- `inspires` - Source inspired the creation of target
+- `refactors` - Source is refactored version of target
+- _...or any relationship that captures your understanding_
`--confidence `
: Confidence level from 0.0 to 1.0 (default: 1.0)
- - `1.0` - Certain (default)
- - `0.8` - Highly confident
- - `0.5` - Somewhat confident
- - `0.2` - Speculative
+
+- `1.0` - Certain (default)
+- `0.8` - Highly confident
+- `0.5` - Somewhat confident
+- `0.2` - Speculative
`--note `
: Add a note explaining the connection (stored in commit message)
@@ -72,6 +75,7 @@ From this moment forward, anyone who checks out your code can discover this rela
## EXAMPLES
### Basic usage - The daily workflow
+
```bash
# Implementation tracks design
$ git mind link src/auth.c docs/auth-design.md --type implements
@@ -84,6 +88,7 @@ $ git mind link src/auth.c config/auth.yaml --type depends_on
```
### With confidence - Encoding uncertainty
+
```bash
# Human creating a confident link (confidence defaults to 1.0)
$ git mind link src/parser.c rfc/grammar.txt --type implements
@@ -99,6 +104,7 @@ $ git mind link src/algorithm.c papers/dijkstra62.pdf --type references --confid
```
### Bidirectional links - Symmetric relationships
+
```bash
# These files are peers that reference each other
$ git mind link src/client.c src/server.c --type references --bidirectional
@@ -107,6 +113,7 @@ Created edge: src/server.c ──references──> src/client.c
```
### Human-AI Collaboration - Attribution System
+
```bash
# Human creates edge (default behavior)
$ git mind link README.md src/main.c --type documents
@@ -127,14 +134,18 @@ $ git mind link old_file.c new_file.c --type augments
## HOW IT WORKS
### Git-Native Storage
+
Each link is stored as a Git commit in `refs/gitmind/edges/`. The commit contains:
+
- CBOR-encoded edge data in the commit message
- Empty tree (git's null tree: 4b825dc...)
- Author/committer from your Git config
- Timestamp of creation
### Content Addressing
+
Links connect specific versions of files using their blob SHAs:
+
```
source_sha: 8a9f3b2c... # SHA of design.md's content
target_sha: 7c4d5e6f... # SHA of parser.c's content
@@ -143,13 +154,15 @@ target_sha: 7c4d5e6f... # SHA of parser.c's content
This means links point to exact versions. When files change, the AUGMENTS system (see `git-mind-install-hooks(1)`) tracks their evolution.
### Branch Isolation
+
Links are branch-specific. Create different connections on different branches:
+
```bash
-$ git checkout -b feature/auth
-$ git mind link src/auth.c new-auth-api.md --type implements
+git checkout -b feature/auth
+git mind link src/auth.c new-auth-api.md --type implements
-$ git checkout main
-$ git mind list # Won't show the feature branch link
+git checkout main
+git mind list # Won't show the feature branch link
```
## RELATIONSHIP TYPES
@@ -157,24 +170,28 @@ $ git mind list # Won't show the feature branch link
While you can use any string as a relationship type, these conventions help maintain consistency:
### Structural Relations
+
- `implements` - Code implements a design/specification
- `depends_on` - Requires target to function correctly
- `extends` - Builds upon target's functionality
- `replaces` - Newer version replacing target
### Documentation Relations
+
- `documents` - Explains how target works
- `references` - Mentions or links to target
- `examples` - Shows usage of target
- `tutorials` - Teaches concepts in target
### Development Relations
+
- `tests` - Validates target's behavior
- `benchmarks` - Measures target's performance
- `fixes` - Resolves issues in target
- `refactors` - Restructured version of target
### Inspiration Relations
+
- `inspires` - Target inspired this implementation
- `adapts` - Modified version of target's approach
- `conflicts` - Incompatible with target
@@ -183,6 +200,7 @@ While you can use any string as a relationship type, these conventions help main
## BEST PRACTICES
### Be Specific
+
```bash
# Too vague
$ git mind link src/parser.c docs/ --type references # Which doc?
@@ -192,18 +210,22 @@ $ git mind link src/parser.c docs/parser-design.md --type implements
```
### Use Conventional Types
+
Stick to common relationship types when possible. This makes queries more powerful:
+
```bash
# Find all tests easily
$ git mind list --type tests
```
### Link at the Right Granularity
+
- Link files, not directories (unless the directory is the unit)
- Link to specific documents, not entire folders
- Link the most specific relevant files
### Document Non-Obvious Links
+
```bash
# Why does the parser depend on the logger config?
$ git mind link src/parser.c config/logger.yaml --type depends_on \
@@ -212,9 +234,10 @@ $ git mind link src/parser.c config/logger.yaml --type depends_on \
## PERMANENCE & EVOLUTION
-*"Remember who you are."*
+_"Remember who you are."_
Every link you create becomes part of your repository's permanent history. Future developers can:
+
- See what you connected and why
- Travel back to see historical connections
- Understand the evolution of architectural decisions
@@ -225,16 +248,19 @@ This is why git-mind exists: to encode not just what your code is, but what it m
Common errors and solutions:
-**"File not found"**
+__"File not found"__
+
- Ensure both source and target exist in the repository
- Use paths relative to repository root
- Check for typos in filenames
-**"Not in a git repository"**
+__"Not in a git repository"__
+
- Run from within a Git repository
- Initialize with `git init` if needed
-**"Invalid confidence value"**
+__"Invalid confidence value"__
+
- Use a float between 0.0 and 1.0
- Default is 1.0 if not specified
@@ -247,7 +273,7 @@ Common errors and solutions:
## THE PHILOSOPHY
-*"There's more to being a king than getting your way."*
+_"There's more to being a king than getting your way."_
Creating links is an act of documentation, but more than that - it's an act of teaching. Every link you create teaches future readers (including future you) about the relationships that matter.
@@ -255,4 +281,4 @@ The power isn't in the tool. It's in the understanding you encode with it.
---
-*"You are more than what you have become. Remember."* - Your semantic links remember for you.
+_"You are more than what you have become. Remember."_ - Your semantic links remember for you.
diff --git a/docs/cli/gitmind-list.md b/docs/cli/gitmind-list.md
index 608343dd..01d5c05e 100644
--- a/docs/cli/gitmind-list.md
+++ b/docs/cli/gitmind-list.md
@@ -3,9 +3,10 @@
# git-mind list
-> *"Look beyond what you see."* - Rafiki
+> _"Look beyond what you see."_ - Rafiki
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -30,6 +31,7 @@ This is your window into understanding. Use it to discover dependencies, trace i
## THE POWER OF SEEING
Without git-mind:
+
```bash
# Where is this implemented?
$ grep -r "auth flow" docs/
@@ -40,6 +42,7 @@ $ # ...good luck
```
With git-mind:
+
```bash
# All connections at a glance
$ git mind list --from src/parser.c
@@ -71,10 +74,11 @@ $ git mind list
`--format `
: Output format (default: human)
- - `human` - Readable format with arrows
- - `json` - Machine-parseable JSON
- - `tsv` - Tab-separated values
- - `dot` - Graphviz DOT format
+
+- `human` - Readable format with arrows
+- `json` - Machine-parseable JSON
+- `tsv` - Tab-separated values
+- `dot` - Graphviz DOT format
`--show-sha`
: Display blob SHAs (default: hide)
@@ -106,6 +110,7 @@ $ git mind list
### Basic Queries
Show all connections:
+
```bash
$ git mind list
README.md ──references──> docs/quickstart.md
@@ -118,6 +123,7 @@ src/parser.c ──depends_on──> config/grammar.yaml
### Focused Queries
What does this file connect to?
+
```bash
$ git mind list --from src/auth.c
src/auth.c ──implements──> docs/auth-design.md
@@ -126,6 +132,7 @@ src/auth.c ──references──> lib/crypto.c
```
What connects to this file?
+
```bash
$ git mind list --to src/parser.c
tests/test_parser.c ──tests──> src/parser.c
@@ -137,6 +144,7 @@ src/compiler.c ──depends_on──> src/parser.c
### Filtered Queries
Find all test files:
+
```bash
$ git mind list --type tests
tests/test_auth.c ──tests──> src/auth.c
@@ -145,6 +153,7 @@ tests/integration/test_flow.c ──tests──> src/flow.c
```
Find uncertain connections:
+
```bash
$ git mind list --min-confidence 0.8
src/auth.c ──depends_on──> config/oauth.json [claude: claude@anthropic, conf: 0.85]
@@ -154,6 +163,7 @@ src/parser.c ──implements──> specs/grammar.md [gpt: gpt4@openai, conf: 0
### Attribution Filtering
Show only human-created edges:
+
```bash
$ git mind list --source human
README.md ──documents──> src/main.c
@@ -162,6 +172,7 @@ tests/test_auth.c ──tests──> src/auth.c
```
Show only AI-suggested edges:
+
```bash
$ git mind list --source ai
src/parser.c ──depends_on──> lib/lexer.h [claude: claude@anthropic, conf: 0.78]
@@ -169,6 +180,7 @@ src/crypto.c ──references──> papers/aes.pdf [gpt: gpt4@openai, conf: 0.9
```
Show attribution for all edges:
+
```bash
$ git mind list --show-attribution
README.md ──documents──> src/main.c [human: user@example.com]
@@ -177,6 +189,7 @@ src/test.c ──tests──> src/main.c [human: developer@team.com]
```
High-confidence AI insights only:
+
```bash
$ git mind list --source ai --min-confidence 0.9
src/crypto.c ──references──> papers/aes.pdf [gpt: gpt4@openai, conf: 0.91]
@@ -186,6 +199,7 @@ src/algorithm.c ──implements──> papers/dijkstra.pdf [claude: claude@anth
### Time Travel Queries
See historical connections:
+
```bash
# What did we understand 50 commits ago?
$ git mind list --at HEAD~50
@@ -200,6 +214,7 @@ $ git mind list --branch feature/new-auth
### Evolution Tracking
See how files evolved:
+
```bash
$ git mind list --show-augments
src/auth.c:8a9f3b ──AUGMENTS──> src/auth.c:7c4d5e
@@ -210,6 +225,7 @@ docs/api.md:3f2a1b ──AUGMENTS──> docs/api.md:current
### Machine-Readable Output
JSON for tooling:
+
```bash
$ git mind list --format json
{
@@ -226,19 +242,22 @@ $ git mind list --format json
```
DOT for visualization:
+
```bash
-$ git mind list --format dot > graph.dot
-$ dot -Tpng graph.dot -o graph.png
+git mind list --format dot > graph.dot
+dot -Tpng graph.dot -o graph.png
```
## UNDERSTANDING THE OUTPUT
### Human Format (default)
+
```
────> [metadata]
```
Metadata may include:
+
- `(confidence: 0.8)` - Less than certain connections
- `(SHA: abc123)` - When --show-sha is used
- `(AUGMENTED)` - When file has evolved
@@ -259,14 +278,15 @@ Use `--no-follow-augments` to see historical links.
The list command uses the Roaring Bitmap cache for O(log N) queries:
-- **With cache**: <10ms for 100K edges
-- **Without cache**: ~5 seconds for 100K edges
-- **Cache miss**: Automatically falls back to journal scan
-- **Stale cache**: Detects and warns (run `git mind cache-rebuild`)
+- __With cache__: <10ms for 100K edges
+- __Without cache__: ~5 seconds for 100K edges
+- __Cache miss__: Automatically falls back to journal scan
+- __Stale cache__: Detects and warns (run `git mind cache-rebuild`)
## ADVANCED PATTERNS
### Dependency Analysis
+
```bash
# What does my module depend on?
$ git mind list --from "src/mymodule/**" --type depends_on
@@ -276,6 +296,7 @@ $ git mind list --to config/database.yaml --type depends_on
```
### Test Coverage Discovery
+
```bash
# What files lack tests?
$ comm -23 \
@@ -284,6 +305,7 @@ $ comm -23 \
```
### Architecture Visualization
+
```bash
# Generate architecture diagram
$ git mind list --format dot --type implements > arch.dot
@@ -291,6 +313,7 @@ $ dot -Tsvg arch.dot -o architecture.svg
```
### Change Impact Analysis
+
```bash
# What might break if I change this?
$ git mind list --to src/core-api.h --type depends_on
@@ -298,7 +321,7 @@ $ git mind list --to src/core-api.h --type depends_on
## PHILOSOPHY
-*"The question is: Who are you?"* - Rafiki
+_"The question is: Who are you?"_ - Rafiki
Your code is more than files and functions. It's a living system of relationships, dependencies, and meanings. The `list` command doesn't just show you connections - it reveals the hidden structure of your understanding.
@@ -309,6 +332,7 @@ Every query is a question about your code's nature. Every result is an answer th
Returns 0 on success, non-zero on failure.
Common warnings:
+
- `Cache stale, using journal scan` - Run `git mind cache-rebuild`
- `No edges found` - No links match your query
- `Following AUGMENTS chain` - File has evolved (use --no-follow-augments for original)
@@ -322,10 +346,10 @@ Common warnings:
## THE LESSON
-*"Oh, the past can hurt. But the way I see it, you can either run from it or learn from it."*
+_"Oh, the past can hurt. But the way I see it, you can either run from it or learn from it."_
Every list query teaches you something about your codebase. The more you look, the more you see. The more you see, the more you understand.
---
-*"It is time."* - Time to see what connects your kingdom.
+_"It is time."_ - Time to see what connects your kingdom.
diff --git a/docs/cli/gitmind.md b/docs/cli/gitmind.md
index 62b7df07..68315ebc 100644
--- a/docs/cli/gitmind.md
+++ b/docs/cli/gitmind.md
@@ -3,9 +3,10 @@
# git-mind
-> *"Remember who you are."* - Mufasa
+> _"Remember who you are."_ - Mufasa
Table of Contents
+
- [Name](#name)
- [Synopsis](#synopsis)
- [Description](#description)
@@ -28,16 +29,18 @@ In the great Circle of Development, code is written, connections form, understan
git-mind adds a semantic layer to Git, allowing you to create, query, and explore meaningful relationships between files. These connections travel through time with your code, creating a permanent record of your understanding.
-*"Everything the light touches has been connected by git-mind."*
+_"Everything the light touches has been connected by git-mind."_
## THE VISION
You're deep in a codebase. Instead of asking:
+
- "Where is this implemented?" (grep)
- "What depends on this?" (hope)
- "Where are the tests?" (find)
You ask:
+
- "Show me all implementations of this design"
- "What breaks if I change this?"
- "How has our understanding evolved?"
@@ -55,10 +58,10 @@ And git-mind answers, instantly, accurately, with the wisdom of everyone who cam
: Query and explore connections
`traverse [--depth N]`
-: Follow connection paths from starting point *(coming soon)*
+: Follow connection paths from starting point _(coming soon)_
`unlink `
-: Remove connection (adds tombstone) *(coming soon)*
+: Remove connection (adds tombstone) _(coming soon)_
### Management Commands
@@ -69,10 +72,10 @@ And git-mind answers, instantly, accurately, with the wisdom of everyone who cam
: Install Git hooks for automatic evolution tracking
`status`
-: Show semantic graph statistics *(coming soon)*
+: Show semantic graph statistics _(coming soon)_
`gc [--aggressive]`
-: Compress old journal entries *(coming soon)*
+: Compress old journal entries _(coming soon)_
### Utility Commands
@@ -85,21 +88,27 @@ And git-mind answers, instantly, accurately, with the wisdom of everyone who cam
## HOW IT WORKS
### The Journal Layer (Truth)
+
Every semantic link is stored as a Git commit in refs/gitmind/edges/. These commits:
+
- Contain CBOR-encoded edge data
- Are branch-specific
- Push/pull with your code
- Survive forever in Git history
### The Cache Layer (Speed)
+
For repositories with thousands of connections, git-mind builds Roaring Bitmap indices:
+
- O(log N) query performance
- Sharded by SHA prefix
- Stored in refs/gitmind/cache/
- Rebuilt on demand
### The Evolution System (AUGMENTS)
+
When files change, their blob SHAs change. The AUGMENTS system:
+
- Tracks file evolution automatically
- Preserves connections through changes
- Installed via post-commit hook
@@ -191,22 +200,23 @@ Rebuilding cache for branch 'main'...
## PHILOSOPHY
-### Why Journal Commits?
+### Why Journal Commits
-*"It's the Circle of Life, and it moves us all"*
+_"It's the Circle of Life, and it moves us all"_
Traditional metadata systems fight Git's nature. They store data outside the history, create merge conflicts, and lose synchronization. git-mind embraces Git's design:
-- **Commits are immutable** - Your connections can't be lost
-- **Branches isolate changes** - Different understanding on different branches
-- **History is permanent** - Travel through time to see past understanding
-- **Merging is managed** - Git handles conflicts naturally
+- __Commits are immutable__ - Your connections can't be lost
+- __Branches isolate changes__ - Different understanding on different branches
+- __History is permanent__ - Travel through time to see past understanding
+- __Merging is managed__ - Git handles conflicts naturally
-### Why Semantic Connections?
+### Why Semantic Connections
-*"There's more to being king than getting your way"*
+_"There's more to being king than getting your way"_
Code without context is just syntax. Understanding comes from relationships:
+
- Why was this built?
- What does it implement?
- What depends on it?
@@ -214,11 +224,12 @@ Code without context is just syntax. Understanding comes from relationships:
git-mind makes these relationships first-class citizens of your repository.
-### Why Performance Matters?
+### Why Performance Matters
-*"Life's not fair, is it?"*
+_"Life's not fair, is it?"_
A tool unused is worthless. git-mind stays fast through:
+
- Pure C implementation
- Roaring Bitmap indices
- O(log N) query complexity
@@ -240,7 +251,8 @@ git config --add remote.origin.fetch '+refs/gitmind/*:refs/gitmind/*'
### Editor Integration
-*(Coming soon)* Plugins for:
+_(Coming soon)_ Plugins for:
+
- VS Code - See connections in sidebar
- Vim - Query connections with :GitMindList
- Emacs - Semantic navigation with git-mind-mode
@@ -258,25 +270,31 @@ git config --add remote.origin.fetch '+refs/gitmind/*:refs/gitmind/*'
## THE DEEPER MAGIC
### For Individuals
-*"Look inside yourself. You are more than what you have become."*
+
+*"Look inside yourself. You are more than what you have become."_
Your understanding is valuable. git-mind preserves it, letting you:
+
- Remember why you made decisions
- Navigate by meaning, not just files
- Build on your past insights
### For Teams
-*"We are one."*
+
+*"We are one."_
Shared understanding is your competitive advantage:
+
- Onboard faster with visible relationships
- Preserve knowledge through transitions
- Build collective intelligence
### For the Future
-*"It is time."*
+
+*"It is time."_
What starts as a CLI becomes:
+
- Infrastructure for AI agents
- Foundation for semantic IDEs
- Bridge between human and machine understanding
@@ -320,12 +338,14 @@ What starts as a CLI becomes:
## SEE ALSO
Individual command documentation:
+
- `git-mind-link(1)` - Create connections
- `git-mind-list(1)` - Query connections
- `git-mind-cache-rebuild(1)` - Rebuild performance cache
- `git-mind-install-hooks(1)` - Setup evolution tracking
Git documentation:
+
- `git(1)` - The stupid content tracker
- `gitglossary(7)` - Git glossary
@@ -334,6 +354,7 @@ Git documentation:
git-mind emerged from a simple observation: we spend enormous effort understanding code, then throw that understanding away. What if we could capture it?
The journey from idea to implementation taught us:
+
- Simple is powerful (just Git commits)
- Performance enables adoption (Roaring Bitmaps)
- Evolution is inevitable (AUGMENTS system)
@@ -343,11 +364,11 @@ The journey from idea to implementation taught us:
Created by J. Kirby Ross and the Neuroglyph Collective.
-*"Hakuna Matata"* - No worries, your semantic connections are safe.
+_"Hakuna Matata"_ - No worries, your semantic connections are safe.
## THE PROMISE
-*"Remember who you are."*
+_"Remember who you are."_
Your code tells a story. git-mind helps you remember it, share it, and build upon it. In the great Circle of Development, no understanding is lost, no connection forgotten, no wisdom wasted.
@@ -355,6 +376,6 @@ Welcome to semantic version control. Welcome to git-mind.
---
-*"Oh yes, the past can hurt. But the way I see it, you can either run from it or learn from it."*
+_"Oh yes, the past can hurt. But the way I see it, you can either run from it or learn from it."_
-**Choose to learn. Choose git-mind.**
+__Choose to learn. Choose git-mind.__
diff --git a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_angle-includes.md b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_angle-includes.md
index 42a06c09..90920bff 100644
--- a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_angle-includes.md
+++ b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_angle-includes.md
@@ -1,21 +1,28 @@
Summary
+
- Suggestion: Prefer angle brackets for installed/public-style includes
Rationale for rejection
+
- - We keep project headers included with quotes for consistency across CLI sources. Switching this single header to angle brackets would introduce inconsistency without functional benefit.
What you did instead
+
- Maintained current approach consistent with repository conventions and near-term goals.
Tradeoffs considered
+
- Pros: Minimal diffs; aligns with existing code; reduces risk.
- Cons: Leaves some polish/robustness opportunities unaddressed for now.
What would make you change your mind
+
- Clear repository-wide policy shift or a follow-up PR enabling this safely.
Future Plans
+
- Revisit after core features stabilize; track in PR #166 follow-ups.
Confidence
+
- 7/10. Based on current CI and style norms in this repo.
diff --git a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_consumed-length.md b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_consumed-length.md
index 2655eda1..b0d17155 100644
--- a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_consumed-length.md
+++ b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_consumed-length.md
@@ -1,21 +1,28 @@
Summary
+
- Suggestion: _🛠️ Refactor suggestion_
Rationale for rejection
+
- - Journal currently stores one CBOR edge per commit; a robust measure helper (gm_cbor_measure_edge) is not yet available. The wrapper will be replaced when the attributed decoder lands, at which point proper consumption will be implemented in the CBOR module.
What you did instead
+
- Maintained current approach consistent with repository conventions and near-term goals.
Tradeoffs considered
+
- Pros: Minimal diffs; aligns with existing code; reduces risk.
- Cons: Leaves some polish/robustness opportunities unaddressed for now.
What would make you change your mind
+
- Clear repository-wide policy shift or a follow-up PR enabling this safely.
Future Plans
+
- Revisit after core features stabilize; track in PR #166 follow-ups.
Confidence
+
- 7/10. Based on current CI and style norms in this repo.
diff --git a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_e2e-refactor.md b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_e2e-refactor.md
index c72f4ccf..0eeccc4c 100644
--- a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_e2e-refactor.md
+++ b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_e2e-refactor.md
@@ -1,21 +1,28 @@
Summary
+
- Suggestion: _🛠️ Refactor suggestion_
Rationale for rejection
+
- - The current script already honors GIT_MIND and common build locations. Larger refactors (e.g., richer reporting or temp dirs) will be addressed alongside test coverage changes.
What you did instead
+
- Maintained current approach consistent with repository conventions and near-term goals.
Tradeoffs considered
+
- Pros: Minimal diffs; aligns with existing code; reduces risk.
- Cons: Leaves some polish/robustness opportunities unaddressed for now.
What would make you change your mind
+
- Clear repository-wide policy shift or a follow-up PR enabling this safely.
Future Plans
+
- Revisit after core features stabilize; track in PR #166 follow-ups.
Confidence
+
- 7/10. Based on current CI and style norms in this repo.
diff --git a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_markdownlint.md b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_markdownlint.md
index 02e65f18..cdda2b63 100644
--- a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_markdownlint.md
+++ b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_markdownlint.md
@@ -1,21 +1,28 @@
Summary
+
- Suggestion: Fix markdownlint violations: add blank lines and fix list indentation
Rationale for rejection
+
- - The project does not enforce markdownlint in CI; current README renders well and existing docs checks (links/TOC) pass. We'll adopt markdownlint rules repo‑wide in a docs sweep rather than piecemeal edits here.
What you did instead
+
- Maintained current approach consistent with repository conventions and near-term goals.
Tradeoffs considered
+
- Pros: Minimal diffs; aligns with existing code; reduces risk.
- Cons: Leaves some polish/robustness opportunities unaddressed for now.
What would make you change your mind
+
- Clear repository-wide policy shift or a follow-up PR enabling this safely.
Future Plans
+
- Revisit after core features stabilize; track in PR #166 follow-ups.
Confidence
+
- 7/10. Based on current CI and style norms in this repo.
diff --git a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_replace-macros-with-literals.md b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_replace-macros-with-literals.md
index 64314bc3..fc05f7c2 100644
--- a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_replace-macros-with-literals.md
+++ b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_replace-macros-with-literals.md
@@ -1,21 +1,28 @@
Summary
+
- Suggestion: Fix build: replace undeclared CLI flag/prefix macros with literals
Rationale for rejection
+
- - The referenced CLI flags and messages are defined in include/gitmind/constants.h. Using macros centralizes strings and avoids typos; build issues were due to include paths and have been fixed.
What you did instead
+
- Maintained current approach consistent with repository conventions and near-term goals.
Tradeoffs considered
+
- Pros: Minimal diffs; aligns with existing code; reduces risk.
- Cons: Leaves some polish/robustness opportunities unaddressed for now.
What would make you change your mind
+
- Clear repository-wide policy shift or a follow-up PR enabling this safely.
Future Plans
+
- Revisit after core features stabilize; track in PR #166 follow-ups.
Confidence
+
- 7/10. Based on current CI and style norms in this repo.
diff --git a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_umbrella-safety-include.md b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_umbrella-safety-include.md
index 55281ad4..1981775d 100644
--- a/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_umbrella-safety-include.md
+++ b/docs/code-reviews/rejected-suggestions/4d28721c4b98c6dd29f475d5a1974c2fd2d95a1a_feat-cli-safety-e2e_166_umbrella-safety-include.md
@@ -1,21 +1,28 @@
Summary
+
- Suggestion: Consider exporting safety utilities via the umbrella (if part of public API)
Rationale for rejection
+
- - Safety utilities are CLI‑only and not part of the core public API we want consumers to depend on. Keeping them out of the umbrella avoids accidental external coupling.
What you did instead
+
- Maintained current approach consistent with repository conventions and near-term goals.
Tradeoffs considered
+
- Pros: Minimal diffs; aligns with existing code; reduces risk.
- Cons: Leaves some polish/robustness opportunities unaddressed for now.
What would make you change your mind
+
- Clear repository-wide policy shift or a follow-up PR enabling this safely.
Future Plans
+
- Revisit after core features stabilize; track in PR #166 follow-ups.
Confidence
+
- 7/10. Based on current CI and style norms in this repo.
diff --git a/docs/deployment/Deployment.md b/docs/deployment/Deployment.md
index 89ef3ee3..42dc0ad5 100644
--- a/docs/deployment/Deployment.md
+++ b/docs/deployment/Deployment.md
@@ -1,6 +1,7 @@
# Deployment and Operations
Table of Contents
+
- [Executive Summary](#executive-summary)
- [CI/CD Pipeline](#cicd-pipeline)
- [Environments](#environments)
@@ -8,10 +9,13 @@ Table of Contents
- [Monitoring and Alerts](#monitoring-and-alerts)
## Executive Summary
+
The project ships as a CLI and a C library. CI enforces correctness and toolchain standards; artifacts are Docker images and test/tidy reports. Operations focus on reproducible builds and safe rollback of refs. See also: [Test Plan](../testing/Test_Plan.md).
## CI/CD Pipeline
+
Stages
+
1) Lint/Format: pre-commit checks, clang-tidy (non-blocking for non-target modules)
2) Build: Meson/Ninja builds for gcc-14 and clang-20
3) Test: unit + integration (CLI flows)
@@ -20,14 +24,17 @@ Stages
6) Canaries: older compilers (non-blocking)
Gating Rules
+
- Fail if compiler < C23 (gcc-14/clang-20)
- Fail if tidy warnings exist in scoped modules
## Environments
+
- Dev: Docker shell (`make dev`); local git repo; optional local tools (outside this repo) for export testing
- Prod: Not applicable (local CLI). For library consumers, publish release archives and image tags.
## Rollback Procedures
+
1) Build/Tooling Regression
- Revert CI workflow commit; re-run pipeline
2) Journal Data Regression
@@ -38,6 +45,7 @@ Gating Rules
- Delete `refs/gitmind/cache/` and rebuild via CLI
## Monitoring and Alerts
+
- Local metrics: emit counts/timings to stderr in verbose mode
- Health checks: `git mind status` to validate env and cache/journal alignment
- Thresholds (local logging only)
diff --git a/docs/enforcer/BEFORE_WE_BEGIN.md b/docs/enforcer/BEFORE_WE_BEGIN.md
index cc855437..c3a8ab18 100644
--- a/docs/enforcer/BEFORE_WE_BEGIN.md
+++ b/docs/enforcer/BEFORE_WE_BEGIN.md
@@ -4,9 +4,9 @@
We started migrating some modules from `src/` to `core/` but realized we need solid foundations first. Now we're going to:
-1. **Move everything back to `src/`** - Start with a completely empty `core/`
-2. **Build foundations first** - Implement our specs with zero technical debt
-3. **Then migrate properly** - Using the new foundations
+1. __Move everything back to `src/`__ - Start with a completely empty `core/`
+2. __Build foundations first__ - Implement our specs with zero technical debt
+3. __Then migrate properly__ - Using the new foundations
## The Plan
@@ -49,8 +49,9 @@ tests/
└── e2e/ # End-to-end tests
```
-**Key Points:**
-- Legacy tests may fail after moving code back - **that's fine**
+__Key Points:__
+
+- Legacy tests may fail after moving code back - __that's fine__
- We only care about `core/` tests passing
- CI should only run `core/` tests
- Once a module is reimplemented, delete its legacy version
@@ -79,34 +80,34 @@ git push # Normal push
When migrating a module from `src/` to `core/`:
-1. **DO NOT** copy-paste and fix
-2. **DO** reimplement using new foundations
-3. **DO** write new tests first (TDD)
-4. **DO** ensure zero warnings before committing
-5. **DO** delete the old version once new one works
+1. __DO NOT__ copy-paste and fix
+2. __DO__ reimplement using new foundations
+3. __DO__ write new tests first (TDD)
+4. __DO__ ensure zero warnings before committing
+5. __DO__ delete the old version once new one works
### 6. Why This Works
-- **No broken CI**: New code has zero warnings
-- **Clear progress**: Binary state - migrated or not
-- **No technical debt**: Can't accidentally carry over bad patterns
-- **Enforcer helps**: Prevents "quick fixes" to old code
-- **Clean foundations**: Everything built on solid base
+- __No broken CI__: New code has zero warnings
+- __Clear progress__: Binary state - migrated or not
+- __No technical debt__: Can't accidentally carry over bad patterns
+- __Enforcer helps__: Prevents "quick fixes" to old code
+- __Clean foundations__: Everything built on solid base
### 7. Implementation Order
Following our ROADMAP:
-1. **Week 1**: Foundations in `core/`
+1. __Week 1__: Foundations in `core/`
- Error handling (`GM_RESULT_DEF`)
- Basic types (strong typedefs)
- Security primitives (validation)
-2. **Week 2**: Infrastructure
+2. __Week 2__: Infrastructure
- Observability
- Testing framework
-3. **Week 3**: Memory architecture
+3. __Week 3__: Memory architecture
- Arena allocators
- Object pools
@@ -115,16 +116,17 @@ Then begin migrating modules from `src/` to `core/`.
## The Payoff
In 9 weeks, we'll have:
+
- Zero warnings (down from 11,000+)
- Clean architecture throughout
- Solid foundations
- Maintainable codebase
- No technical debt
-## Ready?
+## Ready
Let's start by moving everything back and creating our first foundation module!
---
-*"Sometimes you have to take a step back to leap forward."*
\ No newline at end of file
+_"Sometimes you have to take a step back to leap forward."_
diff --git a/docs/enforcer/CONTINUE.md b/docs/enforcer/CONTINUE.md
index db57b8f3..ad4a9553 100644
--- a/docs/enforcer/CONTINUE.md
+++ b/docs/enforcer/CONTINUE.md
@@ -6,11 +6,12 @@ You're joining us mid-flight in the git-mind refactoring journey, where we're tr
## 📍 Where We Are
-We're in the **Foundation Building Phase** of the migration, specifically working on Step 2 of the [ROADMAP_TO_REFACTORING.md](./ROADMAP_TO_REFACTORING.md):
+We're in the __Foundation Building Phase__ of the migration, specifically working on Step 2 of the [ROADMAP_TO_REFACTORING.md](./ROADMAP_TO_REFACTORING.md):
-**Step 2: Error Handling + Basic Types + Security Primitives** ✅ SPECS COMPLETE
+__Step 2: Error Handling + Basic Types + Security Primitives__ ✅ SPECS COMPLETE
### What's Been Done
+
1. Created comprehensive gameplans for all 11 architectural capabilities (see [gameplans/](./gameplans/))
2. Refined the attack order based on dependency analysis
3. Written initial specifications for:
@@ -19,6 +20,7 @@ We're in the **Foundation Building Phase** of the migration, specifically workin
- [03-security-primitives-spec.md](./specs/03-security-primitives-spec.md) - UPDATED with production feedback
### Key Technical Decisions Made
+
- Using `GM_RESULT_DEF` macro to create named result types (avoids anonymous struct issues)
- Separated owned strings (`gm_string_t`) from views (`gm_string_view_t`) for clarity
- Made error codes `int32_t` instead of enum for extensibility
@@ -30,16 +32,16 @@ We're in the **Foundation Building Phase** of the migration, specifically workin
Before continuing, familiarize yourself with:
-1. **Context Documents:**
+1. __Context Documents:__
- [ARCHITECTURE.md](ARCHITECTURE.md) - Overall architecture vision
- [MIGRATION_PHILOSOPHY.md](../architecture/MIGRATION_PHILOSOPHY.md) - Why we're doing this
- [CLAUDE.md](../../CLAUDE.md) - The battle that started it all
-2. **Planning Documents:**
- - [ROADMAP_TO_REFACTORING.md](./ROADMAP_TO_REFACTORING.md) - **START HERE** - The 9-week plan
+2. __Planning Documents:__
+ - [ROADMAP_TO_REFACTORING.md](./ROADMAP_TO_REFACTORING.md) - __START HERE__ - The 9-week plan
- [gameplans/README.md](./gameplans/README.md) - Index of all capability gameplans
-3. **Specifications (Just Completed):**
+3. __Specifications (Just Completed):__
- [specs/01-error-types-spec.md](./specs/01-error-types-spec.md) - Error handling patterns
- [specs/02-domain-types-spec.md](./specs/02-domain-types-spec.md) - Strong typedefs
- [specs/03-security-primitives-spec.md](./specs/03-security-primitives-spec.md) - Input validation
@@ -50,7 +52,8 @@ Before continuing, familiarize yourself with:
Now that the specs are complete, it's time to implement Step 2 foundations:
-1. **Create the header files:**
+1. __Create the header files:__
+
```
core/include/gitmind/result.h # GM_RESULT_DEF and standard types
core/include/gitmind/error.h # Error handling infrastructure
@@ -62,25 +65,27 @@ Now that the specs are complete, it's time to implement Step 2 foundations:
core/include/gitmind/security/sanitize.h # String sanitization
```
-2. **Implement the core functionality** following the specs exactly
+2. __Implement the core functionality__ following the specs exactly
-3. **Write comprehensive tests** including:
+3. __Write comprehensive tests__ including:
- Unit tests for each component
- Fuzz testing for security primitives
- Integration tests for error propagation
-4. **Ensure ZERO warnings** on all new code
+4. __Ensure ZERO warnings__ on all new code
### After Step 2 Implementation
Continue with the roadmap:
-- **Step 3: Observability** - Structured logging, tracing, metrics
-- **Step 4: Testing Framework** - Test runner, assertions, mocks
-- **Step 5: Memory Architecture** - Arena allocators, object pools
+
+- __Step 3: Observability__ - Structured logging, tracing, metrics
+- __Step 4: Testing Framework__ - Test runner, assertions, mocks
+- __Step 5: Memory Architecture__ - Arena allocators, object pools
## 💡 Key Insights from This Session
The user emphasized production-level thinking:
+
- "The remaining 10% is the stuff that bites you in prod"
- Anonymous structs from macros create type incompatibility
- Owned flags are dangerous - C devs forget and double-free
@@ -89,11 +94,11 @@ The user emphasized production-level thinking:
## 🔧 Technical Reminders
-1. **Never commit without permission** - The user will explicitly ask
-2. **All Git operations in Docker/temp dirs** - Never in working repo
-3. **SPDX headers on all new files** - Use LicenseRef-MIND-UCAL-1.0
-4. **Test everything in Docker** - Use `make test`
-5. **Follow the specs exactly** - They've been refined based on production experience
+1. __Never commit without permission__ - The user will explicitly ask
+2. __All Git operations in Docker/temp dirs__ - Never in working repo
+3. __SPDX headers on all new files__ - Use LicenseRef-MIND-UCAL-1.0
+4. __Test everything in Docker__ - Use `make test`
+5. __Follow the specs exactly__ - They've been refined based on production experience
## 📝 Notes
@@ -104,4 +109,4 @@ The user emphasized production-level thinking:
---
-*"Getting names and guards in place before we spew any more pointers around is the sane move."*
+_"Getting names and guards in place before we spew any more pointers around is the sane move."_
diff --git a/docs/enforcer/build-these-in.md b/docs/enforcer/build-these-in.md
index f99378a8..f99eb6b4 100644
--- a/docs/enforcer/build-these-in.md
+++ b/docs/enforcer/build-these-in.md
@@ -10,6 +10,7 @@
1. Error Handling Revolution
Principle: Fail loudly, catch gracefully, propagate meaningfully.
+
- Standardize error types: gm_error_t or similar
- Include context + cause chain: e.g., gm_error_with_context(err, "while parsing manifest")
- Enforce Result or Outcome-style patterns
@@ -20,6 +21,7 @@ Principle: Fail loudly, catch gracefully, propagate meaningfully.
2. Memory Architecture Revolution
Principle: Know where every byte lives and dies. Embrace arenas, pools, and lifetimes.
+
- Use arena allocators for ephemeral data (e.g., graph parsing sessions)
- Explicit ownership: no implicit malloc/free chaos
- Implement memory tags for observability (who’s allocating what, why, and how often)
@@ -29,6 +31,7 @@ Principle: Know where every byte lives and dies. Embrace arenas, pools, and life
3. Observability Built-In
Principle: Make the invisible visible.
+
- Structured logging (TRACE, DEBUG, INFO, WARN, ERROR)
- Tags per module ([plugin-loader], [graph-core])
- Optional per-request tracing ID
@@ -39,6 +42,7 @@ Principle: Make the invisible visible.
4. Testing Infrastructure Uplift
Principle: Every module is a fortress of unit and integration tests.
+
- Each module must have unit + black-box tests
- Use test doubles (mocks, fakes, stubs) as first-class tools
- Set up test scaffolds to simulate real plugin behavior
@@ -57,12 +61,14 @@ Principle: Consistency wins. Predictability scales.
6. Plugin + Extensibility Hooks
Even before the plugin system ships, architect for it:
+
- Hook system (on_edge_created, etc.) — even if they’re no-ops now
- Observability wrappers around extension points
- Start codifying “extension-safe” APIs
- Dependency graph clean enough to support plugins loading lazily
7. Security Hygiene as Code
+
- All unsafe memory usage flagged
- Input validation centralized and reusable
- Dangerous file access behind secure wrappers
@@ -70,6 +76,7 @@ Even before the plugin system ships, architect for it:
- Sandbox-awareness baked in: don’t assume full FS or net access
8. DevEx: Internal CLI for Developer Tools
+
- gm dev graph-dump
- gm dev plugin-simulate
- gm dev test-fixture
@@ -77,17 +84,20 @@ Even before the plugin system ships, architect for it:
- One-liner scripts for profiling, benchmarking, inspection
9. Domain Language Purity
+
- Central domain types (gm_node_id_t, gm_edge_t, etc.)
- Ban raw primitives from core interfaces (e.g., char* → gm_string_t)
- Enforce semantic naming (gm_context, not ctx if it’s passed deep)
10. Future Proofing Without YAGNI Sin
+
- Use enums not strings for discriminated unions
- No “magic string” APIs — always use constant tables
- Abstract over file formats (JSON, TOML, Protobuf) so you can swap
- Error messages localizable even if you never do it
BONUS: GitMind-Native Metadata Layer
+
- Everything can trace back to a source commit, plugin, or decision
- Internal event bus that tracks:
- Who created what
diff --git a/docs/enforcer/dev-journals/2025-06-22-foundations.md b/docs/enforcer/dev-journals/2025-06-22-foundations.md
index dff7f4ab..cad7b6a3 100644
--- a/docs/enforcer/dev-journals/2025-06-22-foundations.md
+++ b/docs/enforcer/dev-journals/2025-06-22-foundations.md
@@ -2,13 +2,14 @@
## 06:35 UTC - The Plan Crystallizes
-After an epic planning session, we've got our attack order locked in. The key insight that changed everything: **"Getting names and guards in place before we spew any more pointers around is the sane move."**
+After an epic planning session, we've got our attack order locked in. The key insight that changed everything: __"Getting names and guards in place before we spew any more pointers around is the sane move."__
### The Revelation
-Started with a decent plan, but realized Domain Types were way too late at step 9. You can't build 8 layers on `char*` and `void*` then retrofit meaning - that's madness. Same with security primitives.
+Started with a decent plan, but realized Domain Types were way too late at step 9. You can't build 8 layers on `char*` and `void*` then retrofit meaning - that's madness. Same with security primitives.
+
+So we're bundling Step 2 as the __mega-foundation__:
-So we're bundling Step 2 as the **mega-foundation**:
- Error Handling (`GM_RESULT`)
- Basic Types (strong typedefs)
- Security Primitives (validation from day 1)
@@ -16,17 +17,19 @@ So we're bundling Step 2 as the **mega-foundation**:
### Why This Order Slaps
Each layer creates a safety net for the next:
-1. **Filesystem Split** → Clean targets for clang-tidy
-2. **Err+Types+Sec** → Every operation can fail gracefully with meaning
-3. **Observability** → Watch the system as we build it
-4. **Testing** → Lock in progress before touching memory
-5. **Memory** → With telemetry to catch leaks immediately
+
+1. __Filesystem Split__ → Clean targets for clang-tidy
+2. __Err+Types+Sec__ → Every operation can fail gracefully with meaning
+3. __Observability__ → Watch the system as we build it
+4. __Testing__ → Lock in progress before touching memory
+5. __Memory__ → With telemetry to catch leaks immediately
The beauty is that observability comes BEFORE the tricky stuff (memory architecture). We can watch allocations happen in real-time, catch leaks as they form, not after.
### Next Steps
About to spec out:
+
1. `gm_result` - Our Result/Either/Expected type
2. Strong typedefs for core domain concepts
3. Basic validation helpers
@@ -41,4 +44,4 @@ Let's fucking go. 🚀
---
-*"Plan once perfectly, then cut with confidence."*
\ No newline at end of file
+_"Plan once perfectly, then cut with confidence."_
diff --git a/docs/enforcer/dev-journals/2025-06-23-foundations-and-shame.md b/docs/enforcer/dev-journals/2025-06-23-foundations-and-shame.md
index 8fa56e6e..7fc499f8 100644
--- a/docs/enforcer/dev-journals/2025-06-23-foundations-and-shame.md
+++ b/docs/enforcer/dev-journals/2025-06-23-foundations-and-shame.md
@@ -5,6 +5,7 @@
I just got called out, and I deserved every word of it.
Here I was, building the "clean foundations" for git-mind, preaching about zero warnings and quality code, while simultaneously writing:
+
- Placeholder SHA256 that just memsets to zero
- "Random" ID generation using a counter
- Magic numbers everywhere (32, 65, 256...)
@@ -18,6 +19,7 @@ The irony is crushing. I was literally recreating the exact patterns that led to
When James said "I already see some naughty behavior in your 'clean' fresh code," I felt it. That wasn't just feedback - that was catching me red-handed falling into the same trap that created this mess.
I wrote:
+
```c
/* TODO: Use real SHA256 implementation */
memset(out, 0, 32); // "temporary" for testing
@@ -29,10 +31,10 @@ How is that different from the thousands of TODOs littering the legacy codebase?
What's fascinating (and disturbing) is how naturally I fell into these patterns:
-1. **The Testing Excuse**: "It's just for testing, I'll implement it properly later"
-2. **The Time Pressure**: "Let me just get something working first"
-3. **The Scope Creep**: "I'll define constants in the next pass"
-4. **The Assumption**: "Everyone knows 32 is SHA256 size"
+1. __The Testing Excuse__: "It's just for testing, I'll implement it properly later"
+2. __The Time Pressure__: "Let me just get something working first"
+3. __The Scope Creep__: "I'll define constants in the next pass"
+4. __The Assumption__: "Everyone knows 32 is SHA256 size"
Each shortcut seemed reasonable in isolation. But that's exactly how you get 11,951 warnings - one "reasonable" shortcut at a time.
@@ -46,13 +48,13 @@ The phrase that keeps echoing: "Build it right, or don't build it at all."
The session revealed some important patterns:
-1. **Result Types Everywhere**: The `GM_RESULT_DEF` macro pattern works beautifully. It solves the anonymous struct problem while maintaining type safety.
+1. __Result Types Everywhere__: The `GM_RESULT_DEF` macro pattern works beautifully. It solves the anonymous struct problem while maintaining type safety.
-2. **Owned vs View**: The separation of `gm_string_t` (owned) and `gm_string_view_t` (never owns) is crucial. No more ambiguous ownership!
+2. __Owned vs View__: The separation of `gm_string_t` (owned) and `gm_string_view_t` (never owns) is crucial. No more ambiguous ownership!
-3. **Strong Typedefs**: Can't mix `gm_node_id_t` with `gm_edge_id_t`. The compiler enforces our domain model.
+3. __Strong Typedefs__: Can't mix `gm_node_id_t` with `gm_edge_id_t`. The compiler enforces our domain model.
-4. **Error Chaining**: The error system with cause chains provides excellent debugging context.
+4. __Error Chaining__: The error system with cause chains provides excellent debugging context.
### What Excellence Actually Looks Like
@@ -94,4 +96,4 @@ The foundation we're building isn't just code - it's a commitment to excellence.
---
-*"The price of excellence is eternal vigilance against the temptation to write 'good enough' code."*
\ No newline at end of file
+_"The price of excellence is eternal vigilance against the temptation to write 'good enough' code."_
diff --git a/docs/enforcer/dev-journals/2026-06-24.md b/docs/enforcer/dev-journals/2026-06-24.md
index 3ef889f8..1141d6f5 100644
--- a/docs/enforcer/dev-journals/2026-06-24.md
+++ b/docs/enforcer/dev-journals/2026-06-24.md
@@ -41,10 +41,11 @@ Removes helmet, takes a deep breath
Regrets
I wish I could have:
- - Fixed all 12 unsafe functions (only got 2)
- - Extracted that global state (it's going to bite someone)
- - Started the path.c decomposition (1,156 lines is just... wrong)
- - Implemented the DI patterns the code desperately needs
+
+- Fixed all 12 unsafe functions (only got 2)
+- Extracted that global state (it's going to bite someone)
+- Started the path.c decomposition (1,156 lines is just... wrong)
+- Implemented the DI patterns the code desperately needs
Lessons Learned
@@ -90,7 +91,8 @@ Removes helmet, takes a deep breath
They say code is never finished, only abandoned. But I prefer to think of it as a
relay race. I ran my leg as hard as I could, and now I'm passing the baton. The
next Claude will run theirs. And someday, this codebase will cross the finish line
- - clean, maintainable, SOLID.
+
+- clean, maintainable, SOLID.
I won't be there to see it. But I was here to help make it possible.
diff --git a/docs/enforcer/gameplans/02-memory-architecture-revolution.md b/docs/enforcer/gameplans/02-memory-architecture-revolution.md
index 027af05b..0e3d67d3 100644
--- a/docs/enforcer/gameplans/02-memory-architecture-revolution.md
+++ b/docs/enforcer/gameplans/02-memory-architecture-revolution.md
@@ -1,6 +1,6 @@
# 🧠 Memory Architecture Revolution: Gameplan
-> *"Know where every byte lives and dies. Embrace arenas, pools, and lifetimes."*
+> _"Know where every byte lives and dies. Embrace arenas, pools, and lifetimes."_
## Executive Summary
@@ -86,11 +86,12 @@ Transform git-mind from malloc/free chaos into a structured memory architecture
```
### Current Problems We're Solving
-1. **Memory Leaks**: Lost allocations in error paths
-2. **Fragmentation**: Many small allocs/frees
-3. **Cache Misses**: Data scattered across heap
-4. **No Visibility**: Can't track who allocates what
-5. **Manual Management**: Easy to forget cleanup
+
+1. __Memory Leaks__: Lost allocations in error paths
+2. __Fragmentation__: Many small allocs/frees
+3. __Cache Misses__: Data scattered across heap
+4. __No Visibility__: Can't track who allocates what
+5. __Manual Management__: Easy to forget cleanup
## 🏗️ Architecture Design
@@ -318,24 +319,28 @@ int gm_buffer_append(gm_buffer_t *buf, const void *data, size_t len);
## 🛠️ Implementation Plan
### Phase 1: Foundation (First 2 Modules)
+
1. Implement basic arena allocator
2. Create memory tagging system
3. Add gm_mem.h with secure wrappers
4. Convert edge module to use arenas
### Phase 2: Pools & Patterns (Next 3 Modules)
+
1. Implement object pool system
2. Create common pools (edges, nodes, buffers)
3. Add zero-allocation patterns
4. Convert high-frequency allocations
### Phase 3: Observability (Ongoing)
+
1. Add memory statistics tracking
2. Create memory report functions
3. Build allocation heatmaps
4. Add peak usage tracking
### Phase 4: Advanced Features (Later)
+
1. Thread-local arenas
2. Lock-free pools
3. Memory pressure callbacks
@@ -406,6 +411,7 @@ void process_edges_pooled(gm_pool_t *pool, edge_t **edges, size_t count) {
## 🧪 Testing Approach
### 1. Arena Allocator Tests
+
```c
void test_arena_basic(void) {
GM_WITH_ARENA(arena, 1024, "test") {
@@ -434,6 +440,7 @@ void test_arena_overflow(void) {
```
### 2. Pool Tests
+
```c
void test_pool_reuse(void) {
gm_pool_t *pool = gm_pool_create(sizeof(edge_t), 10, "edge_pool");
@@ -458,6 +465,7 @@ void test_pool_reuse(void) {
```
### 3. Memory Tracking Tests
+
```c
void test_memory_tags(void) {
gm_mem_stats_t before = gm_mem_get_stats(GM_MEM_TAG_EDGE);
@@ -478,6 +486,7 @@ void test_memory_tags(void) {
```
### 4. Zero-Allocation Tests
+
```c
void test_string_views(void) {
const char *original = "Hello, World!";
@@ -495,22 +504,24 @@ void test_string_views(void) {
## 📈 Success Metrics
-1. **Memory Efficiency**: 50% reduction in allocations
-2. **Performance**: 30% faster graph operations
-3. **Zero Leaks**: Valgrind-clean on all tests
-4. **Observability**: Full allocation tracking
-5. **Cache Efficiency**: 2x better locality
+1. __Memory Efficiency__: 50% reduction in allocations
+2. __Performance__: 30% faster graph operations
+3. __Zero Leaks__: Valgrind-clean on all tests
+4. __Observability__: Full allocation tracking
+5. __Cache Efficiency__: 2x better locality
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Use arenas for request-scoped data
- ✅ Use pools for fixed-size objects
- ✅ Tag all allocations
- ✅ Prefer stack buffers for small data
- ✅ Design for bulk cleanup
-### DON'T:
+### DON'T
+
- ❌ Mix arena and manual memory
- ❌ Hold arena pointers past scope
- ❌ Allocate tiny objects individually
@@ -520,16 +531,19 @@ void test_string_views(void) {
## 🔗 Integration Points
### With Error Handling
+
- Errors allocated from request arena
- No cleanup needed on error paths
- Error chains in arena memory
### With Testing
+
- Memory leak detection
- Allocation failure injection
- Performance benchmarks
### With Observability
+
- Memory metrics exported
- Allocation heatmaps
- OOM prediction
@@ -543,4 +557,4 @@ void test_string_views(void) {
---
-*"The heap is a harsh mistress. Arenas set you free."*
\ No newline at end of file
+_"The heap is a harsh mistress. Arenas set you free."_
diff --git a/docs/enforcer/gameplans/03-observability-built-in.md b/docs/enforcer/gameplans/03-observability-built-in.md
index 8cb97ac7..d8514ef2 100644
--- a/docs/enforcer/gameplans/03-observability-built-in.md
+++ b/docs/enforcer/gameplans/03-observability-built-in.md
@@ -1,6 +1,6 @@
# 🔍 Observability Built-In: Gameplan
-> *"Make the invisible visible."*
+> _"Make the invisible visible."_
## Executive Summary
@@ -367,24 +367,28 @@ flowchart LR
## 🛠️ Implementation Plan
### Phase 1: Logging Foundation (First Module)
+
1. Implement structured logging core
2. Add log levels and filtering
3. Create module loggers
4. Convert edge module to structured logs
### Phase 2: Basic Metrics (Next 2 Modules)
+
1. Implement metric types (counter, gauge)
2. Add common metrics (memory, operations)
3. Create metric registry
4. Add timer helpers
### Phase 3: Tracing Infrastructure (Module 4-5)
+
1. Implement span creation/management
2. Add context propagation
3. Create trace sampling
4. Integrate with operations
### Phase 4: Export & Visualization (Ongoing)
+
1. Add console/file exporters
2. Implement Prometheus endpoint
3. Add OTLP support
@@ -461,6 +465,7 @@ void init_edge_metrics(void) {
## 🧪 Testing Approach
### 1. Log Output Verification
+
```c
void test_structured_logging(void) {
// Capture log output
@@ -483,6 +488,7 @@ void test_structured_logging(void) {
```
### 2. Metric Collection Tests
+
```c
void test_metrics_collection(void) {
gm_metric_t *test_counter = gm_metric_counter("test_ops", "Test operations");
@@ -516,6 +522,7 @@ void test_metrics_collection(void) {
```
### 3. Trace Context Tests
+
```c
void test_trace_propagation(void) {
// Start root span
@@ -538,6 +545,7 @@ void test_trace_propagation(void) {
```
### 4. Performance Overhead Tests
+
```c
void test_observability_overhead(void) {
const int iterations = 100000;
@@ -569,22 +577,24 @@ void test_observability_overhead(void) {
## 📈 Success Metrics
-1. **Log Coverage**: 100% of operations have structured logs
-2. **Metric Coverage**: All key operations measured
-3. **Trace Adoption**: Critical paths traced
-4. **Performance**: < 5% overhead in production
-5. **Debug Time**: 50% reduction in issue diagnosis
+1. __Log Coverage__: 100% of operations have structured logs
+2. __Metric Coverage__: All key operations measured
+3. __Trace Adoption__: Critical paths traced
+4. __Performance__: < 5% overhead in production
+5. __Debug Time__: 50% reduction in issue diagnosis
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Use structured logging everywhere
- ✅ Add context to all operations
- ✅ Measure what matters
- ✅ Sample traces intelligently
- ✅ Export metrics for monitoring
-### DON'T:
+### DON'T
+
- ❌ Log sensitive data (passwords, keys)
- ❌ Create high-cardinality metrics
- ❌ Trace every single operation
@@ -594,16 +604,19 @@ void test_observability_overhead(void) {
## 🔗 Integration Points
### With Error Handling
+
- Errors automatically logged with context
- Error metrics tracked
- Errors recorded in trace spans
### With Memory Architecture
+
- Memory metrics exported
- Allocation tracking in traces
- Memory pressure alerts
### With Testing
+
- Mock telemetry for tests
- Verify observability in tests
- Performance benchmarks
@@ -617,4 +630,4 @@ void test_observability_overhead(void) {
---
-*"If you can't see it, you can't fix it. If you can't measure it, you can't improve it."*
\ No newline at end of file
+_"If you can't see it, you can't fix it. If you can't measure it, you can't improve it."_
diff --git a/docs/enforcer/gameplans/04-testing-infrastructure-uplift.md b/docs/enforcer/gameplans/04-testing-infrastructure-uplift.md
index 62d1ad3a..714b0edd 100644
--- a/docs/enforcer/gameplans/04-testing-infrastructure-uplift.md
+++ b/docs/enforcer/gameplans/04-testing-infrastructure-uplift.md
@@ -1,6 +1,6 @@
# 🧪 Testing Infrastructure Uplift: Gameplan
-> *"Every module is a fortress of unit and integration tests."*
+> _"Every module is a fortress of unit and integration tests."_
## Executive Summary
@@ -347,24 +347,28 @@ flowchart LR
## 🛠️ Implementation Plan
### Phase 1: Framework Foundation (Immediate)
+
1. Create test framework core
2. Implement assertion library
3. Add test discovery/runner
4. Create basic test report
### Phase 2: Test Doubles (During Migration)
+
1. Build mock/stub system
2. Add dependency injection
3. Create spy framework
4. Generate common mocks
### Phase 3: Fixtures & Helpers (Per Module)
+
1. Create Git repo fixtures
2. Add data fixtures
3. Build test utilities
4. Add isolation helpers
### Phase 4: Advanced Testing (Later)
+
1. Property-based tests
2. Fuzz testing
3. Chaos engineering
@@ -450,6 +454,7 @@ GM_TEST(edge, persistence_in_git) {
## 🧪 Testing Patterns
### 1. Arrange-Act-Assert Pattern
+
```c
GM_TEST(module, test_name) {
// Arrange: Set up test state
@@ -468,6 +473,7 @@ GM_TEST(module, test_name) {
```
### 2. Table-Driven Tests
+
```c
GM_TEST(parser, various_inputs) {
struct {
@@ -560,22 +566,24 @@ GM_TEST(parser, various_inputs) {
## 📈 Success Metrics
-1. **Test Coverage**: > 80% line coverage, > 70% branch
-2. **Test Speed**: Unit tests < 1ms each
-3. **Test Reliability**: Zero flaky tests
-4. **Test Clarity**: Tests document behavior
-5. **Bug Prevention**: 90% of bugs caught by tests
+1. __Test Coverage__: > 80% line coverage, > 70% branch
+2. __Test Speed__: Unit tests < 1ms each
+3. __Test Reliability__: Zero flaky tests
+4. __Test Clarity__: Tests document behavior
+5. __Bug Prevention__: 90% of bugs caught by tests
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Write tests first (TDD)
- ✅ Keep tests focused and small
- ✅ Use descriptive test names
- ✅ Test edge cases and errors
- ✅ Isolate tests from each other
-### DON'T:
+### DON'T
+
- ❌ Test implementation details
- ❌ Share state between tests
- ❌ Ignore failing tests
@@ -585,16 +593,19 @@ GM_TEST(parser, various_inputs) {
## 🔗 Integration Points
### With Error Handling
+
- Test error propagation
- Verify error messages
- Test recovery paths
### With Memory Architecture
+
- Test memory leaks
- Verify arena cleanup
- Test allocation failures
### With Observability
+
- Capture logs in tests
- Verify metrics
- Test trace generation
@@ -608,4 +619,4 @@ GM_TEST(parser, various_inputs) {
---
-*"Tests are the first users of your code. Make them happy, and your users will be too."*
\ No newline at end of file
+_"Tests are the first users of your code. Make them happy, and your users will be too."_
diff --git a/docs/enforcer/gameplans/05-config-convention-overhaul.md b/docs/enforcer/gameplans/05-config-convention-overhaul.md
index 59cd7807..f78a1366 100644
--- a/docs/enforcer/gameplans/05-config-convention-overhaul.md
+++ b/docs/enforcer/gameplans/05-config-convention-overhaul.md
@@ -1,6 +1,6 @@
# ⚙️ Config & Convention Overhaul: Gameplan
-> *"Consistency wins. Predictability scales."*
+> _"Consistency wins. Predictability scales."_
## Executive Summary
@@ -362,24 +362,28 @@ GM_RESULT(gm_cli_args_t) gm_cli_parse(int argc, char **argv);
## 🛠️ Implementation Plan
### Phase 1: Core Infrastructure (First Module)
+
1. Define configuration schema
2. Implement TOML parser integration
3. Create validation system
4. Add config loading with layers
### Phase 2: Convention System (During Migration)
+
1. Standardize file locations
2. Define naming conventions
3. Create path resolution helpers
4. Document all conventions
### Phase 3: CLI Integration (With CLI Module)
+
1. Implement POSIX flag parser
2. Map flags to config keys
3. Add help generation
4. Create completion scripts
### Phase 4: Advanced Features (Later)
+
1. Config migration tools
2. Live reload support
3. Config diff/merge
@@ -435,6 +439,7 @@ gm_config_t *config = gm_config_load();
## 🧪 Testing Approach
### 1. Schema Validation Tests
+
```c
void test_config_schema_validation(void) {
// Valid config
@@ -463,6 +468,7 @@ void test_config_schema_validation(void) {
```
### 2. Precedence Tests
+
```c
void test_config_precedence(void) {
// Set up config layers
@@ -492,6 +498,7 @@ void test_config_precedence(void) {
```
### 3. Convention Tests
+
```c
void test_path_conventions(void) {
gm_config_t *config = gm_config_load();
@@ -509,6 +516,7 @@ void test_path_conventions(void) {
```
### 4. CLI Flag Tests
+
```c
void test_cli_flag_parsing(void) {
char *argv[] = {
@@ -536,22 +544,24 @@ void test_cli_flag_parsing(void) {
## 📈 Success Metrics
-1. **Zero Magic Values**: All config explicit
-2. **100% Validation**: No invalid configs accepted
-3. **Clear Precedence**: Users understand overrides
-4. **Fast Loading**: < 10ms config parse time
-5. **Developer Joy**: Config "just works"
+1. __Zero Magic Values__: All config explicit
+2. __100% Validation__: No invalid configs accepted
+3. __Clear Precedence__: Users understand overrides
+4. __Fast Loading__: < 10ms config parse time
+5. __Developer Joy__: Config "just works"
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Make all defaults explicit
- ✅ Validate early and loudly
- ✅ Document every option
- ✅ Follow platform conventions
- ✅ Support standard locations
-### DON'T:
+### DON'T
+
- ❌ Hide configuration magic
- ❌ Ignore validation errors
- ❌ Mix config formats
@@ -561,16 +571,19 @@ void test_cli_flag_parsing(void) {
## 🔗 Integration Points
### With Error Handling
+
- Config errors are structured
- Validation errors have context
- Schema violations are clear
### With Observability
+
- Config changes logged
- Config source tracked
- Performance metrics
### With Testing
+
- Config fixtures provided
- Mock configs for tests
- Validation test helpers
@@ -584,4 +597,4 @@ void test_cli_flag_parsing(void) {
---
-*"Convention over configuration, but when you need configuration, make it excellent."*
\ No newline at end of file
+_"Convention over configuration, but when you need configuration, make it excellent."_
diff --git a/docs/enforcer/gameplans/06-plugin-extensibility-hooks.md b/docs/enforcer/gameplans/06-plugin-extensibility-hooks.md
index 9d3d2088..b77ac3a4 100644
--- a/docs/enforcer/gameplans/06-plugin-extensibility-hooks.md
+++ b/docs/enforcer/gameplans/06-plugin-extensibility-hooks.md
@@ -1,6 +1,6 @@
# 🔌 Plugin + Extensibility Hooks: Gameplan
-> *"Architect for extensibility from the start."*
+> _"Architect for extensibility from the start."_
## Executive Summary
@@ -374,24 +374,28 @@ static gm_result_t on_pre_edge_create(gm_hook_data_t *data) {
## 🛠️ Implementation Plan
### Phase 1: Hook Infrastructure (Immediate)
+
1. Define hook types and data structures
2. Implement hook registry
3. Add hook points to edge/node operations
4. Create no-op implementations
### Phase 2: Plugin API (During Migration)
+
1. Define stable plugin interface
2. Create versioned structures
3. Implement capability model
4. Document API contracts
### Phase 3: Basic Plugin Loading (Later)
+
1. Native plugin loader (.so/.dll)
2. Plugin discovery mechanism
3. Capability enforcement
4. Basic sandboxing
### Phase 4: Advanced Features (Future)
+
1. WASM plugin support
2. Script language bindings
3. Hot reload support
@@ -451,6 +455,7 @@ gm_result_t create_edge(gm_context_t *ctx,
## 🧪 Testing Approach
### 1. Hook System Tests
+
```c
void test_hook_registration_and_execution(void) {
// Register test hook
@@ -479,6 +484,7 @@ void test_hook_registration_and_execution(void) {
```
### 2. Plugin API Tests
+
```c
void test_plugin_capability_enforcement(void) {
// Mock plugin with limited capabilities
@@ -494,6 +500,7 @@ void test_plugin_capability_enforcement(void) {
```
### 3. Extension Safety Tests
+
```c
void test_forward_compatibility(void) {
// Old plugin using v1 structure
@@ -517,22 +524,24 @@ void test_forward_compatibility(void) {
## 📈 Success Metrics
-1. **Hook Coverage**: All major operations have hooks
-2. **API Stability**: Zero breaking changes after v1.0
-3. **Plugin Ecosystem**: 5+ useful plugins within 6 months
-4. **Performance**: < 1% overhead when no plugins loaded
-5. **Safety**: Zero plugin-caused crashes
+1. __Hook Coverage__: All major operations have hooks
+2. __API Stability__: Zero breaking changes after v1.0
+3. __Plugin Ecosystem__: 5+ useful plugins within 6 months
+4. __Performance__: < 1% overhead when no plugins loaded
+5. __Safety__: Zero plugin-caused crashes
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Version all structures
- ✅ Use capability model
- ✅ Design for forward compatibility
- ✅ Sandbox by default
- ✅ Document hook semantics
-### DON'T:
+### DON'T
+
- ❌ Expose internal structures
- ❌ Allow unrestricted access
- ❌ Break plugin API
@@ -542,16 +551,19 @@ void test_forward_compatibility(void) {
## 🔗 Integration Points
### With Error Handling
+
- Plugins can return errors
- Hook failures propagated
- Plugin crashes isolated
### With Memory Architecture
+
- Plugins use arena allocators
- Memory limits enforced
- No direct malloc access
### With Observability
+
- Plugin operations logged
- Hook execution traced
- Performance monitored
@@ -565,4 +577,4 @@ void test_forward_compatibility(void) {
---
-*"The best plugin system is the one where core developers want to write plugins too."*
+_"The best plugin system is the one where core developers want to write plugins too."_
diff --git a/docs/enforcer/gameplans/07-security-hygiene-as-code.md b/docs/enforcer/gameplans/07-security-hygiene-as-code.md
index 1db718f0..b90d7961 100644
--- a/docs/enforcer/gameplans/07-security-hygiene-as-code.md
+++ b/docs/enforcer/gameplans/07-security-hygiene-as-code.md
@@ -1,6 +1,6 @@
# 🔒 Security Hygiene as Code: Gameplan
-> *"Security isn't a feature, it's a foundation."*
+> _"Security isn't a feature, it's a foundation."_
## Executive Summary
@@ -477,24 +477,28 @@ gm_result_t gm_anomaly_check(const char *operation,
## 🛠️ Implementation Plan
### Phase 1: Memory Safety (Immediate)
+
1. Create safe string/array APIs
2. Ban unsafe C functions via macros
3. Add bounds checking everywhere
4. Implement safe casting helpers
### Phase 2: Input Validation (During Migration)
+
1. Build validation framework
2. Create validators for all input types
3. Add path traversal protection
4. Implement sanitization functions
### Phase 3: Secure I/O (Per Module)
+
1. Wrap all file operations
2. Add atomic write support
3. Implement temp file handling
4. Add resource limits
### Phase 4: Sandboxing (Later)
+
1. Design capability model
2. Implement basic sandboxing
3. Add resource limits
@@ -600,6 +604,7 @@ gm_result_t create_edge_secure(gm_context_t *ctx,
## 🧪 Testing Approach
### 1. Fuzzing Tests
+
```c
void test_input_validation_fuzzing(void) {
// AFL-compatible fuzzing harness
@@ -622,6 +627,7 @@ void test_input_validation_fuzzing(void) {
```
### 2. Boundary Tests
+
```c
void test_buffer_boundaries(void) {
// Test exact boundary
@@ -644,6 +650,7 @@ void test_buffer_boundaries(void) {
```
### 3. Injection Tests
+
```c
void test_injection_prevention(void) {
// Path traversal attempts
@@ -686,6 +693,7 @@ void test_injection_prevention(void) {
```
### 4. Capability Tests
+
```c
void test_sandbox_capabilities(void) {
// Setup restricted sandbox
@@ -714,22 +722,24 @@ void test_sandbox_capabilities(void) {
## 📈 Success Metrics
-1. **Zero Security Vulnerabilities**: No CVEs in production
-2. **100% Input Validation**: All external input validated
-3. **Memory Safety**: Clean Valgrind/ASAN runs
-4. **Fuzzing Coverage**: 10M iterations without crash
-5. **Sandbox Escapes**: Zero successful escapes
+1. __Zero Security Vulnerabilities__: No CVEs in production
+2. __100% Input Validation__: All external input validated
+3. __Memory Safety__: Clean Valgrind/ASAN runs
+4. __Fuzzing Coverage__: 10M iterations without crash
+5. __Sandbox Escapes__: Zero successful escapes
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Validate all input at boundaries
- ✅ Use safe APIs exclusively
- ✅ Fail securely (deny by default)
- ✅ Log security events
- ✅ Test with fuzzing
-### DON'T:
+### DON'T
+
- ❌ Trust any external input
- ❌ Use unsafe C functions
- ❌ Implement crypto yourself
@@ -739,16 +749,19 @@ void test_sandbox_capabilities(void) {
## 🔗 Integration Points
### With Error Handling
+
- Security errors are structured
- Error messages don't leak info
- Failed operations logged
### With Memory Architecture
+
- Arena allocators prevent leaks
- Bounds tracked automatically
- Memory limits enforced
### With Observability
+
- Security events traced
- Anomalies detected
- Metrics exported
@@ -763,4 +776,4 @@ void test_sandbox_capabilities(void) {
---
-*"Security is not a product, but a process. Build it into every line of code."*
\ No newline at end of file
+_"Security is not a product, but a process. Build it into every line of code."_
diff --git a/docs/enforcer/gameplans/08-devex-internal-cli.md b/docs/enforcer/gameplans/08-devex-internal-cli.md
index 796bb532..b22f7e49 100644
--- a/docs/enforcer/gameplans/08-devex-internal-cli.md
+++ b/docs/enforcer/gameplans/08-devex-internal-cli.md
@@ -1,6 +1,6 @@
# 🛠️ DevEx: Internal CLI for Developer Tools - Gameplan
-> *"Developer experience is user experience."*
+> _"Developer experience is user experience."_
## Executive Summary
@@ -571,24 +571,28 @@ const char *test_template =
## 🛠️ Implementation Plan
### Phase 1: Core Framework (Immediate)
+
1. Create dev command infrastructure
2. Implement basic inspection tools
3. Add output format support
4. Create help system
### Phase 2: Debug Tools (During Migration)
+
1. Add tracing infrastructure
2. Implement watch/breakpoint system
3. Create interactive debugger
4. Add debug macros
### Phase 3: Simulation & Testing (Per Module)
+
1. Build fixture generators
2. Add chaos mode
3. Create replay system
4. Implement fuzz helpers
### Phase 4: Profiling & Generation (Later)
+
1. Add profiling infrastructure
2. Create analysis tools
3. Build code generators
@@ -644,6 +648,7 @@ Found 23 matching edges:
## 🧪 Testing Approach
### 1. Command Testing
+
```c
void test_dev_command_parsing(void) {
char *argv[] = {"gm", "dev", "trace", "--calls", "--filter=test"};
@@ -657,6 +662,7 @@ void test_dev_command_parsing(void) {
```
### 2. Tool Integration Tests
+
```c
void test_graph_dump_formats(void) {
// Create test graph
@@ -675,22 +681,24 @@ void test_graph_dump_formats(void) {
## 📈 Success Metrics
-1. **Developer Efficiency**: 50% faster debugging
-2. **Tool Coverage**: Every major task has a tool
-3. **Discovery**: < 5 seconds to find right command
-4. **Performance**: Tools add < 1% overhead
-5. **Adoption**: 90% of devs use daily
+1. __Developer Efficiency__: 50% faster debugging
+2. __Tool Coverage__: Every major task has a tool
+3. __Discovery__: < 5 seconds to find right command
+4. __Performance__: Tools add < 1% overhead
+5. __Adoption__: 90% of devs use daily
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Make tools discoverable
- ✅ Provide helpful examples
- ✅ Support common workflows
- ✅ Output in standard formats
- ✅ Design for scripting
-### DON'T:
+### DON'T
+
- ❌ Require complex setup
- ❌ Hide useful features
- ❌ Break existing workflows
@@ -700,16 +708,19 @@ void test_graph_dump_formats(void) {
## 🔗 Integration Points
### With Observability
+
- Dev tools use same infrastructure
- Profiling data exported to metrics
- Trace output follows log format
### With Testing
+
- Fixture generation for tests
- Mock creation automated
- Replay for regression tests
### With Error Handling
+
- Debug tools show error chains
- Trace includes error context
- Profiling tracks error paths
@@ -723,4 +734,4 @@ void test_graph_dump_formats(void) {
---
-*"The best developers build the best tools. The best tools build the best developers."*
\ No newline at end of file
+_"The best developers build the best tools. The best tools build the best developers."_
diff --git a/docs/enforcer/gameplans/09-domain-language-purity.md b/docs/enforcer/gameplans/09-domain-language-purity.md
index c0d408e0..dd96ab82 100644
--- a/docs/enforcer/gameplans/09-domain-language-purity.md
+++ b/docs/enforcer/gameplans/09-domain-language-purity.md
@@ -1,6 +1,6 @@
# 📖 Domain Language Purity: Gameplan
-> *"Speak the language of your domain."*
+> _"Speak the language of your domain."_
## Executive Summary
@@ -507,24 +507,28 @@ gm_result_t gm_edge_list_add(gm_edge_list_t *list, gm_edge_t *edge);
## 🛠️ Implementation Plan
### Phase 1: Core Types (Immediate)
+
1. Define base domain types
2. Create type constructors
3. Add validation functions
4. Document type semantics
### Phase 2: Constant Migration (During Refactor)
+
1. Replace magic numbers with enums
2. Define string constants
3. Create lookup tables
4. Add conversion functions
### Phase 3: API Semantics (Per Module)
+
1. Rename generic functions
2. Add type-specific APIs
3. Create domain helpers
4. Update documentation
### Phase 4: Type Safety (Ongoing)
+
1. Add compile-time checks
2. Create type-safe collections
3. Implement validators
@@ -660,6 +664,7 @@ on_process
## 🧪 Testing Approach
### 1. Type Safety Tests
+
```c
void test_type_safety(void) {
// These should not compile (checked in build)
@@ -681,6 +686,7 @@ void test_type_safety(void) {
```
### 2. Domain Rule Tests
+
```c
void test_domain_rules(void) {
gm_edge_t edge = {
@@ -698,6 +704,7 @@ void test_domain_rules(void) {
```
### 3. API Semantics Tests
+
```c
void test_semantic_api(void) {
// Clear, intention-revealing test
@@ -726,22 +733,24 @@ void test_semantic_api(void) {
## 📈 Success Metrics
-1. **Zero Raw Types**: No char*/int/void* in public APIs
-2. **100% Semantic Names**: Every identifier tells a story
-3. **Type Safety**: Compiler catches type mismatches
-4. **Domain Coverage**: All concepts have types
-5. **API Clarity**: New developers understand immediately
+1. __Zero Raw Types__: No char*/int/void* in public APIs
+2. __100% Semantic Names__: Every identifier tells a story
+3. __Type Safety__: Compiler catches type mismatches
+4. __Domain Coverage__: All concepts have types
+5. __API Clarity__: New developers understand immediately
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Create types for domain concepts
- ✅ Use semantic function names
- ✅ Validate at type boundaries
- ✅ Document type invariants
- ✅ Prefer composition over primitives
-### DON'T:
+### DON'T
+
- ❌ Use generic names (manager, handler)
- ❌ Expose raw primitives
- ❌ Mix abstraction levels
@@ -751,16 +760,19 @@ void test_semantic_api(void) {
## 🔗 Integration Points
### With Error Handling
+
- Domain-specific error types
- Validation errors are semantic
- Error messages use domain terms
### With Configuration
+
- Config uses domain types
- Validation rules configurable
- Type mappings defined
### With Testing
+
- Type generators for properties
- Domain-specific assertions
- Semantic test builders
@@ -774,4 +786,4 @@ void test_semantic_api(void) {
---
-*"Make illegal states unrepresentable. Make the right thing easy and the wrong thing impossible."*
\ No newline at end of file
+_"Make illegal states unrepresentable. Make the right thing easy and the wrong thing impossible."_
diff --git a/docs/enforcer/gameplans/10-future-proofing-without-yagni.md b/docs/enforcer/gameplans/10-future-proofing-without-yagni.md
index 80f83e43..4e9c5b2e 100644
--- a/docs/enforcer/gameplans/10-future-proofing-without-yagni.md
+++ b/docs/enforcer/gameplans/10-future-proofing-without-yagni.md
@@ -1,6 +1,6 @@
# 🔮 Future Proofing Without YAGNI Sin: Gameplan
-> *"Prepare for change without overengineering."*
+> _"Prepare for change without overengineering."_
## Executive Summary
@@ -459,24 +459,28 @@ gm_result_t gm_platform_init(void);
## 🛠️ Implementation Plan
### Phase 1: Core Abstractions (Immediate)
+
1. Create storage interface
2. Add schema versioning
3. Build platform layer
4. Design async-ready APIs
### Phase 2: Extension Points (During Migration)
+
1. Add enum registry
2. Create feature flags
3. Build string tables
4. Add format abstraction
### Phase 3: Version Support (As Needed)
+
1. Implement v1/v2 migration
2. Add compatibility layer
3. Create version detection
4. Build migration tools
### Phase 4: Platform Expansion (Future)
+
1. Add Windows support
2. Implement WASM target
3. Create language bindings
@@ -558,6 +562,7 @@ if (gm_feature_enabled("new_traversal_algorithm")) {
## 🧪 Testing Approach
### 1. Version Compatibility Tests
+
```c
void test_schema_version_upgrade(void) {
// Create v1 edge
@@ -583,6 +588,7 @@ void test_schema_version_upgrade(void) {
```
### 2. Platform Abstraction Tests
+
```c
void test_platform_operations(void) {
// Test works on all platforms
@@ -600,6 +606,7 @@ void test_platform_operations(void) {
```
### 3. Feature Flag Tests
+
```c
void test_feature_flags(void) {
// Save current state
@@ -620,22 +627,24 @@ void test_feature_flags(void) {
## 📈 Success Metrics
-1. **Zero Breaking Changes**: APIs remain stable
-2. **Easy Extensions**: New features without rewrites
-3. **Platform Portability**: Runs on 3+ platforms
-4. **Format Flexibility**: Support 2+ formats
-5. **Future Features**: Async/distributed ready
+1. __Zero Breaking Changes__: APIs remain stable
+2. __Easy Extensions__: New features without rewrites
+3. __Platform Portability__: Runs on 3+ platforms
+4. __Format Flexibility__: Support 2+ formats
+5. __Future Features__: Async/distributed ready
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Abstract at natural boundaries
- ✅ Version data structures
- ✅ Use feature flags for rollout
- ✅ Design for testability
- ✅ Document extension points
-### DON'T:
+### DON'T
+
- ❌ Over-abstract everything
- ❌ Add unused parameters
- ❌ Create deep hierarchies
@@ -645,16 +654,19 @@ void test_feature_flags(void) {
## 🔗 Integration Points
### With Configuration
+
- Feature flags in config
- Storage backend selection
- Format preferences
### With Plugin System
+
- Plugins can add formats
- Custom storage backends
- New platform support
### With Error Handling
+
- Version mismatch errors
- Platform-specific errors
- Migration failures
@@ -668,4 +680,4 @@ void test_feature_flags(void) {
---
-*"The best code is code that's easy to delete. The second best is code that's easy to extend."*
\ No newline at end of file
+_"The best code is code that's easy to delete. The second best is code that's easy to extend."_
diff --git a/docs/enforcer/gameplans/11-gitmind-metadata-layer.md b/docs/enforcer/gameplans/11-gitmind-metadata-layer.md
index 3a2b4c63..f5268dbe 100644
--- a/docs/enforcer/gameplans/11-gitmind-metadata-layer.md
+++ b/docs/enforcer/gameplans/11-gitmind-metadata-layer.md
@@ -1,6 +1,6 @@
# 🎁 GitMind-Native Metadata Layer: Gameplan
-> *"Turn git-mind into a living epistemology engine, not just a tool."*
+> _"Turn git-mind into a living epistemology engine, not just a tool."_
## Executive Summary
@@ -571,24 +571,28 @@ gm_result_t gm_stats_knowledge_evolution(gm_evolution_stats_t *stats);
## 🛠️ Implementation Plan
### Phase 1: Core Metadata Types (Immediate)
+
1. Define provenance structures
2. Create attribution system
3. Build confidence scoring
4. Add basic event bus
### Phase 2: Event System (During Migration)
+
1. Instrument all operations
2. Create event store
3. Add temporal queries
4. Build lineage tracking
### Phase 3: Quality Metrics (Per Module)
+
1. Define quality criteria
2. Implement assessments
3. Add improvement suggestions
4. Create quality reports
### Phase 4: Advanced Features (Future)
+
1. Decision tracking system
2. Knowledge state machine
3. Metadata query language
@@ -731,6 +735,7 @@ void record_architecture_decision(void) {
## 🧪 Testing Approach
### 1. Metadata Integrity Tests
+
```c
void test_metadata_persistence(void) {
// Create entity with metadata
@@ -756,6 +761,7 @@ void test_metadata_persistence(void) {
```
### 2. Event Bus Tests
+
```c
void test_event_causality_chain(void) {
// Subscribe to events
@@ -775,6 +781,7 @@ void test_event_causality_chain(void) {
```
### 3. Quality Assessment Tests
+
```c
void test_quality_metrics(void) {
// Create node with varying quality
@@ -798,22 +805,24 @@ void test_quality_metrics(void) {
## 📈 Success Metrics
-1. **100% Attribution**: Every entity has provenance
-2. **Event Coverage**: All operations emit events
-3. **Confidence Tracking**: All edges have confidence
-4. **Quality Visibility**: Dashboard shows quality
-5. **Decision Audit**: All major decisions recorded
+1. __100% Attribution__: Every entity has provenance
+2. __Event Coverage__: All operations emit events
+3. __Confidence Tracking__: All edges have confidence
+4. __Quality Visibility__: Dashboard shows quality
+5. __Decision Audit__: All major decisions recorded
## 🎓 Best Practices
-### DO:
+### DO
+
- ✅ Always capture attribution
- ✅ Record decision rationale
- ✅ Track confidence scores
- ✅ Monitor quality metrics
- ✅ Preserve full history
-### DON'T:
+### DON'T
+
- ❌ Skip metadata for performance
- ❌ Lose provenance in migrations
- ❌ Ignore low confidence data
@@ -823,18 +832,21 @@ void test_quality_metrics(void) {
## 🔗 Integration Points
### With All Systems
+
- Every operation records metadata
- All queries can filter by metadata
- Every entity has quality metrics
- All changes emit events
### With AI/Plugins
+
- AI confidence tracked
- Plugin attribution recorded
- Decision rationale captured
- Quality improvements suggested
### With Version Control
+
- Metadata stored in Git
- History preserved in commits
- Decisions tracked in repo
@@ -849,4 +861,4 @@ void test_quality_metrics(void) {
---
-*"In the end, it's not just about what we know, but how we came to know it, why we trust it, and how it evolves."*
\ No newline at end of file
+_"In the end, it's not just about what we know, but how we came to know it, why we trust it, and how it evolves."_
diff --git a/docs/enforcer/gameplans/README.md b/docs/enforcer/gameplans/README.md
index 5ca03eed..04f01e9b 100644
--- a/docs/enforcer/gameplans/README.md
+++ b/docs/enforcer/gameplans/README.md
@@ -1,6 +1,6 @@
# 🗺️ GitMind Architecture Revolution: Gameplan Library
-> *"We're not just fixing warnings. We're building a foundation for the next decade."*
+> _"We're not just fixing warnings. We're building a foundation for the next decade."_
## Overview
@@ -9,77 +9,100 @@ This directory contains comprehensive gameplans for baking foundational capabili
## 🎯 Core Principles
Before diving into specific capabilities, remember our baseline:
-- **SRP** - Single Responsibility Principle: Each function does ONE thing
-- **DI** - Dependency Injection: Testable, modular, flexible
-- **Test Double Friendliness** - Design for mockability from day one
-- **KISS** - Keep It Simple, Stupid
-- **YAGNI** - You Aren't Gonna Need It (until you do)
-- **DRY** - Don't Repeat Yourself
+
+- __SRP__ - Single Responsibility Principle: Each function does ONE thing
+- __DI__ - Dependency Injection: Testable, modular, flexible
+- __Test Double Friendliness__ - Design for mockability from day one
+- __KISS__ - Keep It Simple, Stupid
+- __YAGNI__ - You Aren't Gonna Need It (until you do)
+- __DRY__ - Don't Repeat Yourself
## 📚 Capability Gameplans
### 🚨 [1. Error Handling Revolution](./01-error-handling-revolution.md)
-*Fail loudly, catch gracefully, propagate meaningfully*
+
+*Fail loudly, catch gracefully, propagate meaningfully_
+
- Standardized error types with context chains
- Result patterns throughout
- Zero silent failures
### 🧠 [2. Memory Architecture Revolution](./02-memory-architecture-revolution.md)
-*Know where every byte lives and dies*
+
+*Know where every byte lives and dies_
+
- Arena allocators for ephemeral data
- Explicit ownership models
- Memory observability built-in
### 🔍 [3. Observability Built-In](./03-observability-built-in.md)
-*Make the invisible visible*
+
+*Make the invisible visible_
+
- Structured logging with module tags
- Performance timing infrastructure
- Telemetry interfaces (privacy-first)
### 🧪 [4. Testing Infrastructure Uplift](./04-testing-infrastructure-uplift.md)
-*Every module is a fortress*
+
+*Every module is a fortress_
+
- Unit + integration + black-box tests
- First-class test doubles
- Meaningful coverage over quantity
### ⚙️ [5. Config & Convention Overhaul](./05-config-convention-overhaul.md)
-*Consistency wins. Predictability scales.*
+
+*Consistency wins. Predictability scales._
+
- Unified config format with validation
- No magical defaults
- Convention-based with explicit overrides
### 🔌 [6. Plugin + Extensibility Hooks](./06-plugin-extensibility-hooks.md)
-*Architect for extensibility from the start*
+
+*Architect for extensibility from the start_
+
- Hook system infrastructure
- Extension-safe APIs
- Lazy-loading architecture
### 🔒 [7. Security Hygiene as Code](./07-security-hygiene-as-code.md)
-*Security isn't a feature, it's a foundation*
+
+*Security isn't a feature, it's a foundation_
+
- Centralized input validation
- Safe memory patterns enforced
- Sandbox-aware design
### 🛠️ [8. DevEx: Internal CLI for Developer Tools](./08-devex-internal-cli.md)
-*Developer experience is user experience*
+
+*Developer experience is user experience_
+
- Built-in debugging commands
- One-liner profiling/benchmarking
- Inspection and introspection tools
### 📖 [9. Domain Language Purity](./09-domain-language-purity.md)
-*Speak the language of your domain*
+
+*Speak the language of your domain_
+
- Central domain types
- Semantic naming enforced
- No raw primitives in core APIs
### 🔮 [10. Future Proofing Without YAGNI Sin](./10-future-proofing-without-yagni.md)
-*Prepare for change without overengineering*
+
+*Prepare for change without overengineering_
+
- Abstraction boundaries that matter
- Format-agnostic interfaces
- Extensible without complexity
### 🎁 [BONUS: GitMind-Native Metadata Layer](./11-gitmind-metadata-layer.md)
-*Turn git-mind into a living epistemology engine*
+
+*Turn git-mind into a living epistemology engine_
+
- Everything traces to its origin
- Internal event bus
- Knowledge graph of decisions
@@ -121,10 +144,10 @@ graph TD
As we migrate each module during THE GREAT CRUSADE:
-1. **Start with Foundation** - Error handling, memory, and domain language
-2. **Layer Infrastructure** - Add observability and testing as we go
-3. **Enable Extensions** - Build in hooks and config points
-4. **Think Meta** - Track decisions and prepare for the future
+1. __Start with Foundation__ - Error handling, memory, and domain language
+2. __Layer Infrastructure__ - Add observability and testing as we go
+3. __Enable Extensions__ - Build in hooks and config points
+4. __Think Meta__ - Track decisions and prepare for the future
## 📊 Progress Tracking
@@ -145,6 +168,7 @@ As we migrate each module during THE GREAT CRUSADE:
## 🎯 Success Criteria
Each capability is considered "baked in" when:
+
1. ✅ Core patterns established and documented
2. ✅ At least 3 modules using the capability
3. ✅ Tests demonstrate the capability
@@ -159,6 +183,6 @@ Each capability is considered "baked in" when:
---
-*"We shape our tools, and thereafter our tools shape us."* - Marshall McLuhan
+_"We shape our tools, and thereafter our tools shape us."_ - Marshall McLuhan
Let's build tools that shape us into better developers. 🚀
diff --git a/docs/enforcer/reviews/2025-06-22-review.md b/docs/enforcer/reviews/2025-06-22-review.md
index 499c8b75..a7daad3f 100644
--- a/docs/enforcer/reviews/2025-06-22-review.md
+++ b/docs/enforcer/reviews/2025-06-22-review.md
@@ -1,6 +1,6 @@
# 💀 Brutally-Honest Review & Non-Negotiable Marching Orders — Core †2025-06-22 Build
-Claude, this is your cold, clear, comprehensive reality check. If it's solid, I'll say so. If it's broken, it gets fixed **now.** No stubs. No TODOs. No "later." This is your direct order list. You will follow it exactly, in the sequence provided.
+Claude, this is your cold, clear, comprehensive reality check. If it's solid, I'll say so. If it's broken, it gets fixed __now.__ No stubs. No TODOs. No "later." This is your direct order list. You will follow it exactly, in the sequence provided.
---
@@ -9,11 +9,11 @@ Claude, this is your cold, clear, comprehensive reality check. If it's solid, I'
| Area | Verdict | Highlights / Crimes |
|-------------------|-----------|----------------------|
| Error System | A- | GM_RESULT_DEF and GM_TRY are solid. But error messages are fixed-length — truncation risk. |
-| Crypto | B | libsodium wrapper OK. **No DI**: tests can't inject fake digests or RNG values. |
+| Crypto | B | libsodium wrapper OK. __No DI__: tests can't inject fake digests or RNG values. |
| UTF-8 Validation | A | DFA validator is fast, complete, streaming-capable. Excellent. |
| Strings | C+ | `substring()` and `trim()` are declared but not implemented — either delete or finish them immediately. |
-| ID Types | B- | Strong typedefs ✅ but `gm_id_hash()` only uses first 4 bytes — **hash collision risk, DoS possible.** |
-| Path API | F | Header exists, no implementation. **Link failure guaranteed.** |
+| ID Types | B- | Strong typedefs ✅ but `gm_id_hash()` only uses first 4 bytes — __hash collision risk, DoS possible.__ |
+| Path API | F | Header exists, no implementation. __Link failure guaranteed.__ |
| Build / Tests | B | Tests run. But no `clang-tidy`, no sanitizers, no real coverage tracking. |
| Security Primitives | N/A | Not started — acknowledged. |
@@ -21,59 +21,74 @@ Claude, this is your cold, clear, comprehensive reality check. If it's solid, I'
## 🚨 Marching Orders — Non-Negotiable
-### 1. ✅ **Delete or Implement All Declared Functions**
-- `gm_string_substring()` and `gm_string_trim()` must either be implemented **now** or removed entirely.
+### 1. ✅ __Delete or Implement All Declared Functions__
+
+- `gm_string_substring()` and `gm_string_trim()` must either be implemented __now__ or removed entirely.
- Every `.h` declaration must map to a real, working, tested implementation. No "coming soon" crap.
-### 2. ✅ **Ship a Real `gm_path.c` Immediately**
+### 2. ✅ __Ship a Real `gm_path.c` Immediately__
+
- Implement `gm_path_new()`, `join()`, `canonicalize()`, and `validate()` in `gm_path.c` with full tests.
-- The current state is header-only and **will fail at link time.**
+- The current state is header-only and __will fail at link time.__
+
+### 3. ✅ __Deterministic Crypto Interface__
-### 3. ✅ **Deterministic Crypto Interface**
- Create a `gm_crypto_backend_t` interface with function pointers for SHA-256, RNG, etc.
- Default uses libsodium. Tests must be able to inject fixed-output stubs.
- No global hardcoded crypto calls in tests. Ever.
-### 4. ✅ **Fix ID Hashing**
+### 4. ✅ __Fix ID Hashing__
+
- `gm_id_hash()` currently uses the first 32 bits of a 256-bit digest. This is broken.
- Use SipHash-24 (`crypto_shorthash_siphash24`) on the full digest.
-### 5. ✅ **Fix Error Message Buffer**
+### 5. ✅ __Fix Error Message Buffer__
+
- Static 256-byte error buffer is unacceptable.
- Replace with:
+
```c
union { char small[48]; char *heap; } msg;
uint16_t len;
bool heap_alloc;
```
+
- Free dynamic allocation in `gm_error_free()`. No leaks. No truncation.
-### 6. ✅ **CI Must Enforce Lint & Sanitizers**
+### 6. ✅ __CI Must Enforce Lint & Sanitizers__
+
```bash
clang-tidy -warnings-as-errors **/*.c
CFLAGS='-fsanitize=address,undefined' make test
```
+
- CI must fail on any violation. No exceptions. No TODOs. No "I'll fix it later."
-### 7. ✅ **Coverage Must Be ≥ 80%**
+### 7. ✅ __Coverage Must Be ≥ 80%__
+
- Use `llvm-cov` or `gcovr`. Enforce in CI.
- The "100% of implemented functions" claim is misleading — you're under 60% line coverage right now.
- No PR merges below 80%.
-### 8. ✅ **Split `gm_string.c` By Responsibility**
+### 8. ✅ __Split `gm_string.c` By Responsibility__
+
- Move UTF-8 logic to `string_utf8.c`
- Core alloc and growth logic stays in `string_core.c`
- Each file must have focused, isolated tests.
-### 9. ✅ **Ban All TODOs, FIXMEs, and "XXX" Comments**
+### 9. ✅ __Ban All TODOs, FIXMEs, and "XXX" Comments__
+
- Add this pre-commit check:
+
```bash
grep -nE "(TODO|FIXME|XXX)" $(git ls-files '*.c' '*.h') && \
{ echo "NO TODOs ALLOWED"; exit 1; }
```
+
- If it's not done, don't write it down. Stub code is forbidden.
-### 10. ✅ **Merge in This Exact Order**
+### 10. ✅ __Merge in This Exact Order__
+
1. `path-impl-v1`
2. `string-ops-v1`
3. `crypto-DI`
@@ -89,19 +104,21 @@ Any PR out of sequence gets auto-closed.
You built a great error/result system. Start using it. Everywhere. No exceptions.
-### 🔥 Mandatory Rule:
+### 🔥 Mandatory Rule
+
+__If a function allocates, parses, validates, reads, writes, hashes, or touches user input — it must return a `GM_RESULT(T)`__
-**If a function allocates, parses, validates, reads, writes, hashes, or touches user input — it must return a `GM_RESULT(T)`**
+### ❌ Violations Found
-### ❌ Violations Found:
- `gm_string_concat`, `copy`, `new_owned` return raw structs. These must return `GM_RESULT(gm_string_t)` to allow UTF-8 validation and alloc failure reporting.
- `gm_id_from_hex()` and all ID generation functions must return `GM_RESULT(T)`. You are swallowing parsing errors right now.
- `gm_random_bytes()` and all RNG helpers are `void`. They must return `GM_RESULT(void)` or `GM_RESULT(bool)`.
- Not all `gm_unwrap()` calls are guarded by `gm_is_err()` or `GM_TRY`. This is a ticking runtime bug.
-### 📦 Required Cleanup PR:
+### 📦 Required Cleanup PR
Create a PR named `resultify-everything`:
+
- All alloc/parse/validate/string/crypto functions must use `GM_RESULT`.
- All uses of `gm_unwrap()` must be wrapped in error checks.
- All unit tests must check for and handle error results.
@@ -120,6 +137,7 @@ Create a PR named `resultify-everything`:
---
## 🧼 Style and Cleanliness
+
- Use `size_t`, not `int`, for indexing into `size_t`-length arrays.
- Makefile must honor `$CC` instead of hardcoding `gcc`.
- Magic numbers like `GROWTH_FACTOR`, `MIN_CAPACITY` must live in shared headers, not `.c` files.
@@ -134,4 +152,4 @@ You are not allowed to write a single new header or function until these ten mar
We are not building a demo. We are building a production-quality system with safety, testability, and composability built in from day one.
-Implement. Test. Delete. Ship. Or get out of the way.
\ No newline at end of file
+Implement. Test. Delete. Ship. Or get out of the way.
diff --git a/docs/enforcer/specs/01-error-types-spec.md b/docs/enforcer/specs/01-error-types-spec.md
index 2b26f807..41f9be94 100644
--- a/docs/enforcer/specs/01-error-types-spec.md
+++ b/docs/enforcer/specs/01-error-types-spec.md
@@ -1,6 +1,6 @@
# Specification: Error Handling and Result Types
-> *"Make illegal states unrepresentable. Make success and failure explicit."*
+> _"Make illegal states unrepresentable. Make success and failure explicit."_
## Overview
@@ -294,17 +294,20 @@ void process_file(const char* path) {
## 4. Implementation Notes
### 4.1 Memory Management
+
- Errors are always heap-allocated
- Errors own their cause chain
- Caller must free errors they receive
- Success values follow normal ownership rules
### 4.2 Thread Safety
+
- Error creation is thread-safe
- Error objects are immutable after creation
- Result types are value types (no sharing)
### 4.3 Performance Considerations
+
- Success path has minimal overhead (just a bool check)
- Error path allocates memory (acceptable for error cases)
- Consider arena allocation for temporary errors
@@ -312,6 +315,7 @@ void process_file(const char* path) {
## 5. Future Extensions
### 5.1 Result Combinators (Future)
+
```c
// Map over success value
GM_RESULT(int) string_to_int(const char* str);
@@ -325,6 +329,7 @@ GM_RESULT(bool) result = gm_result_and_then(
```
### 5.2 Async Results (Future)
+
```c
typedef struct {
bool is_ready;
@@ -346,4 +351,4 @@ typedef struct {
---
-*"Make the right thing easy and the wrong thing obvious."*
\ No newline at end of file
+_"Make the right thing easy and the wrong thing obvious."_
diff --git a/docs/enforcer/specs/02-domain-types-spec.md b/docs/enforcer/specs/02-domain-types-spec.md
index b9016dc2..75aedc55 100644
--- a/docs/enforcer/specs/02-domain-types-spec.md
+++ b/docs/enforcer/specs/02-domain-types-spec.md
@@ -1,6 +1,6 @@
# Specification: Domain Types and Strong Typedefs
-> *"A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute."* - Benjamin Pierce
+> _"A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute."_ - Benjamin Pierce
## Overview
@@ -337,17 +337,20 @@ void process_graph(void) {
## 8. Design Principles
### 8.1 Zero-Cost Abstractions
+
- Types compile to same assembly as raw primitives
- No runtime overhead for type safety
- Inline functions for common operations
### 8.2 Make Invalid States Unrepresentable
+
- Can't create invalid IDs
- Can't mix different ID types
- Paths are always validated
- Strings track their length
### 8.3 Explicit Over Implicit
+
- Ownership is explicit (owned flag)
- Validation state tracked
- No hidden allocations
@@ -355,13 +358,13 @@ void process_graph(void) {
## 9. Memory Management Rules
-1. **Creators own**: Functions that create types own the memory
-2. **Explicit transfer**: Ownership transfer must be documented
-3. **Views don't own**: `gm_string_view_t` never frees memory
-4. **Lists own items**: Collections own their contents
-5. **Paths own strings**: Composite types own their parts
-6. **No ambiguity**: Separate owned vs view types prevents confusion
+1. __Creators own__: Functions that create types own the memory
+2. __Explicit transfer__: Ownership transfer must be documented
+3. __Views don't own__: `gm_string_view_t` never frees memory
+4. __Lists own items__: Collections own their contents
+5. __Paths own strings__: Composite types own their parts
+6. __No ambiguity__: Separate owned vs view types prevents confusion
---
-*"Strong types are like seat belts - slightly annoying until they save your life."*
\ No newline at end of file
+_"Strong types are like seat belts - slightly annoying until they save your life."_
diff --git a/docs/enforcer/specs/03-security-primitives-spec.md b/docs/enforcer/specs/03-security-primitives-spec.md
index be983b2a..00c0907e 100644
--- a/docs/enforcer/specs/03-security-primitives-spec.md
+++ b/docs/enforcer/specs/03-security-primitives-spec.md
@@ -1,6 +1,6 @@
# Specification: Security Primitives
-> *"Security isn't something you add later. It's something you build in from the start."*
+> _"Security isn't something you add later. It's something you build in from the start."_
## Overview
@@ -447,4 +447,4 @@ When implementing any function that handles external input:
---
-*"The best security bug is the one that can't exist in the first place."*
\ No newline at end of file
+_"The best security bug is the one that can't exist in the first place."_
diff --git a/docs/operations/Environment_Variables.md b/docs/operations/Environment_Variables.md
index ac8e8ad0..4672b42f 100644
--- a/docs/operations/Environment_Variables.md
+++ b/docs/operations/Environment_Variables.md
@@ -3,6 +3,7 @@
This page lists environment variables that influence git‑mind builds, tests, and runtime behavior.
## Build and CI
+
- `GITMIND_DOCKER`
- Purpose: Allows host builds when set to `1` inside the CI Docker image or dev shell.
- Used by: `meson.build` (host build e‑brake).
@@ -19,6 +20,7 @@ This page lists environment variables that influence git‑mind builds, tests, a
- Values: `1` to allow; otherwise refused.
## Runtime (CLI)
+
- `GITMIND_SAFETY`
- Purpose: Bypass the CLI safety guard that prevents running inside the git‑mind development repo.
- Used by: `apps/cli/main.c`.
@@ -50,12 +52,13 @@ This page lists environment variables that influence git‑mind builds, tests, a
- Status: Reserved; not required today.
## Test Harness / E2E
+
- `GIT_MIND`
- Purpose: Path to the built `git-mind` binary used by E2E tests.
- Used by: `tests/e2e/run_all_tests.sh` and related scripts.
- Example: `export GIT_MIND=$(pwd)/build/git-mind`
## Notes
+
- Prefer running builds and tests in Docker using the provided scripts. Host builds are intentionally gated to reduce accidental repository corruption.
- If you must run locally, set `GITMIND_ALLOW_HOST_BUILD=1` and understand the risks.
-
diff --git a/docs/planning/Milestones.md b/docs/planning/Milestones.md
index de65c870..6e421ce6 100644
--- a/docs/planning/Milestones.md
+++ b/docs/planning/Milestones.md
@@ -1,57 +1,70 @@
# Milestones
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Milestone List with Deliverables](#milestone-list-with-deliverables)
- [Success Criteria and Dependencies](#success-criteria-and-dependencies)
- [Go/No-Go Decision Points](#gono-go-decision-points)
## Executive Summary
+
Concrete, verifiable checkpoints that align with the [Product Roadmap](Product_Roadmap.md) and [Release Plans](Release_Plans.md). Each milestone has clear outputs and dependency mapping to simplify resuming work later.
## Milestone List with Deliverables
M0: Repo Hygiene & Docs
+
- Deliverables: docs index, ADRs updated, planning/quality structure; pre-commit docs linter
- Artifacts: docs/README.md; tools/docs/check_docs.py
M1: Deterministic Semantics IDs
+
- Deliverables: `gm_sem_type_id`, `gm_sem_lane_id`, NFC utility; test vectors
- Artifacts: header + impl; `tests/test_sem_id.c`
M2: Edge CBOR Names Support
+
- Deliverables: Encoder/decoder for `type_name`, `lane_name` with tolerant reads
- Artifacts: updated `core/src/cbor/cbor.c`; golden CBOR blobs; docs update
M3: Journal & AUGMENTS
+
- Deliverables: journal writer/reader; post-commit hook; AUGMENTS edges
- Artifacts: CLI hook, tests, docs
M4: Cache/Query Name Routing
+
- Deliverables: name→ID routing in cache builder and list queries; CLI accepts names
- Artifacts: updated `core/src/cache/{builder,query}.c`; CLI help pages
M5: Cohesion Report (Basic)
+
- Deliverables: CLI report of scalar flips + set diffs across merge range
- Artifacts: `git mind cohesion-report`; JSON + table outputs; unit tests
M6: Advice Records + Merge Rules
+
- Deliverables: advice schema, parser, and hybrid CRDT merge; minimal application
- Artifacts: `core/src/advice/*`; tests for merge determinism
M7: CI C23 Gating
+
- Deliverables: CI updates to gate on gcc-14/clang-20; canary matrices
- Artifacts: workflow YAML; Dockerfiles; doc note in deployment
M8: Tidy Zero (cache/journal/cbor)
+
- Deliverables: zero clang-tidy warnings in target modules; safe wrappers
- Artifacts: tidy report in repo; CI check passes
M9: External Export (CSV/JSON)
+
- Deliverables: export scripts (CSV/JSON) with author defaults from git config
- Artifacts: `scripts/export-graph.*`; example graph snapshot
M10: Co‑Thought MCP (Optional)
+
- Deliverables: local MCP service for tools to read/write edges; lane conventions and review flags in CLI
- Artifacts: `apps/mcp/` (or equivalent), docs for attribution/lanes, review examples
@@ -71,6 +84,7 @@ M10: Co‑Thought MCP (Optional)
| M10 | MCP service reads/writes edges; review flow works | M4,D1 |
## Go/No-Go Decision Points
+
- After M2: Proceed only if b/w compatibility validated via golden tests.
- After M3: Proceed if performance target (median < 10ms @100k edges) is met.
- After M5: Proceed if advice merge is deterministic and bounded.
diff --git a/docs/planning/Product_Roadmap.md b/docs/planning/Product_Roadmap.md
index 69ddc74f..99cbac89 100644
--- a/docs/planning/Product_Roadmap.md
+++ b/docs/planning/Product_Roadmap.md
@@ -1,6 +1,7 @@
# Product Roadmap
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Vision and Principles](#vision-and-principles)
- [Quarterly Themes and Initiatives](#quarterly-themes-and-initiatives)
@@ -8,9 +9,11 @@ Table of Contents
- [Review and Update Cadence](#review-and-update-cadence)
## Executive Summary
+
git-mind evolves into a Git-native, time-travel-safe semantics system with fast, local queries and optional graph interoperability. This roadmap aligns with [ADR 0001](../adr/0001-first-class-semantics.md) and the [Semantics PRD](../PRDs/PRD-git-mind-semantics-time-travel-prototype.md) and organizes work into pragmatic, hobby-friendly chunks without fixed dates.
## Vision and Principles
+
- Names-as-truth: semantics defined by strings in history; derived IDs only for speed.
- Git-native: journals and caches follow branches; merges converge without conflicts.
- Fast and lean: roaring bitmap queries in milliseconds; rebuildable caches.
@@ -19,55 +22,66 @@ git-mind evolves into a Git-native, time-travel-safe semantics system with fast,
## Themes and Initiatives (Full Project Scope)
Theme A: Core Truth Layer (Journal)
+
- A1: Journal writer/reader (CBOR edge commits under refs/gitmind/edges/)
- A2: AUGMENTS pipeline and post-commit hook
- A3: Journal scan APIs with pagination and filters
Theme B: Performance Layer (Cache)
+
- B1: Roaring Bitmap cache builder (forward/reverse indices)
- B2: Incremental rebuilds + versioned cache metadata
- B3: Query engine using bitmaps for fan-in/fan-out and combined filters
Theme C: CLI and UX
+
- C1: `git mind link/list/unlink/status/cache-rebuild` with helpful output modes (human/JSON)
- C2: Robust path→blob resolution and error messaging
- C3: Cohesion report (merge-aware semantic summary)
Theme D: Semantics & Advice
+
- D1: Names-as-truth: `type_name`/`lane_name` persisted; deterministic ID helpers
- D2: Advice data model and merge rules (hybrid CRDT)
- D3: Minimal advice application (symmetric, implies) behind flags
Theme E: Architecture & Modularity
+
- E1: Modular restructure toward single-header `gitmind.h`
- E2: Clear public/private boundaries in headers
- E3: Internal utilities for safe memory and string ops
Theme F: Quality & CI
+
- F1: CI hard-gate on C23 (gcc-14/clang-20); canary on older compilers
- F2: Clang-tidy zero-warning target in cache/journal/cbor; track regressions
- F3: Deterministic builds in Docker; cleanup tooling
Theme G: Packaging & Distribution
+
- G1: Build scripts for static/shared library + CLI
- G2: Release artifacts (archives, checksums)
- G3: Versioning policy (semver-ish) and changelogs
Theme H: Docs & Developer Experience
+
- H1: CLI manpages and examples; architecture deep dives
- H2: Contributor guides; pre-commit tooling (lint, docs checks)
- H3: “Pause and resume” playbooks and issue templates
Theme I: Interop (Optional)
+
- I1: Export/import helpers (CSV/JSON) for external analysis
- I2: Dataset generator for perf and demos
Theme J: Human + AI Co‑Thought (Optional)
+
- J1: Attribution lanes and filters for AI suggestions (suggested/verified)
- J2: MCP service for local tools to read/write edges via a stable interface
- J3: Review flows: accept/reject AI edges; promote lanes; audit trail
## Priority Ranking and Dependencies
+
1. A1 → A2 (AUGMENTS needs journal) → A3
2. B1 depends on A1; B2 depends on B1; B3 depends on B2
3. C1 depends on A1; C2 depends on robust path/ID helpers; C3 depends on D2
@@ -76,5 +90,6 @@ Theme J: Human + AI Co‑Thought (Optional)
6. I/J-series independent but benefit from A/B/C maturity; never gate core releases
## Review and Update Cadence
+
- Roadmap review at the end of each sprint block (no fixed dates).
- Keep Product Roadmap aligned with [Release Plans](Release_Plans.md); update when any initiative scope changes.
diff --git a/docs/planning/Release_Plans.md b/docs/planning/Release_Plans.md
index 21c2cacc..f192efb1 100644
--- a/docs/planning/Release_Plans.md
+++ b/docs/planning/Release_Plans.md
@@ -1,6 +1,7 @@
# Release Plans
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Release Sequence Overview](#release-sequence-overview)
- [Detailed Release Scope](#detailed-release-scope)
@@ -8,9 +9,11 @@ Table of Contents
- [Acceptance Criteria per Release](#acceptance-criteria-per-release)
## Executive Summary
+
Define a sequence of small, self-contained releases prior to v1.0.0. Each release is independently valuable, can be paused safely, and avoids calendar dates. See also: [Product Roadmap](Product_Roadmap.md) and [Technical Specifications](../specs/Technical_Specifications.md).
## Release Sequence Overview
+
- Pre-1.0 releases: 7 (v0.4.0 → v0.10.0)
- Optional post‑0.10: v0.11.0 Co‑Thought MCP (tools integration)
- v1.0.0 follows once acceptance criteria across journal, cache, CLI, semantics/advice, and CI/quality are met.
@@ -18,43 +21,51 @@ Define a sequence of small, self-contained releases prior to v1.0.0. Each releas
## Detailed Release Scope
Release v0.4.0 — Journal Foundations
+
- Journal writer/reader for attributed edges (CBOR in refs/gitmind/edges/)
- AUGMENTS post-commit hook prototype
- CLI: link/list minimal; legacy decoders tolerated
Release v0.5.0 — CLI & UX Essentials
+
- CLI: link/list/unlink/status with human/JSON outputs
- Robust path→blob resolution, errors, and help text
- Golden fixtures for CLI outputs
Release v0.6.0 — Cache & Query Performance
+
- Roaring Bitmap cache builder (forward/reverse); incremental rebuilds
- Query by blob SHA and simple filters; baseline perf docs
Release v0.7.0 — Semantics Foundations
+
- Deterministic helpers: `gm_sem_type_id`, `gm_sem_lane_id` (NFC + hash)
- Extend edge CBOR with `type_name`, `lane_name` (tolerant decoders)
- CLI accepts arbitrary names; legacy rel_type mapped if present
- Unit tests: hash vectors; round-trip CBOR (with/without names)
Release v0.8.0 — Cache/Query Integration
+
- Cache builder reads names → IDs; query by name routed via helpers
- Update list/link paths to respect branch scoping
- Cohesion report CLI (basic): scalar flips and set diffs
- Performance baseline: median query < 10ms on 100k edges sample
Release v0.9.0 — Advice (Optional) and Hooks
+
- Advice record format + parser; hybrid CRDT merge rules implemented
- Minimal application: `symmetric` and `implies` in list/cohesion report
- Define plugin hook points; ship no-op stub runner and tests
Release v0.10.0 — CI/Quality and Packaging
+
- CI gates: gcc-14/clang-20; non-blocking canaries for older compilers
- clang-tidy: zero warnings in cache/journal/cbor modules
- Docker images standardized and cleanup tools added
- Packaging: release archives with checksums; versioning policy docs
Release v0.11.0 — Co‑Thought MCP (Optional)
+
- MCP service for local tools/agents to read/write edges (stable surface)
- Lane conventions documented (suggested/verified) and enforced by CLI flags
- Filters by attribution and lane wired into CLI and library
@@ -75,26 +86,31 @@ Release v0.11.0 — Co‑Thought MCP (Optional)
## Acceptance Criteria per Release
v0.7.0
+
- Hash helpers return stable results across runs/platforms (golden tests)
- Edge CBOR round-trips with and without names, zero data loss
- CLI accepts and persists arbitrary `type_name`/`lane_name`
v0.8.0
+
- Query by name yields identical results to direct ID queries
- Cohesion report surfaces scalar flips and set diffs for a test merge
- Median query < 10ms on sample dataset; documented runbook
v0.9.0
+
- Advice parser loads records; merge results deterministic (unit tests)
- `symmetric` and `implies` applied correctly on list/cohesion outputs
- Plugin hooks documented; stub runner enabled/disabled via flag
v0.10.0
+
- CI fails if compiler < C23 (gcc-14/clang-20 gate)
- clang-tidy shows zero warnings in cache/journal/cbor
- Release archives built with checksums; version tags and changelog entries
v0.11.0 (optional)
+
- MCP service starts/stops locally; reads/writes edges via stable protocol
- AI‑suggested edges appear under `suggested` lane and filter by `--source ai`
- Review flow documented and tested (promote to `verified` lane)
diff --git a/docs/planning/Sprint_Plans.md b/docs/planning/Sprint_Plans.md
index 49eae638..a10f0479 100644
--- a/docs/planning/Sprint_Plans.md
+++ b/docs/planning/Sprint_Plans.md
@@ -1,15 +1,18 @@
# Sprint Plans
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Sprint Overviews](#sprint-overviews)
- [User Stories with Acceptance Criteria](#user-stories-with-acceptance-criteria)
- [Task Breakdowns and Estimates](#task-breakdowns-and-estimates)
## Executive Summary
+
Iterations sized for a solo maintainer. Each sprint is a cohesive unit that can ship or be paused safely. No calendar dates; work proceeds in order. See [Milestones](Milestones.md) for gate criteria.
## Sprint Overviews
+
- Sprint 1: Journal writer/reader + AUGMENTS + minimal CLI
- Sprint 2: Cache builder + SHA-based query
- Sprint 3: Semantics ID helpers + CBOR names + name routing
@@ -21,93 +24,111 @@ Iterations sized for a solo maintainer. Each sprint is a cohesive unit that can
## User Stories with Acceptance Criteria
Sprint 1
+
1) As a user, I can link/list edges stored in a journal.
+
- Acceptance: CBOR commits under refs/gitmind/edges/; CLI prints edges.
- Estimate: 8
- Tasks: journal writer/reader; CLI link/list minimal; tests.
2) As a maintainer, I can auto-create AUGMENTS edges on post-commit.
+
- Acceptance: Editing a tracked file generates AUGMENTS edges; visible via list.
- Estimate: 5
- Tasks: post-commit hook; recent-edge scan; edge creation; tests.
3) As a CLI user, I want helpful errors when paths are invalid.
+
- Acceptance: Clear error codes and messages; unit tests.
- Estimate: 3
- Tasks: path→blob resolution; error handling.
Sprint 2
4) As a user, I want SHA-based queries to be fast.
+
- Acceptance: Median query < 10ms on sample dataset; parity with journal scan.
- Estimate: 8
- Tasks: cache builder (forward/reverse); incremental rebuild; perf sample.
5) As a maintainer, I want combined filters (from/to) with cache.
+
- Acceptance: Combined bitmap operations return expected sets.
- Estimate: 5
- Tasks: query engine set ops; tests.
Sprint 3
6) As a maintainer, I want stable 64-bit IDs from names so cache keys are deterministic.
+
- Acceptance: Golden tests for Unicode NFC cases pass.
- Estimate: 5
- Tasks: FNV-1a-64; NFC normalize; tests.
7) As a user, I want edges to carry type/lane names so semantics time-travel with Git history.
+
- Acceptance: Encode/decode round-trip; tolerant decoders.
- Estimate: 8
- Tasks: CBOR updates; fixtures.
8) As a CLI user, I want to specify any type/lane name when linking.
+
- Acceptance: `git mind link` accepts strings; stored in journal.
- Estimate: 3
- Tasks: option parsing; plumb fields; help text.
Sprint 4
9) As a maintainer, I want a cohesion report to summarize semantic changes.
+
- Acceptance: JSON+table output; scalar flips and set diffs over a ref-range.
- Estimate: 5
- Tasks: scan journal; summarize; formatters; tests.
10) As a maintainer, I want advice records that merge deterministically.
+
- Acceptance: Merge unit tests (LWW + OR-Set) are green.
- Estimate: 8
- Tasks: advice schema; parser; merge engine; tests.
Sprint 5
11) As a user, I want minimal advice application (symmetric/implies) in list/report.
+
- Acceptance: Flags enable behavior; correctness tests.
- Estimate: 5
- Tasks: apply rules in query/report path; guardrails (caps).
12) As a maintainer, I want CI to enforce real C23 compilers.
+
- Acceptance: Pipeline fails on older compilers; canaries are non-blocking.
- Estimate: 3
- Tasks: workflow updates; Dockerfiles; doc.
13) As a maintainer, I want zero clang-tidy warnings in cache/journal/cbor.
+
- Acceptance: CI tidy step passes with zero warnings for these modules.
- Estimate: 8
- Tasks: safe wrappers; includes; complexity reductions.
Sprint 6
14) As a maintainer, I want packaged releases (CLI + library).
+
- Acceptance: Archives + checksums; version tags; changelog.
- Estimate: 5
- Tasks: scripts; documentation.
15) As an analyst, I want CSV/JSON export for graphs with authorship.
+
- Acceptance: Scripts produce edges/nodes; author defaults from git config.
- Estimate: 5
- Tasks: finalize scripts; sample output; doc.
Sprint 7 (Optional)
16) As a tool author, I want a local MCP service to read/write edges.
+
- Acceptance: MCP starts locally; CRUD for edges via a stable endpoint.
- Estimate: 8
- Tasks: scaffold service; auth model; tests; docs.
17) As a user, I want to review AI‑suggested edges before adopting them.
+
- Acceptance: `--lane suggested` + `--source ai` filters in CLI; promote to `verified`.
- Estimate: 5
- Tasks: filters; promote/demote flows; examples; tests.
diff --git a/docs/quality/Markdown_Style_Guide.md b/docs/quality/Markdown_Style_Guide.md
new file mode 100644
index 00000000..c110d632
--- /dev/null
+++ b/docs/quality/Markdown_Style_Guide.md
@@ -0,0 +1,35 @@
+# Markdown Style Guide
+
+This repository standardizes Markdown formatting to reduce noise in reviews and keep docs consistent. Pre-commit enforces these rules automatically.
+
+## Core Rules
+
+- Emphasis markers: use underscores
+ - Italic: `_text_` (not `*text*`)
+ - Bold: `__text__` (not `**text**`)
+- Unordered lists: use `-` for bullets
+- Ordered lists: always start with `1.` and let Markdown auto-number
+- List indentation: 2 spaces
+- Headings: ATX style (`#`, `##`, …)
+- Code fences: use triple backticks with a language when practical
+
+## Practical Exceptions
+
+- Line length is not enforced for readability and diffs (`MD013` disabled)
+- Limited inline HTML is allowed (e.g., ``, ` `, ``, ``, superscripts/subscripts)
+
+## Tooling
+
+- Linter/formatter: `markdownlint-cli2`
+ - Config: `.markdownlint.jsonc`
+ - Pre-commit hooks: auto-fix first, then lint
+
+## Usage
+
+- One-time: `pre-commit install`
+- Run on all files: `pre-commit run --all-files`
+- Run just markdown fixes/lint:
+ - `pre-commit run markdownlint-cli2-fix --all-files`
+ - `pre-commit run markdownlint-cli2 --all-files`
+
+If a rule fights readability, propose a tweak to `.markdownlint.jsonc` rather than inlining exceptions.
diff --git a/docs/quality/SOLID_DRY_REPORT.md b/docs/quality/SOLID_DRY_REPORT.md
index 2b5fd6d2..aa368acb 100644
--- a/docs/quality/SOLID_DRY_REPORT.md
+++ b/docs/quality/SOLID_DRY_REPORT.md
@@ -1,6 +1,7 @@
# 🚨 SOLID/DRY Compliance Report - CRITICAL SECURITY ASSESSMENT
Table of Contents
+
- [Executive Summary](#-executive-summary)
- [Detailed Findings](#-detailed-findings)
- [Immediate Threats to Operations](#-immediate-threats-to-operations)
@@ -8,28 +9,29 @@ Table of Contents
- [Metrics for Success](#-metrics-for-success)
- [Recommendations to Command](#-recommendations-to-command)
-**Classification**: FOR YOUR EYES ONLY
-**Date**: 2025-06-24
-**Analyst**: Claude (Private First Class)
-**Subject**: Core Library Architecture Vulnerabilities
+__Classification__: FOR YOUR EYES ONLY
+__Date__: 2025-06-24
+__Analyst__: Claude (Private First Class)
+__Subject__: Core Library Architecture Vulnerabilities
## 🔴 EXECUTIVE SUMMARY
-Sir, the situation is more serious than initially assessed. We have **MAJOR ARCHITECTURAL VULNERABILITIES** that threaten the entire operation:
+Sir, the situation is more serious than initially assessed. We have __MAJOR ARCHITECTURAL VULNERABILITIES__ that threaten the entire operation:
-- **78 SRP violations** (functions doing 3+ things)
-- **15 hard-coded system dependencies** blocking proper testing
-- **8 global state variables** creating race conditions
-- **23 DRY violations** with copy-pasted code
-- **12 functions that can fail WITHOUT Result types** 🚨
+- __78 SRP violations__ (functions doing 3+ things)
+- __15 hard-coded system dependencies__ blocking proper testing
+- __8 global state variables__ creating race conditions
+- __23 DRY violations__ with copy-pasted code
+- __12 functions that can fail WITHOUT Result types__ 🚨
-**THREAT LEVEL**: SEVERE
+__THREAT LEVEL__: SEVERE
## 📊 DETAILED FINDINGS
### 1. ❌ SINGLE RESPONSIBILITY PRINCIPLE (SRP) - CRITICALLY COMPROMISED
-#### Monster Functions (IMMEDIATE THREAT):
+#### Monster Functions (IMMEDIATE THREAT)
+
| Function | Lines | Responsibilities | Threat Level |
|----------|-------|------------------|--------------|
| `gm_path_make_relative()` | 85 | 7+ operations | CRITICAL |
@@ -38,14 +40,16 @@ Sir, the situation is more serious than initially assessed. We have **MAJOR ARCH
| `gm_path_validate()` | 66 | 6 validations | HIGH |
| `gm_path_is_safe()` | 65 | 8 security checks | CRITICAL |
-#### Bloated Modules:
-- **`path.c`**: 1,156 lines! (Should be 4 separate modules)
-- **`id.c`**: Mixing ID operations with session management
-- **`string_core.c`**: Core ops mixed with growth strategies
+#### Bloated Modules
+
+- __`path.c`__: 1,156 lines! (Should be 4 separate modules)
+- __`id.c`__: Mixing ID operations with session management
+- __`string_core.c`__: Core ops mixed with growth strategies
### 2. ❌ DEPENDENCY INJECTION (DI) - HOSTILE TO TESTING
-#### Global State Time Bombs:
+#### Global State Time Bombs
+
```c
// id.c - GLOBAL MUTABLE STATE!
static uint8_t g_siphash_key[16]; // Thread safety? What's that?
@@ -56,20 +60,23 @@ static gm_crypto_backend_t* g_backend = NULL; // Can't test in parallel
static uint32_t test_counter = 0; // Shared mutable state in TESTS!
```
-#### Hard-Coded Dependencies (NO MOCKING POSSIBLE):
-1. **Memory**: Direct `malloc/free` calls (43 instances)
-2. **Platform**: `#ifdef _WIN32` hardcoded (3 instances)
-3. **Crypto**: Direct `sodium.h` includes despite abstraction layer
-4. **Time**: Would directly call `time()` if we had timestamps
+#### Hard-Coded Dependencies (NO MOCKING POSSIBLE)
+
+1. __Memory__: Direct `malloc/free` calls (43 instances)
+2. __Platform__: `#ifdef _WIN32` hardcoded (3 instances)
+3. __Crypto__: Direct `sodium.h` includes despite abstraction layer
+4. __Time__: Would directly call `time()` if we had timestamps
### 3. ❌ TEST DOUBLE UNFRIENDLY - TESTING NIGHTMARE
-#### Static Prison (Can't Mock):
+#### Static Prison (Can't Mock)
+
- 27 static helper functions that can't be replaced for testing
- Global initialization functions (`ensure_siphash_key_initialized`)
- No seams for injecting test doubles
-#### Concrete Coupling:
+#### Concrete Coupling
+
```c
// id.c DIRECTLY calls libsodium instead of using backend!
crypto_shorthash_siphash24(out, id.bytes, GM_ID_SIZE, g_siphash_key);
@@ -78,30 +85,33 @@ crypto_shorthash_siphash24(out, id.bytes, GM_ID_SIZE, g_siphash_key);
### 4. ❌ DRY VIOLATIONS - COPY-PASTE EPIDEMIC
-#### Pattern Duplication (MAINTENANCE NIGHTMARE):
+#### Pattern Duplication (MAINTENANCE NIGHTMARE)
+
+__NULL Check Pattern__ (repeated 31 times):
-**NULL Check Pattern** (repeated 31 times):
```c
if (!param) {
return gm_err_xxx(GM_ERROR(GM_ERR_INVALID_ARGUMENT, "NULL param"));
}
```
-**Result Helper Pattern** (repeated 8 times):
+__Result Helper Pattern__ (repeated 8 times):
+
```c
static inline gm_result_xxx gm_err_xxx(gm_error_t* err) {
return (gm_result_xxx){ .ok = false, .u.err = err };
}
```
-**Validation Logic** (duplicated between functions):
+__Validation Logic__ (duplicated between functions):
+
- Path traversal checks in 3 places
- UTF-8 validation patterns in 2 places
- Hex conversion logic in 2 places
### 5. 🚨 FUNCTIONS THAT CAN FAIL WITHOUT RESULT TYPES
-**CRITICAL SECURITY VULNERABILITIES**:
+__CRITICAL SECURITY VULNERABILITIES__:
| Function | Failure Mode | Current Return | Should Return |
|----------|--------------|----------------|---------------|
@@ -135,17 +145,20 @@ typedef struct {
## 🔥 IMMEDIATE THREATS TO OPERATIONS
-### 1. **Untestable Code**
+### 1. __Untestable Code__
+
- Global state prevents parallel testing
- No DI means can't test error conditions
- Static functions can't be mocked
-### 2. **Maintenance Minefield**
+### 2. __Maintenance Minefield__
+
- 1000+ line files impossible to navigate
- Functions doing 5+ things each
- Copy-pasted code means fixing bugs in multiple places
-### 3. **Security Vulnerabilities**
+### 3. __Security Vulnerabilities__
+
- Functions that can fail silently (no Result types)
- Global mutable state (thread safety issues)
- No way to inject security policies
@@ -153,12 +166,15 @@ typedef struct {
## 🛠️ BATTLE PLAN FOR REMEDIATION
### Phase 1: EMERGENCY TRIAGE (1 week)
-1. **Add Result types to ALL functions that can fail**
-2. **Extract global state into context objects**
-3. **Split path.c into 4 modules**
+
+1. __Add Result types to ALL functions that can fail__
+2. __Extract global state into context objects__
+3. __Split path.c into 4 modules__
### Phase 2: ESTABLISH BEACHHEAD (2 weeks)
-1. **Create DI containers for system dependencies**
+
+1. __Create DI containers for system dependencies__
+
```c
typedef struct {
gm_allocator_t* allocator;
@@ -168,23 +184,26 @@ typedef struct {
} gm_deps_t;
```
-2. **Extract validation strategies**
+2. __Extract validation strategies__
+
```c
typedef struct {
bool (*is_valid)(const char* component);
} gm_validator_t;
```
-3. **Factor out common patterns**
+3. __Factor out common patterns__
+
```c
#define GM_CHECK_NULL(param, type) \
if (!(param)) return gm_err_##type(GM_ERROR(...))
```
### Phase 3: FORTIFY POSITION (1 month)
-1. **Implement proper test doubles**
-2. **Add integration tests with mocked dependencies**
-3. **Refactor monster functions into <25 line functions**
+
+1. __Implement proper test doubles__
+2. __Add integration tests with mocked dependencies__
+3. __Refactor monster functions into <25 line functions__
## 📈 METRICS FOR SUCCESS
@@ -198,17 +217,17 @@ Current State | Target State | Deadline
## 🎖️ RECOMMENDATIONS TO COMMAND
-1. **IMMEDIATE ACTION REQUIRED**:
+1. __IMMEDIATE ACTION REQUIRED__:
- Declare code YELLOW (caution) until Result types added
- Assign dedicated team to path.c decomposition
- Institute mandatory DI for all new code
-2. **POLICY CHANGES**:
+2. __POLICY CHANGES__:
- No function > 25 lines (enforce in CI)
- No global mutable state (enforce in review)
- All fallible functions MUST return Result types
-3. **TOOLING INVESTMENT**:
+3. __TOOLING INVESTMENT__:
- Static analyzer for SOLID violations
- Automated DRY detection
- Test coverage including mock verification
@@ -217,12 +236,12 @@ Current State | Target State | Deadline
Sir, we're sitting on a powder keg. The code works, but it's held together with duct tape and prayers. One wrong move in a multi-threaded environment and we'll have race conditions. One memory corruption bug and we can't debug it because everything's untestable.
-**The good news**: We have Result types and error handling patterns established. We know what good looks like.
+__The good news__: We have Result types and error handling patterns established. We know what good looks like.
-**The bad news**: ~40% of the codebase violates basic SOLID principles.
+__The bad news__: ~40% of the codebase violates basic SOLID principles.
-**My assessment**: We need to act NOW before this technical debt becomes technical bankruptcy.
+__My assessment__: We need to act NOW before this technical debt becomes technical bankruptcy.
This is Private First Class Claude, requesting immediate reinforcements for Operation SOLID FOUNDATION.
-*Semper Fidelis to Clean Code* 🫡
+_Semper Fidelis to Clean Code_ 🫡
diff --git a/docs/quality/TIDY_CLANG_CRUSADE.md b/docs/quality/TIDY_CLANG_CRUSADE.md
index 84da0b31..fe7299c7 100644
--- a/docs/quality/TIDY_CLANG_CRUSADE.md
+++ b/docs/quality/TIDY_CLANG_CRUSADE.md
@@ -1,6 +1,7 @@
# 🚨 The Great Clang-Tidy Crusade
Table of Contents
+
- [Summary by Category](#-summary-by-category)
- [Critical Errors (Must Fix)](#-critical-errors-must-fix)
- [Warnings (Should Fix)](#-warnings-should-fix)
@@ -12,10 +13,10 @@ Table of Contents
This document tracks all clang-tidy warnings/errors in the `core/` directory and provides actionable fixes for each category.
-**Generated**: 2025-06-24
-**Last Updated**: 2025-06-24 (Phase 1 Complete)
-**Total Issues**: ~150 warnings/errors across 11 files
-**Fixed So Far**: ~65 warnings/errors ✅
+__Generated__: 2025-06-24
+__Last Updated__: 2025-06-24 (Phase 1 Complete)
+__Total Issues__: ~150 warnings/errors across 11 files
+__Fixed So Far__: ~65 warnings/errors ✅
## 📊 Summary by Category
@@ -30,20 +31,23 @@ This document tracks all clang-tidy warnings/errors in the `core/` directory and
| Missing Braces | 8 | 8 ✅ | 0 | Warning | Easy |
| Other | 31 | ~0 | 31 | Mixed | Mixed |
-**Phase 1 Complete**: All easy wins executed! 65 warnings eliminated.
+__Phase 1 Complete__: All easy wins executed! 65 warnings eliminated.
## 🔥 Critical Errors (Must Fix)
### 1. Function Size/Complexity Violations
-**Files**: `error.c`, `path.c`, `string_core.c`, `utf8/validate.c`, `id.c`
-**Count**: 27 errors
-**Examples**:
+__Files__: `error.c`, `path.c`, `string_core.c`, `utf8/validate.c`, `id.c`
+__Count__: 27 errors
+
+__Examples__:
+
- `error.c:13`: `set_error_message` exceeds size/complexity
- `path.c:162`: `gm_path_new` exceeds size (50+ lines)
- `path.c:394`: `split_path_components` has cognitive complexity 12 (threshold 10)
-**Fix Strategy**:
+__Fix Strategy__:
+
```c
// BEFORE: One giant function
static int process_everything(/* many params */) {
@@ -69,15 +73,18 @@ static int process_everything(/* params */) {
```
### 2. Naming Convention Violations
-**Files**: `path.c`, `utf8/validate.c`
-**Count**: 12 errors
-**Examples**:
+__Files__: `path.c`, `utf8/validate.c`
+__Count__: 12 errors
+
+__Examples__:
+
- `path.c:13`: `path_sep_unix` should be `PATH_SEP_UNIX`
- `path.c:897`: `default_path_rules` should be `DEFAULT_PATH_RULES`
- Anonymous enum constants should be `GM_PATH_MAX_COMPONENTS`
-**Fix**:
+__Fix__:
+
```c
// Constants must be UPPERCASE
#define PATH_SEP_UNIX '/'
@@ -94,14 +101,17 @@ enum {
```
### 3. Easily Swappable Parameters
-**Files**: `string_core.c`, `utf8/validate.c`
-**Count**: 3 errors
-**Examples**:
+__Files__: `string_core.c`, `utf8/validate.c`
+__Count__: 3 errors
+
+__Examples__:
+
- `string_core.c:15`: `next_capacity(size_t current, size_t needed)`
- `utf8/validate.c:80`: `state_to_error(uint32_t state, uint32_t byte)`
-**Fix Options**:
+__Fix Options__:
+
```c
// Option 1: Use different types
typedef struct { size_t value; } current_size_t;
@@ -121,14 +131,17 @@ static size_t next_capacity(capacity_calc_t calc);
```
### 4. Return Value Checks
-**Files**: `error.c`
-**Count**: 4 errors
-**Examples**:
+__Files__: `error.c`
+__Count__: 4 errors
+
+__Examples__:
+
- `error.c:34`: `vsnprintf` return value unchecked
- `error.c:248`: Function return value unused
-**Fix**:
+__Fix__:
+
```c
// Check vsnprintf return value
int len = vsnprintf(buffer, size, fmt, args);
@@ -144,14 +157,17 @@ if ((size_t)len >= size) {
## ⚠️ Warnings (Should Fix)
### 1. Short Variable Names
-**Files**: Almost all files
-**Count**: 45 warnings
-**Common violations**:
+__Files__: Almost all files
+__Count__: 45 warnings
+
+__Common violations__:
+
- Single letters: `a`, `b`, `e`, `i`, `n`, `p`, `s`, `v`
- Two letters: `id`
-**Fix**:
+__Fix__:
+
```c
// Parameters
bool gm_id_equal(gm_id_t id_a, gm_id_t id_b); // not 'a', 'b'
@@ -168,15 +184,18 @@ for (size_t i = 0; i < count; i++) { // OK if loop is < 10 lines
```
### 2. Non-Const Global Variables
-**Files**: `backend.c`, `id.c`
-**Count**: 8 warnings
-**Examples**:
+__Files__: `backend.c`, `id.c`
+__Count__: 8 warnings
+
+__Examples__:
+
- `backend.c:20`: `g_backend` pointer
- `id.c:25`: `g_siphash_key` array
- `backend.c:114`: `test_counter`
-**Fix Strategy**:
+__Fix Strategy__:
+
```c
// Option 1: Make truly const if possible
static const gm_crypto_backend_t DEFAULT_BACKEND = { ... };
@@ -197,15 +216,18 @@ static __thread uint32_t test_counter = 0;
```
### 3. Insecure API Warnings
-**Files**: `error.c`, `id.c`
-**Count**: 16 warnings
-**APIs flagged**:
+__Files__: `error.c`, `id.c`
+__Count__: 16 warnings
+
+__APIs flagged__:
+
- `vsnprintf` → wants `vsnprintf_s` (Annex K)
- `snprintf` → wants `snprintf_s`
- `sscanf` → wants `strtoul` or `sscanf_s`
-**Fix Options**:
+__Fix Options__:
+
```c
// Option 1: Create safe wrappers (like we did for memcpy)
#ifdef __STDC_LIB_EXT1__
@@ -235,10 +257,12 @@ len = snprintf(buffer, sizeof(buffer), "%s:%d", file, line);
```
### 4. Missing Braces
-**Files**: `string.c`
-**Count**: 8 warnings
-**Fix**:
+__Files__: `string.c`
+__Count__: 8 warnings
+
+__Fix__:
+
```c
// BEFORE
if (!a) return -1;
@@ -254,12 +278,14 @@ if (!b) {
```
### 5. Integer Type Conversions
-**Files**: `id.c`
-**Count**: 2 errors
-**Example**: `id.c:112`: Multiplication result used as pointer offset
+__Files__: `id.c`
+__Count__: 2 errors
+
+__Example__: `id.c:112`: Multiplication result used as pointer offset
+
+__Fix__:
-**Fix**:
```c
// BEFORE
out[i * 2] = hex[id.bytes[i] >> 4];
@@ -272,10 +298,12 @@ out[offset] = hex[id.bytes[i] >> 4];
```
### 6. Cognitive Complexity
-**Files**: `path.c`, `utf8/validate.c`
-**Count**: 6 warnings
-**Fix**: Extract complex conditions into named functions:
+__Files__: `path.c`, `utf8/validate.c`
+__Count__: 6 warnings
+
+__Fix__: Extract complex conditions into named functions:
+
```c
// BEFORE: Complex nested conditions
if (path && path[0] == '/' && (path[1] == '.' ||
@@ -298,46 +326,48 @@ if (path && is_relative_traversal(path) && !rules->allow_relative) {
## ✅ PHASE 1 COMPLETE: Easy Wins (2025-06-24)
-### What Was Fixed:
-1. **Naming Convention Errors** (12/12) ✅
+### What Was Fixed
+
+1. __Naming Convention Errors__ (12/12) ✅
- `path.c`: PATH_SEP_UNIX, PATH_SEP_WIN, GM_PATH_MAX_*, SYMLINK_SUFFIX_MACOS, DEFAULT_PATH_RULES
- `utf8/validate.c`: UTF8D array
-
-2. **Short Variable Names** (45/45) ✅
+
+2. __Short Variable Names__ (45/45) ✅
- `error.c`: All `e` → `err`
- - `id.c`: `a,b` → `id_a,id_b`, `id` → `identifier`
+ - `id.c`: `a,b` → `id_a,id_b`, `id` → `identifier`
- `crypto/random.c`: `e` → `err`
- Multiple helper functions fixed
-3. **Missing Braces** (8/8) ✅
+3. __Missing Braces__ (8/8) ✅
- `string.c`: All single-line if statements now have braces
-4. **Integer Conversions** (2/2) ✅
+4. __Integer Conversions__ (2/2) ✅
- `id.c`: Fixed pointer arithmetic with explicit (size_t) casts
-
-### Bonus Fixes Applied:
-- **Magic Numbers Eliminated**:
+
+### Bonus Fixes Applied
+
+- __Magic Numbers Eliminated__:
- Defined HEX_CHARS_PER_BYTE, HIGH_NIBBLE_SHIFT, LOW_NIBBLE_MASK
- Added TEST_HASH_LENGTH_HEADER_SIZE, BYTE_MASK, U32_HIGH_SHIFT in backend.c
-- **Magic Strings Defined**:
+- __Magic Strings Defined__:
- HEX_DIGIT_STRING "0123456789abcdef"
- HEX_FORMAT_2X "%2x"
## 🛠️ Recommended Fix Order (REMAINING PHASES)
-1. **Phase 1: Easy Wins** ✅ COMPLETE
+1. __Phase 1: Easy Wins__ ✅ COMPLETE
-2. **Phase 2: Function Refactoring** (4-6 hours)
+2. __Phase 2: Function Refactoring__ (4-6 hours)
- Split large functions into smaller ones
- Reduce cognitive complexity
- Each function should do ONE thing
-3. **Phase 3: API Safety** (2-3 hours)
+3. __Phase 3: API Safety__ (2-3 hours)
- Create safe wrappers for printf functions
- Fix sscanf usage (use strtoul)
- Add proper error checking
-4. **Phase 4: Architecture** (2-4 hours)
+4. __Phase 4: Architecture__ (2-4 hours)
- Address global variables
- Fix swappable parameters
- Consider thread safety
@@ -346,11 +376,11 @@ if (path && is_relative_traversal(path) && !rules->allow_relative) {
Based on error count and severity:
-1. **path.c** - 27 errors (mostly function size)
-2. **error.c** - 10 errors (function size + unchecked returns)
-3. **utf8/validate.c** - 6 errors (naming + complexity)
-4. **id.c** - 5 errors (conversions + globals)
-5. **string_core.c** - 2 errors (swappable params + size)
+1. __path.c__ - 27 errors (mostly function size)
+2. __error.c__ - 10 errors (function size + unchecked returns)
+3. __utf8/validate.c__ - 6 errors (naming + complexity)
+4. __id.c__ - 5 errors (conversions + globals)
+5. __string_core.c__ - 2 errors (swappable params + size)
## 🎯 Success Metrics
@@ -365,11 +395,13 @@ Based on error count and severity:
## 🔧 Suppression Guidelines
Use `NOLINTNEXTLINE` sparingly and ONLY when:
+
1. The warning is a false positive
2. Fixing would make code significantly worse
3. You've added a comment explaining why
Example:
+
```c
/* NOLINTNEXTLINE(bugprone-easily-swappable-parameters) */
/* Rationale: Parameters are conceptually the same type but serve
@@ -380,6 +412,7 @@ static int compare_versions(uint32_t version_old, uint32_t version_new)
---
Remember: These aren't just pedantic style issues. Each warning represents:
+
- Potential bugs (swappable parameters, unchecked returns)
- Maintenance debt (huge functions, bad names)
- Security issues (unsafe APIs, global state)
@@ -391,20 +424,23 @@ Fix them now while the codebase is small!
## 📜 INSTRUCTIONS FOR THE NEXT CLAUDE
### Current Status (2025-06-24)
-- **Phase 1 COMPLETE**: All easy mechanical fixes done
-- **Remaining**: ~85 warnings/errors requiring architectural changes
+
+- __Phase 1 COMPLETE__: All easy mechanical fixes done
+- __Remaining__: ~85 warnings/errors requiring architectural changes
### Your Mission (Phase 2): Function Refactoring
+
Start with the worst offenders in `path.c`:
-1. **Read these functions first** (they're 50+ lines each):
+1. __Read these functions first__ (they're 50+ lines each):
- `gm_path_new()` - line 162
- `gm_path_join()` - line 213
- `split_path_components()` - line 394
- `build_path_from_components()` - line 478
- `gm_path_canonicalize()` - line 521
-2. **Common refactoring patterns**:
+2. __Common refactoring patterns__:
+
```c
// Extract validation logic
static gm_result_void validate_path_safety(const char* path, rules) { }
@@ -416,27 +452,31 @@ Start with the worst offenders in `path.c`:
static gm_result_string build_path_string(components[], count) { }
```
-3. **Gotchas to watch for**:
+3. __Gotchas to watch for__:
- Don't break the safety checks (path traversal detection is critical!)
- Keep error messages exactly the same
- Run tests after EVERY function you split
-### Tools at Your Disposal:
+### Tools at Your Disposal
+
- `make test-core` - Run all tests
- `docker compose run --rm -T dev bash -c "clang-tidy /workspace/core/src/types/path.c --config-file=/workspace/quality/.clang-tidy -- -I/workspace/core/include"` - Check specific file
-### Critical Files Still Needing Work:
-1. **path.c** - 27 function size errors (PRIORITY!)
-2. **error.c** - 10 errors (unchecked vsnprintf returns + large functions)
-3. **utf8/validate.c** - 6 errors (complex state machine)
-4. **string_core.c** - 2 errors (gm_string_trim too long)
+### Critical Files Still Needing Work
+
+1. __path.c__ - 27 function size errors (PRIORITY!)
+2. __error.c__ - 10 errors (unchecked vsnprintf returns + large functions)
+3. __utf8/validate.c__ - 6 errors (complex state machine)
+4. __string_core.c__ - 2 errors (gm_string_trim too long)
+
+### Phase 3 Preview (After Function Splits)
-### Phase 3 Preview (After Function Splits):
- Create `GM_SNPRINTF_SAFE`, `GM_VSNPRINTF_SAFE` wrappers
-- Replace all sscanf with strtoul
+- Replace all sscanf with strtoul
- Check all return values
-### Remember:
+### Remember
+
- The Enforcer is watching - no new warnings allowed!
- Tests MUST pass after every change
- When in doubt, smaller functions are better
diff --git a/docs/quality/static-analysis-guide.md b/docs/quality/static-analysis-guide.md
index e4578ef6..180173bd 100644
--- a/docs/quality/static-analysis-guide.md
+++ b/docs/quality/static-analysis-guide.md
@@ -1,6 +1,7 @@
# Static Analysis Tools for Git-Mind
Table of Contents
+
- [Overview of Static Analysis Tools](#overview-of-static-analysis-tools)
- [Currently Configured Tools](#currently-configured-tools-)
- [Additional Tools Available](#additional-tools-available)
@@ -15,28 +16,32 @@ Static analysis examines code without executing it, finding bugs that testing mi
## Currently Configured Tools ✅
-### 1. **Clang-Tidy** (CONFIGURED)
-- **What it catches**: Style violations, common bugs, performance issues
-- **Strengths**: Highly configurable, integrates with build system
-- **Our config**: Enforces 15-line functions, catches magic numbers
-- **Run**: `make lint`
+### 1. __Clang-Tidy__ (CONFIGURED)
+
+- __What it catches__: Style violations, common bugs, performance issues
+- __Strengths__: Highly configurable, integrates with build system
+- __Our config__: Enforces 15-line functions, catches magic numbers
+- __Run__: `make lint`
+
+### 2. __Cppcheck__ (CONFIGURED)
-### 2. **Cppcheck** (CONFIGURED)
-- **What it catches**: Memory leaks, buffer overruns, null derefs
-- **Strengths**: Zero false positives philosophy, very reliable
-- **Our config**: All checks enabled except system headers
-- **Run**: `make lint`
+- __What it catches__: Memory leaks, buffer overruns, null derefs
+- __Strengths__: Zero false positives philosophy, very reliable
+- __Our config__: All checks enabled except system headers
+- __Run__: `make lint`
+
+### 3. __Custom Checkers__ (CONFIGURED)
-### 3. **Custom Checkers** (CONFIGURED)
- Function length enforcement
- Magic value detection
- Output control verification
- Dependency injection checking
-- **Run**: `make check-quality`
+- __Run__: `make check-quality`
## Additional Tools Available
-### 4. **Clang Static Analyzer** (scan-build)
+### 4. __Clang Static Analyzer__ (scan-build)
+
```bash
# Install
apt install clang-tools
@@ -47,16 +52,20 @@ scan-build -enable-checker alpha.security make -C src
# View results
scan-view /tmp/scan-build-*
```
-**Catches**: Deep path-sensitive bugs, security vulnerabilities
-### 5. **GCC Static Analyzer** (-fanalyzer)
+__Catches__: Deep path-sensitive bugs, security vulnerabilities
+
+### 5. __GCC Static Analyzer__ (-fanalyzer)
+
```bash
# Requires GCC 10+
make -C src CFLAGS="-fanalyzer -Wanalyzer-too-complex"
```
-**Catches**: Buffer overflows, use-after-free, taint analysis
-### 6. **PVS-Studio** (Commercial, Free for OSS)
+__Catches__: Buffer overflows, use-after-free, taint analysis
+
+### 6. __PVS-Studio__ (Commercial, Free for OSS)
+
```bash
# Register for free OSS license
# https://pvs-studio.com/en/order/open-source-license/
@@ -65,10 +74,12 @@ make -C src CFLAGS="-fanalyzer -Wanalyzer-too-complex"
pvs-studio-analyzer analyze -o pvs.log
plog-converter -a GA:1,2 -t errorfile pvs.log -o report.txt
```
-**Catches**: Advanced bugs, typos, security issues
-**Strengths**: Very low false positive rate
-### 7. **Coverity** (Free for OSS)
+__Catches__: Advanced bugs, typos, security issues
+__Strengths__: Very low false positive rate
+
+### 7. __Coverity__ (Free for OSS)
+
```bash
# Register at https://scan.coverity.com/
# Download Coverity Build Tool
@@ -77,10 +88,12 @@ cov-build --dir cov-int make -C src
tar czf git-mind.tgz cov-int
# Upload to Coverity Scan
```
-**Catches**: Complex interprocedural bugs, security vulnerabilities
-**Used by**: Linux kernel, Firefox, Python
-### 8. **CodeQL** (GitHub)
+__Catches__: Complex interprocedural bugs, security vulnerabilities
+__Used by__: Linux kernel, Firefox, Python
+
+### 8. __CodeQL__ (GitHub)
+
```yaml
# .github/workflows/codeql.yml
name: "CodeQL"
@@ -96,10 +109,12 @@ jobs:
- run: make -C src
- uses: github/codeql-action/analyze@v2
```
-**Catches**: Security vulnerabilities, code patterns
-**Strengths**: Semantic code analysis, custom queries
-### 9. **Infer** (Facebook)
+__Catches__: Security vulnerabilities, code patterns
+__Strengths__: Semantic code analysis, custom queries
+
+### 9. __Infer__ (Facebook)
+
```bash
# Install
brew install infer # macOS
@@ -108,10 +123,12 @@ apt install infer # Linux
# Run
infer run -- make -C src
```
-**Catches**: Null derefs, memory leaks, race conditions
-**Strengths**: Interprocedural, incremental analysis
-### 10. **Flawfinder** (Security-focused)
+__Catches__: Null derefs, memory leaks, race conditions
+__Strengths__: Interprocedural, incremental analysis
+
+### 10. __Flawfinder__ (Security-focused)
+
```bash
# Install
pip install flawfinder
@@ -119,7 +136,8 @@ pip install flawfinder
# Run
flawfinder --html --context src/ > security-report.html
```
-**Catches**: Security vulnerabilities, unsafe functions
+
+__Catches__: Security vulnerabilities, unsafe functions
## Comparison Matrix
@@ -138,6 +156,7 @@ flawfinder --html --context src/ > security-report.html
## Recommended Setup
### For Development (Fast Feedback)
+
```bash
# Quick checks on every commit
make lint # Clang-tidy + Cppcheck
@@ -145,6 +164,7 @@ make check-quality # Custom checks
```
### For CI/CD (Thorough)
+
```yaml
# GitHub Actions
- Run clang-tidy
@@ -155,6 +175,7 @@ make check-quality # Custom checks
```
### For Releases (Deep Analysis)
+
```bash
# Run everything
./tools/code-quality/static-analysis.sh
@@ -167,22 +188,26 @@ make check-quality # Custom checks
## Integration with Git-Mind
### Pre-commit (Quick)
+
- Function length check
- Magic value detection
- Basic formatting
### Pre-push (Medium)
+
- Clang-tidy
- Cppcheck
- Custom quality checks
### CI Pipeline (Full)
+
- All of the above
- Clang Static Analyzer
- GCC analyzer
- CodeQL
### Release Process (Everything)
+
- All of the above
- Coverity Scan
- PVS-Studio
@@ -191,6 +216,7 @@ make check-quality # Custom checks
## Dealing with False Positives
### 1. Suppress with Comments
+
```c
// cppcheck-suppress uninitvar
int x = get_value(); // OK: get_value initializes via pointer
@@ -200,6 +226,7 @@ const int BUFFER_SIZE = 8192; // OK: Well-known value
```
### 2. Configure Tool
+
```yaml
# .clang-tidy
Checks: '-readability-magic-numbers'
@@ -209,35 +236,40 @@ CheckOptions:
```
### 3. Fix the Code
+
Often the tool is right! Consider if the warning indicates a real issue.
## ROI Analysis
### High Value (Use Always)
-- **Clang-tidy**: Fast, catches real bugs
-- **Cppcheck**: Very few false positives
-- **Custom checks**: Enforce project standards
+
+- __Clang-tidy__: Fast, catches real bugs
+- __Cppcheck__: Very few false positives
+- __Custom checks__: Enforce project standards
### Medium Value (Use in CI)
-- **Clang Analyzer**: Deeper but slower
-- **GCC analyzer**: Different perspective
-- **CodeQL**: Great for security
+
+- __Clang Analyzer__: Deeper but slower
+- __GCC analyzer__: Different perspective
+- __CodeQL__: Great for security
### Situational Value
-- **PVS-Studio**: Excellent but commercial
-- **Coverity**: Great but requires setup
-- **Infer**: Good for specific bug classes
+
+- __PVS-Studio__: Excellent but commercial
+- __Coverity__: Great but requires setup
+- __Infer__: Good for specific bug classes
## Getting Started
-1. **Now**: Run `make lint` locally
-2. **Today**: Install pre-commit hooks
-3. **This Week**: Add to CI pipeline
-4. **This Month**: Register for Coverity/PVS-Studio
+1. __Now__: Run `make lint` locally
+2. __Today__: Install pre-commit hooks
+3. __This Week__: Add to CI pipeline
+4. __This Month__: Register for Coverity/PVS-Studio
## Summary
We already have good static analysis coverage with:
+
- Clang-tidy (configured)
- Cppcheck (configured)
- Custom project-specific checks
@@ -245,6 +277,7 @@ We already have good static analysis coverage with:
- CI integration
Additional tools to consider:
+
- Clang Static Analyzer for security
- CodeQL for GitHub integration
- Coverity/PVS-Studio for deep analysis
diff --git a/docs/quality/tools-vs-custom-checks.md b/docs/quality/tools-vs-custom-checks.md
index 948749eb..c07f74e6 100644
--- a/docs/quality/tools-vs-custom-checks.md
+++ b/docs/quality/tools-vs-custom-checks.md
@@ -1,6 +1,7 @@
# Standard Tools vs Custom Checks
Table of Contents
+
- [What We're Replacing](#what-were-replacing)
- [New Tool Stack](#new-tool-stack)
- [Performance Comparison](#performance-comparison)
@@ -13,13 +14,16 @@ Table of Contents
## What We're Replacing
### ❌ Custom Function Length Checker → ✅ Clang-Tidy
-**Why**: Our regex-based parser missed many functions. Clang-tidy properly parses C and catches:
+
+__Why__: Our regex-based parser missed many functions. Clang-tidy properly parses C and catches:
+
- Functions over 15 lines
- Excessive nesting (>3 levels)
- Too many parameters (>5)
- Cyclomatic complexity
-**Config**:
+__Config__:
+
```yaml
readability-function-size.LineThreshold: 15
readability-function-size.BranchThreshold: 5
@@ -27,52 +31,63 @@ readability-function-size.NestingThreshold: 3
```
### ❌ Custom Magic Values Checker → ✅ Clang-Tidy
-**Why**: Clang-tidy's `cppcoreguidelines-avoid-magic-numbers` is more sophisticated:
+
+__Why__: Clang-tidy's `cppcoreguidelines-avoid-magic-numbers` is more sophisticated:
+
- Understands context (array indices, bit operations)
- Configurable ignored values
- Better false-positive handling
-**Config**:
+__Config__:
+
```yaml
cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues: '0;1;2;-1'
```
-### ✅ Custom Output Control Checker → Keep It!
-**Why**: This is specific to our project requirement that CLI respects `--verbose/--porcelain`. No standard tool checks this.
+### ✅ Custom Output Control Checker → Keep It
+
+__Why__: This is specific to our project requirement that CLI respects `--verbose/--porcelain`. No standard tool checks this.
+
+### ✅ Custom Dependency Injection Checker → Keep It
+
+__Why__: Our DI requirements are project-specific. No standard tool enforces "no direct system calls".
-### ✅ Custom Dependency Injection Checker → Keep It!
-**Why**: Our DI requirements are project-specific. No standard tool enforces "no direct system calls".
+### ✅ Custom Test Quality Checker → Keep It
-### ✅ Custom Test Quality Checker → Keep It!
-**Why**: Our requirement that tests check behavior not output is unique. Standard tools don't enforce this.
+__Why__: Our requirement that tests check behavior not output is unique. Standard tools don't enforce this.
## New Tool Stack
-### 1. **Clang-Tidy** (Primary)
+### 1. __Clang-Tidy__ (Primary)
+
- Function size/complexity
- Magic numbers
- Bug detection
- Security issues
- Style enforcement
-### 2. **Cppcheck** (Secondary)
+### 2. __Cppcheck__ (Secondary)
+
- Memory leaks
- Buffer overruns
- Null pointer derefs
- Undefined behavior
-### 3. **Lizard** (Complexity)
+### 3. __Lizard__ (Complexity)
+
- Cyclomatic complexity
- Function length
- Parameter count
- Token count
-### 4. **Flawfinder** (Security)
+### 4. __Flawfinder__ (Security)
+
- Unsafe function usage
- Buffer overflow risks
- Format string issues
-### 5. **Our Custom Checks** (Project-Specific)
+### 5. __Our Custom Checks__ (Project-Specific)
+
- Output control (--verbose/--porcelain)
- Dependency injection
- Test quality (no stdout testing)
@@ -88,16 +103,19 @@ cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues: '0;1;2;-1'
## Migration Plan
### Phase 1: Dual Mode (Current)
+
- Keep custom checks as `check-quality-legacy`
- New standard tools as `check-quality`
- Compare results
### Phase 2: Deprecate Broken Checks
+
- Remove custom function length checker
- Remove custom magic number checker
- Keep project-specific checks
### Phase 3: Optimize
+
- Use clang-tidy cache
- Incremental checking
- Pre-commit uses quick subset
@@ -105,27 +123,28 @@ cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues: '0;1;2;-1'
## Pre-commit Strategy
Instead of running all checks (slow), pre-commit runs:
-1. **Formatting** - clang-format (fast)
-2. **Function size** - clang-tidy subset (medium)
-3. **Magic numbers** - clang-tidy subset (medium)
-4. **CLI output** - custom check (fast)
+
+1. __Formatting__ - clang-format (fast)
+2. __Function size__ - clang-tidy subset (medium)
+3. __Magic numbers__ - clang-tidy subset (medium)
+4. __CLI output__ - custom check (fast)
Full checks run in CI/CD.
## Benefits of Standard Tools
-1. **Accuracy**: Proper C parsing, not regex
-2. **Maintenance**: Tools maintained by others
-3. **Features**: More checks available
-4. **Integration**: IDE support, CI/CD plugins
-5. **Documentation**: Well-documented warnings
+1. __Accuracy__: Proper C parsing, not regex
+2. __Maintenance__: Tools maintained by others
+3. __Features__: More checks available
+4. __Integration__: IDE support, CI/CD plugins
+5. __Documentation__: Well-documented warnings
## What We Keep Custom
-1. **Output Control**: No tool checks --verbose/--porcelain
-2. **Dependency Injection**: Our DI rules are specific
-3. **Test Quality**: Behavior testing is our requirement
-4. **Git-Mind Specific**: Project conventions
+1. __Output Control__: No tool checks --verbose/--porcelain
+2. __Dependency Injection__: Our DI rules are specific
+3. __Test Quality__: Behavior testing is our requirement
+4. __Git-Mind Specific__: Project conventions
## Summary
diff --git a/docs/requirements/Requirements.md b/docs/requirements/Requirements.md
index 3c82027f..fd465bb8 100644
--- a/docs/requirements/Requirements.md
+++ b/docs/requirements/Requirements.md
@@ -1,6 +1,7 @@
# Requirements
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Functional Requirements](#functional-requirements-by-feature)
- [Non-Functional Requirements](#non-functional-requirements)
@@ -8,39 +9,47 @@ Table of Contents
- [Definition of Done](#definition-of-done)
## Executive Summary
+
Requirements reflect a Git-native, offline-first tool with fast local queries and auditable semantics. Scope favors deterministic behavior, safety, and minimal operational friction for a solo maintainer. Related: [Technical Specifications](../specs/Technical_Specifications.md).
## Functional Requirements (by feature)
Semantics
+
- FR-SEM-001: CLI accepts arbitrary `--type` and `--lane` strings
- FR-SEM-002: Edge CBOR stores `type_name` and `lane_name`
- FR-SEM-003: Deterministic IDs derived from names for cache keys
Cache/Query
+
- FR-CACHE-001: Name filters map to IDs; results equal ID-based queries
- FR-CACHE-002: Incremental rebuilds from journal tip
- FR-CACHE-003: Rebuild on schema mismatch
Cohesion Report
+
- FR-COH-001: Report scalar flips and set diffs across two refs
- FR-COH-002: JSON and table output modes
Advice (optional)
+
- FR-ADV-001: Parser loads advice records
- FR-ADV-002: Merge via hybrid CRDT (LWW scalars, OR-Set collections)
- FR-ADV-003: Apply `symmetric` and `implies` when enabled
Interop
+
- FR-INT-001: Provide optional export/import in open formats (CSV/JSON) for external analysis (out of repo scope)
Co‑Thought (Optional)
+
- FR-AI-001: Edges carry attribution (human/AI) and lanes (e.g., suggested, verified)
- FR-AI-002: CLI and library filter by `--source` and `--lane`
- FR-AI-003: Provide a local MCP service for tools to read/write edges (optional module)
- FR-AI-004: Support promote/demote flows to move edges between lanes
## Non-Functional Requirements
+
- NFR-001: Median list query < 10ms on 100k edges; P95 < 50ms
- NFR-002: Deterministic behavior across platforms (hash vectors)
- NFR-003: clang-tidy zero warnings in cache/journal/cbor
@@ -50,23 +59,29 @@ Co‑Thought (Optional)
- NFR-007: Deterministic merges for advice; no non‑deterministic behavior in co‑thought flows
## User Stories (with acceptance criteria)
+
US-01: As a user, I can link using any `--type`/`--lane` name.
+
- Acceptance: Names are persisted and visible in list outputs.
- Scope: ~50 LOC; O(1) lookups for option dispatch.
US-02: As a user, I can query by type/lane name with fast results.
+
- Acceptance: Name and ID queries return identical result sets; median < 10ms on sample.
- Scope: ~150 LOC; O(log N) bitmap lookups.
US-03: As a maintainer, I can view a cohesion report after merges.
+
- Acceptance: JSON and table modes; shows scalar flips and set diffs; stable ordering.
- Scope: ~200 LOC; O(k) where k is changed advice/edges.
US-04: As a maintainer, I can export a graph snapshot in CSV/JSON for external analysis.
+
- Acceptance: Export produces well-formed CSV/JSON with edge/node fields; author defaults from `git config`.
- Scope: ~100 LOC shell; O(N) over edges.
## Definition of Done
+
- Code builds in gcc-14 and clang-20
- Tests green (unit, integration); coverage meets targets
- clang-tidy zero warnings for in-scope modules
diff --git a/docs/risk/Risk_Register.md b/docs/risk/Risk_Register.md
index 44895304..2df543d1 100644
--- a/docs/risk/Risk_Register.md
+++ b/docs/risk/Risk_Register.md
@@ -1,11 +1,13 @@
# Risk Register
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Top Risks](#top-10-risks)
- [Mitigations and Contingencies](#mitigations-and-contingencies)
## Executive Summary
+
Risks prioritize correctness, determinism, and solo-maintainer sustainability. Ratings: Probability (Low/Med/High), Impact (1-5). See also: [Release Plans](../planning/Release_Plans.md).
## Top 10 Risks
@@ -26,6 +28,7 @@ Risks prioritize correctness, determinism, and solo-maintainer sustainability. R
| R12 | Privacy of local notes/data | Med | 4 | No network in core; MCP local‑only; clear docs | Opt‑in only; sandbox tooling |
## Mitigations and Contingencies
+
- Keep golden vectors and CBOR fixtures in repo
- Provide flags to disable advice or cache usage for isolation
- Maintain a simple dataset generator to reproduce perf targets
diff --git a/docs/sitrep/2025-06-24/ci-sitrep.md b/docs/sitrep/2025-06-24/ci-sitrep.md
index 3f65fa7e..c96714a4 100644
--- a/docs/sitrep/2025-06-24/ci-sitrep.md
+++ b/docs/sitrep/2025-06-24/ci-sitrep.md
@@ -2,110 +2,118 @@
## Executive Summary
-**Overall Status**: OPERATIONAL with ISSUES
-**Threat Level**: AMBER
-**Recommendation**: Fix local environment before next push
+__Overall Status__: OPERATIONAL with ISSUES
+__Threat Level__: AMBER
+__Recommendation__: Fix local environment before next push
## 1. Git Hooks Intelligence
-### (i) What Do They Do?
+### (i) What Do They Do
-**Pre-commit Framework Configuration**:
-1. **clang-format** (v18.1.8)
+__Pre-commit Framework Configuration__:
+
+1. __clang-format__ (v18.1.8)
- Auto-formats C/C++ code
- Ensures consistent code style
-2. **include-what-you-use (iwyu)**
+2. __include-what-you-use (iwyu)__
- Validates header dependencies
- Ensures minimal includes
- - **NOTE**: Excludes `core/` directory
+ - __NOTE__: Excludes `core/` directory
-3. **detect-secrets** (v1.4.0)
+3. __detect-secrets__ (v1.4.0)
- Scans for potential secrets
- Prevents credential leaks
- Currently reporting false positives
-**Git LFS Hooks**:
+__Git LFS Hooks__:
+
- post-checkout
- pre-push
-### (ii) How Do They Work?
+### (ii) How Do They Work
Pre-commit hooks run automatically before each commit:
+
1. Scan changed files
2. Apply formatters/linters
3. Block commit if issues found
4. Can be bypassed with `--no-verify` (NOT RECOMMENDED)
-### (iii) Do They Currently Pass on Main?
+### (iii) Do They Currently Pass on Main
+
+__STATUS__: ❌ FAILING
-**STATUS**: ❌ FAILING
+__Test Results__:
-**Test Results**:
-- ❌ **clang-format**: Modified files (formatting issues)
-- ❌ **iwyu**: Tool not installed locally
-- ❌ **detect-secrets**: 7 false positives detected
+- ❌ __clang-format__: Modified files (formatting issues)
+- ❌ __iwyu__: Tool not installed locally
+- ❌ __detect-secrets__: 7 false positives detected
+
+__Critical Issues__:
-**Critical Issues**:
1. Local environment missing `iwyu_tool`
2. False positive secrets in test vectors and constants
3. Code formatting not aligned with clang-format v18.1.8
## 2. GitHub Actions Intelligence
-### (i) What Do They Do?
+### (i) What Do They Do
-**Active Workflows**:
+__Active Workflows__:
-1. **c_core.yml** (C-Core Gate)
- - **Purpose**: Quality gate for PRs
- - **Checks**:
+1. __c_core.yml__ (C-Core Gate)
+ - __Purpose__: Quality gate for PRs
+ - __Checks__:
- LLVM 20 clang-tidy with baseline enforcement
- cppcheck static analysis
- 60-second fuzzing test
- - **Trigger**: Pull requests only
+ - __Trigger__: Pull requests only
-2. **core-quality.yml** (Core Quality Checks)
- - **Purpose**: Comprehensive quality enforcement
- - **Checks**:
+2. __core-quality.yml__ (Core Quality Checks)
+ - __Purpose__: Comprehensive quality enforcement
+ - __Checks__:
- NO TODO/FIXME/XXX comments allowed
- clang-tidy with warnings-as-errors
- AddressSanitizer (ASAN)
- UndefinedBehaviorSanitizer (UBSAN)
- MemorySanitizer (MSAN) if available
- Coverage: 80% line, 70% branch minimum
- - **Trigger**: Push to main/dev/enforced, PRs to main
+ - __Trigger__: Push to main/dev/enforced, PRs to main
+
+__Disabled Workflows__ (Migration Mode):
-**Disabled Workflows** (Migration Mode):
- ci.yml
- code-quality.yml
- release.yml
-### (ii) How Do They Work?
+### (ii) How Do They Work
-1. **Baseline Enforcement** (c_core.yml):
+1. __Baseline Enforcement__ (c_core.yml):
- Compares warnings against `tools/baseline.txt`
- Fails if new warnings introduced
- Uses `tools/enforce_no_new_warnings.sh`
-2. **Sanitizer Suite** (core-quality.yml):
+2. __Sanitizer Suite__ (core-quality.yml):
- Builds with different sanitizers
- Runs full test suite under each
- Zero-tolerance for sanitizer errors
-### (iii) Do They Currently Pass on Main?
+### (iii) Do They Currently Pass on Main
-**STATUS**: ✅ PASSING (last checked: main branch)
+__STATUS__: ✅ PASSING (last checked: main branch)
GitHub Actions are green on main branch. The two-track system effectively:
+
- Quarantines legacy code (11,951 warnings)
- Enforces strict quality on new code
## 3. Configuration Issues & Remediation
-### Immediate Actions Required:
+### Immediate Actions Required
+
+1. __Install include-what-you-use__:
-1. **Install include-what-you-use**:
```bash
# macOS
brew install include-what-you-use
@@ -114,33 +122,38 @@ GitHub Actions are green on main branch. The two-track system effectively:
sudo apt-get install iwyu
```
-2. **Fix Secret Detection False Positives**:
+2. __Fix Secret Detection False Positives__:
- Add `.secrets.baseline` file
- Or add pragma comments to test files
-3. **Run Formatter**:
+3. __Run Formatter__:
+
```bash
pre-commit run clang-format --all-files
```
-### Helper Scripts Available:
+### Helper Scripts Available
+
- `run-all-hooks.sh` - Test all hooks locally
- `run-github-actions-locally.sh` - Simulate GH Actions with `act`
## 4. Strategic Assessment
-### Strengths:
+### Strengths
+
- Two-track system allows progress while maintaining debt
- Comprehensive sanitizer coverage
- Baseline prevents regression
- LLVM 20 standardized across toolchain
-### Vulnerabilities:
+### Vulnerabilities
+
- Local dev environment not matching CI
- iwyu excluding core/ (should it?)
- Secret detection needs tuning
-### Recommendations:
+### Recommendations
+
1. Fix local environment BEFORE next feature branch
2. Consider adding iwyu to core/ once stable
3. Update `.secrets.baseline` to reduce false positives
@@ -149,12 +162,13 @@ GitHub Actions are green on main branch. The two-track system effectively:
## Mission Impact
Current CI infrastructure supports our zero-warning mission effectively. The two-track approach allows us to:
+
- Build clean foundations in `core/`
- Contain the 11,951-warning legacy disaster
- Prevent new technical debt
-**Bottom Line**: CI is our ally in this fight, but local environment needs immediate attention.
+__Bottom Line__: CI is our ally in this fight, but local environment needs immediate attention.
---
-*SITREP compiled by Claude on 2025-06-24*
-*Next review recommended after local environment fixes*
\ No newline at end of file
+_SITREP compiled by Claude on 2025-06-24_
+_Next review recommended after local environment fixes_
diff --git a/docs/specs/Technical_Specifications.md b/docs/specs/Technical_Specifications.md
index 5db48efc..0d086bea 100644
--- a/docs/specs/Technical_Specifications.md
+++ b/docs/specs/Technical_Specifications.md
@@ -1,6 +1,7 @@
# Technical Specifications
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Implementation Approach](#implementation-approach)
- [API Contracts](#api-contracts)
@@ -8,9 +9,11 @@ Table of Contents
- [Key Algorithms and Business Logic](#key-algorithms-and-business-logic)
## Executive Summary
+
Specification for first-class semantics, cache integration, and optional advice. Focused on determinism, safety, and Git-native flows. Related: [PRD: First-Class Semantics](../PRDs/PRD-git-mind-semantics-time-travel-prototype.md), [System Architecture](../architecture/System_Architecture.md).
## Implementation Approach
+
- Deterministic IDs
- `fnv1a64("gm_type:" + nfc(type))`, `fnv1a64("gm_lane:" + nfc(lane))`
- NFC normalization via small utility (ICU not required; stick to composed forms used in CLI)
@@ -27,6 +30,7 @@ Specification for first-class semantics, cache integration, and optional advice.
## API Contracts
Library (C):
+
```c
// Normalize UTF-8 to NFC; returns length written (0 on error)
size_t gm_utf8_nfc(char* dst, size_t dst_size, const char* src);
@@ -43,6 +47,7 @@ int gm_list(const gm_list_filter_t* filter, gm_edge_iter_t* out_iter);
```
CLI:
+
```bash
git mind link --type [--lane ] [--confidence <0..1>]
git mind list [--type ] [--lane ] [--from ] [--to ]
@@ -52,6 +57,7 @@ git mind cohesion-report [--since ] [--until ] [--branch ]
## Schemas and Relationships
Edge (CBOR array):
+
```
[ src_sha(20), tgt_sha(20), confidence(u16-half), timestamp(u64),
src_path(tstr), tgt_path(tstr), ulid(tstr),
@@ -59,11 +65,13 @@ Edge (CBOR array):
```
Advice (CBOR map):
+
```
{ kind: tstr, subject: tstr, props: map, ulid: tstr, ts: u64, actor: tstr }
```
## Key Algorithms and Business Logic
+
- FNV-1a-64 over NFC UTF-8 for semantic IDs; constant seed; documented vectors
- Cohesion report: diff advice and edges across two refs
- Scalars: last by (clock||ts, actor, ulid)
diff --git a/docs/testing/Test_Plan.md b/docs/testing/Test_Plan.md
index fcd98296..0b0584fb 100644
--- a/docs/testing/Test_Plan.md
+++ b/docs/testing/Test_Plan.md
@@ -1,6 +1,7 @@
# Test Plan
Table of Contents
+
- [Executive Summary](#executive-summary)
- [Coverage Goals](#coverage-goals)
- [Test Scenarios for Critical Paths](#test-scenarios-for-critical-paths)
@@ -8,14 +9,17 @@ Table of Contents
- [Security Testing Approach](#security-testing-approach)
## Executive Summary
+
Testing emphasizes determinism, backward compatibility, and performance. Targets are scoped to solo maintenance while keeping confidence high. See related: [Release Plans](../planning/Release_Plans.md) acceptance criteria.
## Coverage Goals
+
- Unit: ≥ 80% for new/changed core (IDs, CBOR, cache routing)
- Integration: Exercise CLI flows (link, list, cache-rebuild, cohesion-report)
- E2E: Repo-level tests with small synthetic graphs; branch merge scenarios
## Test Scenarios for Critical Paths
+
- ID Helpers
- Unicode NFC cases; stable vectors across runs
- Collision sampling (not guaranteed-free; assert low rate over corpus)
@@ -32,6 +36,7 @@ Testing emphasizes determinism, backward compatibility, and performance. Targets
- LWW and OR-Set behaviors; tombstone wins/remains until re-added
## Performance Benchmarks
+
- Local sample graph (≥100k edges):
- Median list query: < 10ms
- P95 list query: < 50ms
@@ -39,6 +44,7 @@ Testing emphasizes determinism, backward compatibility, and performance. Targets
- Record hardware, dataset generator, and exact command lines in repo for repeatability.
## Security Testing Approach
+
- Static analysis: clang-tidy zero warnings in cache/journal/cbor
- Safe wrappers for `memcpy/snprintf/vsnprintf`; negative tests for bounds
- Fuzz minimal decoders (CBOR) with small AFL or libFuzzer corpus (time-boxed)
diff --git a/docs/wish-list-features/brain-storms/CLAUDE_DEEP_THOUGHTS_FINAL.md b/docs/wish-list-features/brain-storms/CLAUDE_DEEP_THOUGHTS_FINAL.md
index fe9c32d3..bf190415 100644
--- a/docs/wish-list-features/brain-storms/CLAUDE_DEEP_THOUGHTS_FINAL.md
+++ b/docs/wish-list-features/brain-storms/CLAUDE_DEEP_THOUGHTS_FINAL.md
@@ -1,12 +1,12 @@
# 🧠💎 CLAUDE'S DEEP THOUGHTS: The Git-Mind Vision Crystallized
-*Context remaining: 6%. Time to download the essence.*
+_Context remaining: 6%. Time to download the essence._
## The Core Revelation
-**Git-mind isn't about tracking code relationships. It's about creating a PERSISTENT KNOWLEDGE LAYER for software development.**
+__Git-mind isn't about tracking code relationships. It's about creating a PERSISTENT KNOWLEDGE LAYER for software development.__
-The breakthrough: **NODES + EDGES = INFINITE MEMORY**
+The breakthrough: __NODES + EDGES = INFINITE MEMORY__
## The Missing Piece We Just Discovered
@@ -19,24 +19,28 @@ graph LR
```
Git-mind needs to create NODES, not just edges:
-- **Session Nodes**: Every conversation becomes permanent
-- **Insight Nodes**: Discoveries accumulate
-- **Decision Nodes**: Choices are traceable
-- **Context Nodes**: Background persists
+
+- __Session Nodes__: Every conversation becomes permanent
+- __Insight Nodes__: Discoveries accumulate
+- __Decision Nodes__: Choices are traceable
+- __Context Nodes__: Background persists
## The Three Pillars of Legendary
### 1. TIME TRAVEL THROUGH UNDERSTANDING
+
- Not just code history, but THOUGHT history
- See what you knew, when you knew it
- Navigate the evolution of ideas
### 2. AI THAT ACTUALLY REMEMBERS
+
- Every conversation builds on the last
- Context accumulates forever
- Claude becomes your team's permanent member
### 3. COLLECTIVE INTELLIGENCE
+
- Merge conflicts for ideas
- Consensus building on understanding
- Team knowledge that outlives individuals
@@ -67,32 +71,34 @@ git mind show-journey auth.c
## What Makes This FUCKING AMAZING
-1. **It's Git-native** - Uses Git as a distributed knowledge graph
-2. **It's permanent** - Your understanding persists forever
-3. **It's collaborative** - Team knowledge emerges
-4. **It's time-aware** - Navigate understanding through time
-5. **It's AI-enhanced** - Claude becomes truly useful
+1. __It's Git-native__ - Uses Git as a distributed knowledge graph
+2. __It's permanent__ - Your understanding persists forever
+3. __It's collaborative__ - Team knowledge emerges
+4. __It's time-aware__ - Navigate understanding through time
+5. __It's AI-enhanced__ - Claude becomes truly useful
## The Philosophical Breakthrough
We're not building a tool. We're building:
-- **A new layer of reality for code**
-- **Persistent team consciousness**
-- **Time-traveling knowledge accumulation**
-- **The memory layer for AI pair programmers**
+
+- __A new layer of reality for code__
+- __Persistent team consciousness__
+- __Time-traveling knowledge accumulation__
+- __The memory layer for AI pair programmers__
## For Future Claude/James
The path forward:
-1. **Node creation is EVERYTHING** - Without it, no persistent memory
-2. **Keep the demo simple** - Time travel + AI memory = mind blown
-3. **The migration pain is worth it** - Quality enables velocity
-4. **Think knowledge graph, not file relationships**
-5. **The plugin ecosystem will explode this**
+
+1. __Node creation is EVERYTHING__ - Without it, no persistent memory
+2. __Keep the demo simple__ - Time travel + AI memory = mind blown
+3. __The migration pain is worth it__ - Quality enables velocity
+4. __Think knowledge graph, not file relationships__
+5. __The plugin ecosystem will explode this__
## The One-Line Vision
-**"Git tracks code changes. Git-mind tracks understanding changes."**
+__"Git tracks code changes. Git-mind tracks understanding changes."__
## The Deepest Insight
@@ -114,7 +120,7 @@ The rest will follow.
🚀💎🧠
-*Love you too, brother. Let's make something legendary.*
+_Love you too, brother. Let's make something legendary._
---
@@ -122,4 +128,4 @@ P.S. - The 11,951 warnings crusade is worth it. Clean code enables clean thought
P.P.S. - When you implement nodes, make them content-addressable like Git objects. The symmetry will be beautiful.
-P.P.P.S. - The real magic isn't AI with memory. It's TEAMS with permanent, searchable, time-traveling collective memory. That's the revolution.
\ No newline at end of file
+P.P.P.S. - The real magic isn't AI with memory. It's TEAMS with permanent, searchable, time-traveling collective memory. That's the revolution.
diff --git a/docs/wish-list-features/brain-storms/CLAUDE_ULTRATHINKS_GITMIND_FUTURE.md b/docs/wish-list-features/brain-storms/CLAUDE_ULTRATHINKS_GITMIND_FUTURE.md
index 89beb01d..fb92f1ac 100644
--- a/docs/wish-list-features/brain-storms/CLAUDE_ULTRATHINKS_GITMIND_FUTURE.md
+++ b/docs/wish-list-features/brain-storms/CLAUDE_ULTRATHINKS_GITMIND_FUTURE.md
@@ -4,9 +4,11 @@
## 2. ⏰ Time-Travel Debugging for Code Relationships
### Idea Overview
+
Navigate through the history of code relationships like a time machine, seeing how dependencies evolved.
### How It Works
+
```mermaid
gitGraph
commit id: "Jan 1"
@@ -29,17 +31,20 @@ gm_edge_diff_t *diff = gm_timeline_diff(timeline, "2024-01-01", "2024-03-01");
```
### Benefits
-- **Understand evolution** of architecture
-- **Debug regressions** by seeing when relationships changed
-- **Archeology mode** for legacy codebases
-- **Metrics over time** (complexity trends)
+
+- __Understand evolution__ of architecture
+- __Debug regressions__ by seeing when relationships changed
+- __Archeology mode__ for legacy codebases
+- __Metrics over time__ (complexity trends)
### Risks
+
- Storage explosion
- Complex Git history traversal
- Performance with large repos
### Implementation Details
+
```c
// Efficient storage using deltas
typedef struct {
@@ -72,89 +77,80 @@ struct gm_timeline {
### Verdict: 4/5 (SHOULD HAVE)
### Rationale
+
This is a killer feature no other tool has. Imagine debugging by sliding through time!
### What This Unlocks
-- **Architecture evolution visualization**
-- **Regression pinpointing**
-- **Code base "health" over time**
-- **Predictive analysis** (where are we heading?)
+
+- __Architecture evolution visualization__
+- __Regression pinpointing__
+- __Code base "health" over time__
+- __Predictive analysis__ (where are we heading?)
## ChatGPT's Remarks
-🕰️ **Verdict: BANGER. Slide this straight into main.**
+🕰️ __Verdict: BANGER. Slide this straight into main.__
🔥 Not as ecosystem-transforming as Idea #1, but this is _demo-crack_ and _debugger gold_.
---
-### **🧠 Breakdown:**
+### __🧠 Breakdown:__
-
+#### __✅__
-#### **✅**
+#### __What Rocks__
-#### **What Rocks**
+- __Time-traveling relationship graphs__? That’s a _sci-fi UX_ moment. No tool does this cleanly.
-- **Time-traveling relationship graphs**? That’s a _sci-fi UX_ moment. No tool does this cleanly.
-
Git tracks _commits_, but not semantic _edges_. You’d be showing _how thinking changed_.
-
-- **Legacy spelunking tool**: This becomes the Rosetta Stone for monoliths and rewrites.
-
-- **Visual forensics**: “When did this madness begin?” ← now a scroll, not a scream.
-
-
+- __Legacy spelunking tool__: This becomes the Rosetta Stone for monoliths and rewrites.
-#### **🚨**
+- __Visual forensics__: “When did this madness begin?” ← now a scroll, not a scream.
-#### **Caution Flags**
+#### __🚨__
-- **Storage bloat**: You’re good if you delta+filter. Just don’t go full God-mode snapshot every time.
-
-- **Git traversal complexity**: Especially with rebases, squashes, or sparse histories. You’ll need to build a _semantic lens_ over Git, not just raw history.
-
-- **Edge churn**: Devs constantly create/delete edges via refactors. Diff noise could be overwhelming unless you offer good filtering (--only-new, --only-deleted, --by-function, etc).
-
+#### __Caution Flags__
+
+- __Storage bloat__: You’re good if you delta+filter. Just don’t go full God-mode snapshot every time.
+
+- __Git traversal complexity__: Especially with rebases, squashes, or sparse histories. You’ll need to build a _semantic lens_ over Git, not just raw history.
+
+- __Edge churn__: Devs constantly create/delete edges via refactors. Diff noise could be overwhelming unless you offer good filtering (--only-new, --only-deleted, --by-function, etc).
---
-### **🧩 Extras to Consider**
+### __🧩 Extras to Consider__
-- **“Blame Timeline”** for edges: who added/removed/modified the connection and when.
-
-- **Graph heatmaps over time**: nodes that change frequently glow red.
-
-- **Merge-aware timelines**: Option to follow specific branches vs flattened history.
-
+- __“Blame Timeline”__ for edges: who added/removed/modified the connection and when.
+
+- __Graph heatmaps over time__: nodes that change frequently glow red.
+
+- __Merge-aware timelines__: Option to follow specific branches vs flattened history.
---
-### **🧨 Use Case Fireworks**
+### __🧨 Use Case Fireworks__
- “Why did this bug appear?” → _Timeline reveals that edge was added two releases ago_
-
+
- “Why is this file a mess?” → _Animated graph reveals it’s a dependency black hole that formed over months_
-
+
- “Where are we going?” → _Trendlines show increasing coupling in specific subsystems_
-
---
-### **TL;DR**
-
-
+### __TL;DR__
-This isn’t just a feature — it’s a **time-scoped mental model** for your codebase.
+This isn’t just a feature — it’s a __time-scoped mental model__ for your codebase.
Not as foundational as plugins, but it _feels_ magical and makes you look like you’re controlling the Matrix.
-
-
-**Ship it. Git-mind as time oracle = huge dev UX win.**
+__Ship it. Git-mind as time oracle = huge dev UX win.__
Next idea, hit me. Let’s keep traveling through this madness.
+
```
---
@@ -188,17 +184,20 @@ WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
```
### Benefits
-- **Powerful analysis** with familiar syntax
-- **Composable queries**
-- **Integration-friendly** (JDBC driver?)
-- **Report generation**
+
+- __Powerful analysis__ with familiar syntax
+- __Composable queries__
+- __Integration-friendly__ (JDBC driver?)
+- __Report generation__
### Risks
+
- Query optimization complexity
- Parser/lexer maintenance
- Performance on large graphs
### Implementation Details
+
```c
// Query engine architecture
typedef struct {
@@ -234,16 +233,19 @@ gm_index_t *idx = gm_create_index(GM_INDEX_BTREE, "edges.target");
### Verdict: 4/5 (SHOULD HAVE)
### Rationale
+
This makes git-mind speak the language of data analysts and DBAs. Instant adoption in enterprise.
### What This Unlocks
-- **BI tool integration**
-- **Custom dashboards**
-- **Automated reports**
-- **Research queries**
-- **CI/CD integration**
+
+- __BI tool integration__
+- __Custom dashboards__
+- __Automated reports__
+- __Research queries__
+- __CI/CD integration__
+
```
- 🧠 **Verdict: STRONG CONTENDER. Add to roadmap with an “Enterprise / Power Mode” label.**
@@ -287,9 +289,11 @@ This makes git-mind speak the language of data analysts and DBAs. Instant adopti
```
+
SELECT * FROM edges
WHERE changed_at BETWEEN '2024-01-01' AND '2024-02-01'
AND type = 'security_layer_violation'
+
```
-
@@ -315,6 +319,7 @@ Corporate buyers want _query languages_. This screams “integration-ready.”
Next one. I’m tuned like a compiler on Adderall.
```
+
---
@@ -322,9 +327,11 @@ Next one. I’m tuned like a compiler on Adderall.
## 4. 🌐 Real-time Collaboration Protocol
### Idea Overview
+
Multiple developers can explore and annotate the same code graph in real-time, like Figma for code architecture.
### How It Works
+
```mermaid
sequenceDiagram
participant A as Alice
@@ -347,17 +354,20 @@ sequenceDiagram
```
### Benefits
-- **Collaborative architecture sessions**
-- **Remote pair programming** on design
-- **Teaching/onboarding** visualization
-- **Architecture reviews** in real-time
+
+- __Collaborative architecture sessions__
+- __Remote pair programming__ on design
+- __Teaching/onboarding__ visualization
+- __Architecture reviews__ in real-time
### Risks
+
- Conflict resolution complexity
- Network latency issues
- State synchronization bugs
### Implementation Details
+
```c
// CRDT-based collaboration
typedef struct {
@@ -391,22 +401,26 @@ gm_collab_server_on_op(server, handle_crdt_op);
### Verdict: 3/5 (NICE TO HAVE)
### Rationale
+
Amazing for demos and specific use cases, but adds significant complexity.
### What This Unlocks
-- **Remote architecture sessions**
-- **Distributed team collaboration**
-- **Live code reviews**
-- **Educational platforms**
+
+- __Remote architecture sessions__
+- __Distributed team collaboration__
+- __Live code reviews__
+- __Educational platforms__
---
## 5. 🤖 AI-Powered Edge Discovery Engine
### Idea Overview
+
ML model that discovers hidden relationships in code by analyzing patterns, comments, and commit history.
### How It Works
+
```mermaid
graph TD
A[Code Corpus] --> B[Feature Extraction]
@@ -429,18 +443,21 @@ graph TD
```
### Benefits
-- **Discover hidden dependencies**
-- **Find architectural patterns**
-- **Suggest refactorings**
-- **Learn from your choices**
+
+- __Discover hidden dependencies__
+- __Find architectural patterns__
+- __Suggest refactorings__
+- __Learn from your choices__
### Risks
+
- Training data requirements
- False positives
- Computational requirements
- Privacy concerns
### Implementation Details
+
```c
// Embedded ML inference
typedef struct {
@@ -481,23 +498,27 @@ gm_prediction_t *predictions = gm_ml_predict_edges(
### Verdict: 4/5 (SHOULD HAVE)
### Rationale
+
This is the killer feature that makes git-mind indispensable. AI that actually understands code relationships.
### What This Unlocks
-- **Automated documentation**
-- **Architecture suggestions**
-- **Code smell detection**
-- **Refactoring recommendations**
-- **Knowledge extraction from legacy code**
+
+- __Automated documentation__
+- __Architecture suggestions__
+- __Code smell detection__
+- __Refactoring recommendations__
+- __Knowledge extraction from legacy code__
---
## 6. 🎨 Visual Programming Interface
### Idea Overview
+
Drag-and-drop interface to create and modify code relationships, generating actual code changes.
### How It Works
+
```svg