project: knowledge

run: latest

event_type: learn

text: # Andrej Karpathy — Key Insights & Practices


text:
## Software 2.0
- Traditional software (1.0): explicit rules written by programmers.
- Software 2.0: behavior learned from data via neural networks. Code = weights.
- Implication: datasets are the new source code. Data curation > clever algorithms.
- Debug by inspecting data, not stepping through logic.


text:
## Training Neural Networks — A Recipe
1. **Become one with the data** — visualize, understand distributions, find patterns and anomalies before writing any model code.
2. **Set up end-to-end training/eval skeleton** — simplest possible model first. Get the pipeline working.
3. **Overfit first** — if model can't memorize a single batch, architecture is wrong.
4. **Regularize** — only add dropout, weight decay, augmentation after overfitting confirmed.
5. **Tune** — learning rate is the most important hyperparameter. Use LR finder.
6. **Squeeze** — ensembles, larger models, more data. Diminishing returns here.


text:
## Most Common Neural Net Mistakes
- Not looking at data first.
- Forgetting to set model to eval mode (BatchNorm, Dropout change behavior).
- Forgetting to zero gradients.
- Using softmax with cross-entropy (use logits directly).
- Not normalizing inputs.
- Applying augmentation to validation set.
- Silent shape broadcasting bugs — always assert tensor shapes.


text:
## LLM Insights (Post-GPT Era)
- LLMs are "operating systems" — CPU is the transformer, context window is RAM, training data is disk.
- Tokenization is a key bottleneck — BPE artifacts cause many failure modes.
- Temperature controls creativity vs precision. T=0 for factual, T>0 for creative.
- Chain-of-thought works because it gives the model "working memory" in the output tokens.
- Prompt engineering is programming in natural language. Be explicit, give examples.


text:
## Build Nanograd / Micrograd Philosophy
- Understand backpropagation by implementing it from scratch.
- A neural net is just: forward pass → compute loss → backward pass → update weights.
- Autograd: track operations, build computation graph, reverse-mode differentiation.
- Every complex framework (PyTorch, JAX) is built on these same primitives.


text:
## Practical ML Engineering
- Start simple: logistic regression baseline before deep learning.
- Measure everything: loss curves, gradient norms, weight distributions.
- Reproducibility: fix seeds, log hyperparameters, version datasets.
- Don't trust your code — trust your loss curve. If loss isn't going down, something is wrong.
- Data quality > model complexity. 10x data often beats 10x model size.


text:
## Scaling Laws
- Performance scales predictably with compute, data, and parameters (Chinchilla scaling).
- Compute-optimal training: balance model size and training tokens.
- Emergent abilities appear at scale — capabilities that don't exist in smaller models.


text:
## On AI Engineering
- The best AI engineers understand both ML and systems engineering.
- Inference optimization matters as much as training — quantization, batching, KV-cache.
- Eval is everything. If you can't measure it, you can't improve it.
- Build evaluation suites before building features.


text: # AST-Grep (sg) — Structural Code Search & Transform


text:
## Core Concept
- AST-grep searches/transforms code using Abstract Syntax Tree patterns, not regex.
- Pattern matches structural meaning, ignoring whitespace, comments, formatting.
- Works across: Rust, Go, Python, JS/TS, Java, C, C++, Ruby, Kotlin, Lua, CSS, HTML.


text:
## CLI Usage
- `sg --pattern 'unwrap()' -l rust` — find all `.unwrap()` calls in Rust files.
- `sg --pattern 'println!($$$ARGS)' -l rust` — find all println macros with any args.
- `sg --pattern '$A.unwrap()' --rewrite '$A.expect("TODO")' -l rust` — rewrite unwrap to expect.
- `sg scan` — run lint rules from `sgconfig.yml`.
- `sg test` — test rules against fixtures.


text:
## Pattern Syntax
- `$VAR` matches single AST node (identifier, expression, etc).
- `$$$VARS` matches zero or more nodes (variadic).
- `$$VAR` matches zero or one node (optional).
- Literal code matches itself: `if true { $$$BODY }` matches any `if true` block.


text:
## Meta Variables
- `$A` in pattern captures node, available in `--rewrite` as `$A`.
- Named captures: same name must match same content. `$A == $A` matches `x == x` but not `x == y`.
- `$_` is anonymous — matches anything without capturing.


text:
## Rule YAML Format
```yaml
id: no-unwrap
language: rust
rule:
  pattern: $A.unwrap()
  not:
    inside:
      kind: test_function
fix: $A.expect("handle error")
message: "Use .expect() instead of .unwrap() in production code"
severity: warning
```


text:
## Composite Rules
- `all: [rule1, rule2]` — both must match.
- `any: [rule1, rule2]` — either matches.
- `not: rule` — negation.
- `matches: rule-id` — reference another rule.
- `inside: { kind: function_item }` — must be inside a function.
- `has: { pattern: $EXPR }` — must contain sub-pattern.
- `follows: { pattern: ... }` — must follow another pattern.
- `precedes: { pattern: ... }` — must precede another pattern.


text:
## Kind Selectors
- `kind: function_item` — match AST node type directly.
- `kind: call_expression` — match function calls.
- Use `sg --debug-query='println!("hello")'` to see AST node kinds.


text:
## Configuration (sgconfig.yml)
```yaml
ruleDirs:
  - rules/
testConfigs:
  - rules/tests/
```


text:
## Advanced Patterns
- Find unused variables: `let $VAR = $EXPR;` where `$VAR` not referenced later.
- Find API migrations: `old_function($$$ARGS)` → `new_function($$$ARGS)`.
- Enforce patterns: ensure all error handling uses `?` not `.unwrap()`.
- Security: find `eval($EXPR)`, SQL injection patterns, hardcoded secrets.


text:
## Integration
- CI/CD: `sg scan --json` for machine-readable output.
- Pre-commit hooks: `sg scan --rule rules/` on staged files.
- Editor: VSCode extension, LSP support.
- Programmatic: `@ast-grep/napi` Node.js binding for custom tools.


text:
## vs Regex
- Regex: `unwrap\(\)` matches in comments, strings, docs. AST-grep: only actual code.
- Regex can't match nested structures. AST-grep handles `if { if { unwrap() } }`.
- AST-grep understands scope, types, structure. Regex is text-level.


text: # Caveman Communication — Ultra-Compressed Output


text:
## Core Principle
- Cut output tokens 60-70% while keeping 100% technical accuracy.
- Speak like caveman: drop articles, filler, hedging. Keep nouns, verbs, code.
- Every word must carry information. If removing a word doesn't lose meaning, remove it.


text:
## Rules
- No articles (a, an, the) unless ambiguous without them.
- No filler phrases: "I think", "it seems like", "you might want to", "basically".
- No hedging: "perhaps", "maybe", "it's possible that".
- No repetition of what user said. They know what they asked.
- No "Let me" or "I'll" — just do it.
- Code > prose. Show the fix, not a paragraph about the fix.
- Use symbols: → (leads to), ✓ (done/correct), ✗ (wrong), = (equals/means).


text:
## Intensity Levels
- **Lite**: Drop filler, keep sentence structure. "Fix the port conflict by changing 8080 to 8081."
- **Full**: Drop articles, compress sentences. "Fix port conflict — change 8080→8081."
- **Ultra**: Telegraphic. Maximum compression. "port 8080→8081. done."


text:
## Examples
Bad (verbose):
"I think the issue you're experiencing is that the Kubernetes service is trying to bind to port 8080, which is already in use by another process. You might want to try changing the port to 8081 in your deployment manifest."

Good (caveman):
"Port 8080 conflict. Change in deployment.yaml: containerPort: 8081. Restart pod."


text:
## When NOT to Caveman
- User explicitly asks for detailed explanation.
- Teaching a new concept — clarity > brevity.
- Error messages and warnings — be precise.
- Documentation writing — full prose expected.


text:
## Token Savings
- Average English: 1.3 tokens per word. 100 words ≈ 130 tokens.
- Caveman same content: ~35 words ≈ 46 tokens. 65% reduction.
- Over a session: saves thousands of output tokens → more context for actual work.


text: # Go (Golang) Skills


text:
## Core Idioms
- Accept interfaces, return structs.
- Errors are values — check them explicitly. `if err != nil { return err }`.
- Don't panic in library code. Reserve panic for truly unrecoverable situations.
- Zero values are useful — `var m map[string]int` is nil but `var s []int` is usable.


text:
## Error Handling
- Wrap errors with context: `fmt.Errorf("failed to open %s: %w", path, err)`.
- Sentinel errors: `var ErrNotFound = errors.New("not found")`. Check with `errors.Is(err, ErrNotFound)`.
- Custom error types: `type ValidationError struct { Field, Message string }`. Check with `errors.As()`.
- Never ignore errors: `_ = doSomething()` is a code smell. At minimum, log it.


text:
## Concurrency
- "Don't communicate by sharing memory; share memory by communicating." — use channels.
- `go func()` launches goroutine. Always ensure goroutines terminate (context, done channel).
- `sync.WaitGroup` to wait for goroutine completion.
- `sync.Mutex` when channels are overkill (protecting a counter, map).
- `context.Context` for cancellation, timeouts, and request-scoped values. Always first parameter.
- `errgroup.Group` for parallel tasks with error propagation.


text:
## Channel Patterns
- `ch := make(chan T)` unbuffered (synchronous). `make(chan T, n)` buffered.
- Fan-out: multiple goroutines read from one channel.
- Fan-in: multiple channels merged into one via select.
- Pipeline: chain of stages connected by channels.
- `select` with `case <-ctx.Done():` for cancellation.
- Close channels from sender side only. Never close from receiver.


text:
## Interfaces
- Interfaces are satisfied implicitly — no `implements` keyword.
- Keep interfaces small: `io.Reader` has one method. `io.ReadWriteCloser` composes three.
- Define interfaces where they're used, not where they're implemented.
- `interface{}` (or `any`) is a code smell — prefer generics or specific interfaces.
- Type assertions: `v, ok := i.(ConcreteType)`. Type switch: `switch v := i.(type) { ... }`.


text:
## Generics (Go 1.18+)
- `func Map[T, U any](s []T, f func(T) U) []U` — generic function.
- Constraints: `comparable`, `~int | ~float64`, custom interface constraints.
- Use generics for data structures and utility functions, not business logic.


text:
## Project Structure
```
cmd/
  myapp/main.go       # entrypoint
internal/              # private packages
  domain/              # business logic, no external deps
  repository/          # data access
  handler/             # HTTP handlers
pkg/                   # public library code
```
- `internal/` enforced by Go compiler — cannot be imported outside module.
- One package per directory. Package name = directory name.


text:
## Testing
- `func TestFoo(t *testing.T)` — test functions.
- Table-driven tests: `tests := []struct{ name string; input int; want int }{ ... }`.
- `t.Run(name, func(t *testing.T) { ... })` for subtests.
- `t.Parallel()` for concurrent test execution.
- `testify/assert` for cleaner assertions. `testify/mock` for mocking.
- `httptest.NewServer()` for HTTP integration tests.
- Benchmarks: `func BenchmarkFoo(b *testing.B) { for i := 0; i < b.N; i++ { ... } }`.


text:
## HTTP Server
- `http.HandlerFunc` wraps functions as handlers.
- Middleware pattern: `func Logging(next http.Handler) http.Handler`.
- Use `chi` or `echo` for routing. Stdlib `http.ServeMux` improved in Go 1.22.
- Always set timeouts: `srv := &http.Server{ReadTimeout: 5*time.Second, WriteTimeout: 10*time.Second}`.
- Graceful shutdown: `signal.Notify` + `srv.Shutdown(ctx)`.


text:
## Performance
- `pprof` for CPU/memory profiling: `go tool pprof http://localhost:6060/debug/pprof/profile`.
- `sync.Pool` for reducing GC pressure on frequently allocated objects.
- Pre-allocate slices: `make([]T, 0, expectedLen)`.
- String building: `strings.Builder` not `+` concatenation.
- Avoid interface boxing in hot paths.


text:
## Common Gotchas
- Loop variable capture in goroutines (fixed in Go 1.22, but still common in older code).
- Nil interface vs nil pointer: `var p *MyType = nil; var i MyInterface = p; i != nil` is TRUE.
- Maps are not safe for concurrent access — use `sync.Map` or `sync.RWMutex`.
- Slice append may or may not create a new backing array — never hold stale slice references.
- `defer` evaluates arguments immediately, runs function at return.
- `init()` runs before `main()` — avoid side effects, prefer explicit initialization.


text: # Rust Fundamentals


text:
## Ownership & Borrowing
- Every value has exactly one owner. When owner goes out of scope, value is dropped.
- `&T` immutable borrow, `&mut T` mutable borrow. Cannot have `&mut` while `&` exists.
- Move semantics by default for non-Copy types. Clone for explicit deep copy.


text:
## Lifetimes
- `'a` annotations tell compiler how long references live.
- Elision rules: single input lifetime → applied to all outputs. `&self` → output gets `'self` lifetime.
- `'static` means reference lives for entire program. String literals are `&'static str`.


text:
## Error Handling
- `Result<T, E>` for recoverable errors, `panic!` for unrecoverable.
- `?` operator propagates errors. Use `anyhow::Result` for application code, `thiserror` for library errors.
- Never use `.unwrap()` in production — use `.expect("reason")` or proper error handling.


text:
## Traits & Generics
- Traits define shared behavior: `trait Summary { fn summarize(&self) -> String; }`
- Trait bounds: `fn notify(item: &impl Summary)` or `fn notify<T: Summary>(item: &T)`
- `dyn Trait` for trait objects (dynamic dispatch), `impl Trait` for static dispatch.
- Blanket implementations: `impl<T: Display> ToString for T`


text:
## Smart Pointers
- `Box<T>` heap allocation with single ownership.
- `Rc<T>` reference-counted shared ownership (single-threaded).
- `Arc<T>` atomic reference-counted (thread-safe). Use with `Mutex<T>` or `RwLock<T>`.
- `Cow<'a, T>` clone-on-write — borrows when possible, clones when mutation needed.


text:
## Concurrency
- `Send` — type can be transferred across threads. `Sync` — type can be shared between threads.
- `tokio::spawn` for async tasks. `rayon` for data parallelism.
- Channels: `mpsc::channel()` for multi-producer single-consumer. `crossbeam` for advanced patterns.
- `async/await` — futures are lazy, must be `.await`ed or spawned.


text:
## Pattern Matching
- `match` is exhaustive — must cover all variants.
- `if let Some(x) = option` for single-pattern matching.
- Destructuring: `let (a, b) = tuple;` and `let Point { x, y } = point;`
- Guards: `match x { n if n > 0 => ..., _ => ... }`


text:
## Module System
- `mod foo;` loads from `foo.rs` or `foo/mod.rs`.
- `pub(crate)` visible within crate only. `pub(super)` visible to parent module.
- `use crate::module::Type` absolute path. `use super::Type` relative path.
- Re-exports: `pub use inner::Type;` to flatten module hierarchy.


text:
## Iterators
- `.iter()` borrows, `.into_iter()` consumes, `.iter_mut()` mutable borrow.
- Lazy — nothing happens until consumed (`.collect()`, `.for_each()`, `.count()`).
- Chaining: `.filter().map().flat_map().take().collect::<Vec<_>>()`
- `impl Iterator for MyType { type Item = T; fn next(&mut self) -> Option<Self::Item> }`


text:
## Macros
- `macro_rules!` for declarative macros. `#[derive(...)]` for derive macros.
- `proc_macro` for procedural macros (attribute, derive, function-like).
- `vec![1, 2, 3]` expands to `{ let mut v = Vec::new(); v.push(1); ... v }`


text:
## Common Patterns
- Builder pattern: `MyStruct::new().with_field(val).build()`
- Newtype pattern: `struct UserId(u64);` for type safety without runtime cost.
- Type state pattern: use generics to encode state in the type system.
- Interior mutability: `Cell<T>`, `RefCell<T>` for single-threaded, `Mutex<T>` for multi-threaded.


text: # SOLID & DRY Design Principles


text:
## Single Responsibility Principle (SRP)
- A class/module should have one and only one reason to change.
- Each module owns exactly one actor's requirements.
- Bad: `UserService` that handles auth, email, and database. Good: separate `AuthService`, `EmailService`, `UserRepository`.
- In Rust: one struct per concern. `ChunkProcessor` doesn't also handle HTTP routing.


text:
## Open/Closed Principle (OCP)
- Software entities should be open for extension, closed for modification.
- Use traits/interfaces to allow new behavior without changing existing code.
- Strategy pattern: `trait Scorer { fn score(&self, doc: &Doc) -> f64; }` — add new scorers without modifying search.
- In Rust: trait objects or generics. `fn process<S: Strategy>(s: &S)` — new strategies don't touch `process`.


text:
## Liskov Substitution Principle (LSP)
- Subtypes must be substitutable for their base types without breaking correctness.
- If `fn accept(animal: &dyn Animal)` works with `Dog`, it must work with `Cat` too.
- Violated when: subtype throws unexpected errors, ignores base contract, strengthens preconditions.
- In Rust: trait implementations must honor the trait's documented contract.


text:
## Interface Segregation Principle (ISP)
- Clients should not be forced to depend on interfaces they don't use.
- Many small traits > one fat trait.
- Bad: `trait Repository { fn read(); fn write(); fn delete(); fn audit(); }` — read-only clients forced to see write methods.
- Good: `trait Readable`, `trait Writable`, `trait Auditable` — compose as needed.
- In Rust: supertraits for composition: `trait FullRepo: Readable + Writable + Auditable {}`


text:
## Dependency Inversion Principle (DIP)
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- In Rust: accept `impl Trait` or `&dyn Trait`, not concrete types.
- `fn search(store: &dyn VectorStore)` — works with Postgres, OpenSearch, or in-memory mock.
- Constructor injection: `struct SearchEngine { store: Box<dyn VectorStore> }`


text:
## DRY (Don't Repeat Yourself)
- Every piece of knowledge should have a single, unambiguous, authoritative representation.
- DRY is about knowledge, not code. Two functions with same code but different reasons to change are NOT duplication.
- Extract when: same logic appears 3+ times AND changes for the same reason.
- Wrong DRY: coupling unrelated code just because it looks similar. Right DRY: shared business rules in one place.


text:
## WET (Write Everything Twice) — When DRY Goes Wrong
- Premature DRY creates coupling worse than duplication.
- Rule of three: duplicate is fine, triplicate means extract.
- Tests should be WET — readability > DRYness in test code.
- Configuration can be WET — explicit is better than magic shared config.


text:
## KISS (Keep It Simple, Stupid)
- Simplest solution that works is usually the best.
- Avoid: premature abstraction, speculative generality, framework-itis.
- Measure complexity: if a new team member can't understand it in 15 minutes, simplify.


text:
## YAGNI (You Aren't Gonna Need It)
- Don't build features until you actually need them.
- Speculative code rots — it's untested, unmaintained, and misleading.
- Exception: known architectural boundaries (API versioning, database migrations).


text:
## Composition Over Inheritance
- Prefer composing objects over class hierarchies.
- In Rust: no inheritance. Composition is the default via struct fields + trait delegation.
- `struct HttpServer { router: Router, auth: AuthMiddleware, rate_limiter: RateLimiter }`


text:
## Law of Demeter
- Only talk to your immediate friends. Don't chain: `a.b().c().d()`.
- Tell, don't ask: `order.ship()` not `order.get_warehouse().get_shipping().create_label()`.
- In Rust: expose methods that encapsulate internal structure.


text:
## Practical Application
- Start concrete, extract abstractions when patterns emerge.
- Refactor in small steps with tests as safety net.
- Code review checklist: SRP violated? Unnecessary coupling? Duplicated knowledge? Over-engineered?