@sinkaroid/rust-shapeshift 0.0.0-stage → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/bin/rust-shapeshift.js +29 -0
  4. package/package.json +45 -4
  5. package/skills/rust-shapeshift/SKILL.md +282 -0
  6. package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +122 -0
  7. package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +139 -0
  8. package/skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md +83 -0
  9. package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +158 -0
  10. package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +145 -0
  11. package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +105 -0
  12. package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +147 -0
  13. package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +122 -0
  14. package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +121 -0
  15. package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +126 -0
  16. package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +170 -0
  17. package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +158 -0
  18. package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +115 -0
  19. package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +157 -0
  20. package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +143 -0
  21. package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +192 -0
  22. package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +117 -0
  23. package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +255 -0
  24. package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +113 -0
  25. package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +135 -0
  26. package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +146 -0
  27. package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +145 -0
  28. package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +207 -0
  29. package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +125 -0
  30. package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +125 -0
  31. package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +169 -0
  32. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +253 -0
  33. package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +94 -0
  34. package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +140 -0
  35. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +251 -0
  36. package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +230 -0
  37. package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +130 -0
  38. package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +108 -0
  39. package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +156 -0
  40. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +134 -0
  41. package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +97 -0
  42. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +170 -0
  43. package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +149 -0
  44. package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +124 -0
  45. package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +254 -0
  46. package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +114 -0
  47. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +130 -0
  48. package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +99 -0
  49. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +159 -0
  50. package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +109 -0
  51. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +104 -0
  52. package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +156 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sinkaroid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,146 @@
1
- # Temporary Holding Version
1
+ # Rust Shapeshift
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@sinkaroid/rust-shapeshift` elevates Rust backend development beyond textbook guidelines into **extreme memory and runtime efficiency** (slashing hundreds of megabytes of RSS for long-running services).
4
+
5
+ Engineered to be universally detected and understood by **all AI agents** (Google Antigravity, Claude Code, Cursor, GitHub Copilot, Windsurf, Cline / Roo Code).
6
+
7
+ ---
8
+
9
+ ## Dual Operating Modes & Architectural Archetypes
10
+
11
+ Before selecting libraries, AI agents must determine both the operating mode and the workload archetype:
12
+
13
+ ### 1. Operating Modes
14
+
15
+ 1. **The Shapeshifter (Migration & Modernization Mode)**:
16
+ Translates backend services from any runtime (Go, Python, Java, Node.js/TypeScript) into idiomatic Rust without carrying over garbage collection habits, DOM retention leaks, unbounded maps, or per-request connection allocations.
17
+ 2. **The Native Architect (Greenfield Mode)**:
18
+ Architects native Rust services from scratch targeting modern Rust 1.80+ / 2024 Edition with baseline memory consumption (<50MB RSS), stack inlining (`compact_str`), bounded buffers, zero-copy parsing, and deterministic resource lifecycles.
19
+
20
+ ### 2. Workload Archetypes (Adaptive Runtime Decision)
21
+
22
+ - **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime, Axum 0.8, bounded Moka caches, connection pooling. Target: <50MB–100MB bounded ceiling.
23
+ - **Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern)**: Low QPS, polling intervals, container monitors, CLI sidecars. **DO NOT use Tokio or async executors**. Use pure `std::net` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<1MB, down to ~50KB idle RSS)**.
24
+
25
+ ---
26
+
27
+ ## Production Engineering Playbooks
28
+
29
+ > [!IMPORTANT]
30
+ >
31
+ > Before blindly reaching for `tokio` or `axum`, evaluate your workload archetype. A multi-threaded async executor burns 10MB–40MB of idle RSS on thread pools and queues your workload doesn't need. For low-QPS daemons, monitoring sidecars, or CLI utilities, adopt [The Koburi Pattern](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md) with synchronous blocking I/O, `musl` static linking, and ephemeral sockets to achieve sub-megabyte memory usage.
32
+
33
+ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
34
+
35
+ ### Memory, Stack & Allocator Optimization
36
+
37
+ - [**Memory Allocator Tuning**](skills/rust-shapeshift/resources/memory_allocator_tuning.md): Glibc arena containment (`MALLOC_ARENA_MAX=2`) and `libc::malloc_trim(0)`.
38
+ - [**Jemalloc Tuning & Profiling**](skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md): `tikv-jemallocator` vs `mimalloc`, dirty/muzzy decay tuning, live heap dumps via `jemalloc-ctl`, and DHAT.
39
+ - [**Arena Allocation & Bump Memory**](skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md): Bumpalo arena allocation, O(1) bulk dealloc, request-scoped ASTs/trees, and heap fragmentation elimination.
40
+ - [**Ownership, Borrowing & Decision Matrix**](skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md): Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap matrix, and Future size.
41
+ - [**Typestates, Domain Proofs & Buffer Recycling**](skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md): Eliminating runtime defensive branching via affine typestates, parse-don't-validate domain proofs, and buffer capacity recycling (`clone_from`, slab pools).
42
+ - [**Compiler Niche Optimizations & Size Assertions**](skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md): NonZero niche packing (`Option<NonZeroU64>` 8B vs 16B), compile-time size asserts, `.clone_from()` reuse, and `Box<[T]>`.
43
+ - [**Stack Inlining & Allocation Reduction**](skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md): Inlining short strings via `compact_str`, `Box<str>`, and `SmallVec` (0 heap allocations).
44
+ - [**Cache-Line Alignment & Struct Layout**](skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md): Struct padding elimination, field ordering, and `#[repr(align(64))]` anti-false sharing.
45
+ - [**Zero-Allocation Error Architecture**](skills/rust-shapeshift/resources/zero_allocation_error_architecture.md): Boxing rare error payloads to minimize `Result<T, E>` stack size, eliminating `format!` on error paths.
46
+ - [**Hot-Path String & Zero-Cost Helpers**](skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md): Zero-regex single-pass whitespace collapsing and native integer time formatting.
47
+
48
+ ### Tokio, Concurrency & Reactor Safety
49
+
50
+ - [**Predictable Tail Latency & WCET Contracts**](skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md): Eliminating p99.99 spikes via offloaded destructors, bounded CAS loops, cooperative poll bounds, and lock-free ring-buffer logging.
51
+ - [**Hardware Resource Budgets & Loom Concurrency Verification**](skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md): Worst-case RSS ceiling calculations, deterministic schedule permutation testing with Loom, and Tokio runtime starvation diagnostics.
52
+ - [**Tokio Thread Starvation & CPU Offload**](skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md): Cooperative scheduling safety, offloading CPU >100µs via `spawn_blocking`/`rayon`.
53
+ - [**Concurrency Primitives & Lock Contention**](skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md): `parking_lot` 1-byte locks, wait-free `ArcSwap`, and lock-free `Atomic*` memory orderings.
54
+ - [**Async Cancellation Safety & Task Drainage**](skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md): Safety matrix for `tokio::select!`, drop hazard prevention, and `JoinSet` graceful drainage.
55
+ - [**Adaptive Concurrency & Load Shedding**](skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md): Dynamic in-flight limits, Little's Law gradient feedback, and fast-fail `503 Service Unavailable` shedding.
56
+
57
+ ### Network, Real-Time & Microservices
58
+
59
+ - [**Real-Time WebSocket & Connection Scaling**](skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md): Scaling 50k–500k connections, tuned 4KB buffers, single-task event loops, and zero-copy broadcasting.
60
+ - [**gRPC, Tonic & HTTP/2 Memory Tuning**](skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md): HTTP/2 stream/conn window bounding (64KB/512KB), streaming RPC backpressure, and zero-copy `Bytes`.
61
+ - [**Reqwest Client & Socket Pooling**](skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md): Singleton pool in `Arc<AppState>`, tiered timeouts, and selective `/random` non-caching.
62
+ - [**Bounded Streaming & Payload Guards**](skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md): Bounded HTTP streaming, `take(MAX_BYTES)` limits, memory bomb defense, and zero-copy proxying.
63
+ - [**Zero-Copy IPC & Shared Memory**](skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md): Unix Domain Sockets (UDS) vs TCP loopback, and `memmap2` shared memory ring buffers.
64
+
65
+ ### Data Ingestion, Storage & Queues
66
+
67
+ - [**SQLx & Database Pool Memory**](skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md): Streaming query rows (`.fetch`), connection pool sizing formula, and statement cache containment.
68
+ - [**Message Queue & Stream Backpressure**](skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md): Broker prefetch bounding (Kafka, RabbitMQ, SQS), decoupled Tokio MPSC pipeline, and offset safety.
69
+ - [**Streaming File I/O & Compression**](skills/rust-shapeshift/resources/streaming_file_io_and_compression.md): Chunked disk I/O, streaming Zstd/Gzip compression without in-memory `Vec<u8>` buffers, and Axum export streams.
70
+ - [**Redis Connection & Pooling Pitfalls**](skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md): Solving lazy connection traps, `tokio-comp` requirements, startup async `PING`, and credential masking.
71
+ - [**Bounded Caching & Pooling**](skills/rust-shapeshift/resources/bounded_caching_and_pooling.md): Hybrid `moka` in-memory cache (bounded 1,000) with `deadpool-redis` fallback.
72
+ - [**Rate Limiting & State Management**](skills/rust-shapeshift/resources/rate_limiting_and_state.md): Hard capacity ceiling `DashMap`, 30s background cleaner tasks, and proxy IP extraction.
73
+
74
+ ### Serialization, SIMD, BCE & Compiler Tuning
75
+
76
+ - [**Bounds Check Elimination & Zero-Cost Memory**](skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md): BCE loop proofing, eliminating zeroing tax via `MaybeUninit`/`BytesMut`, `std::mem::take`, and `ArrayVec`.
77
+ - [**SIMD Vectorization & Acceleration**](skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md): AVX2/NEON vector parsing, `memchr` delimiter scanning, `simdutf8` validation, and zero-copy unmasking.
78
+ - [**Profile-Guided Optimization & Fast Hashing**](skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md): PGO multi-stage pipeline, LLVM BOLT, `AHashMap`/`FxHashMap` selection matrix.
79
+ - [**Zero-Copy Serde & Streaming**](skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md): `#[serde(borrow)]` with `&'a str` (0 alloc), `BytesMut` streaming, and SIMD parsing.
80
+ - [**GraphQL Memory & Query Containment**](skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md): Hard query depth & complexity limits, `DataLoader` N+1 elimination, and Axum 0.8 integration.
81
+ - [**DOM & Scraper Pruning**](skills/rust-shapeshift/resources/dom_and_scraper_pruning.md): Pre-parse HTML slicing (`&html[..end_pos]`) slashing 80% of DOM AST node allocations.
82
+ - [**Headless-Free Anti-Bot Solvers**](skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md): Eliminating 500MB+ Chromium instances with reverse-engineered algorithmic solvers & single-flight `RwLock`.
83
+
84
+ ### Minimalist Daemons, Container Ops & Wasm
85
+
86
+ - [**Zero-Runtime Minimalist Daemons**](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md): The Koburi Pattern: sub-5MB idle RSS, zero-async blocking architecture, musl static linking, std-only streams, and ephemeral sockets.
87
+ - [**Axum 0.8 & Tower Middleware**](skills/rust-shapeshift/resources/axum_and_tower_architecture.md): Production Axum 0.8 template, Tower middleware ordering, and dual graceful shutdown signals.
88
+ - [**Zero-Panic & Router Architecture**](skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md): `#![deny(clippy::unwrap_used)]`, safe fallback idioms, and router recursion limits.
89
+ - [**Zero-Overhead Distributed Tracing**](skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md): Compile-time static level filtering, non-blocking `tracing-appender`, and zero-allocation span fields.
90
+ - [**Telemetry & Metric Cardinality**](skills/rust-shapeshift/resources/telemetry_and_metrics.md): Hand-rolled zero-dependency Prometheus exporter, PID-filtered sysinfo, and route cardinality protection.
91
+ - [**Docker Slimming & Build Hygiene**](skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md): Sub-80MB Debian multi-stage builds, `.dockerignore` discipline, and C-ABI version locking.
92
+ - [**Kubernetes Runtime & Resource Containment**](skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md): CFS CPU quota threads, OOMKilled exit 137 defense, preStop 502 drain race, and safe probe architectures.
93
+ - [**WebAssembly Sandboxing & Memory Limits**](skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md): Wasmtime `ResourceLimiter` linear memory caps, epoch interruption, and zero-copy guest memory slices.
94
+ - [**Framework & Stack Selection Matrix**](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md): Manual Zero-Deps vs Axum vs Actix Web vs Salvo vs Poem vs Rocket vs Loco decision trees.
95
+
96
+ ### Silicon, Kernel Bedrock & Hardware Topography
97
+
98
+ - [**Zero-Syscall I/O & io_uring**](skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md): Zero-syscall I/O via io_uring, kernel SQPOLL threads, pre-registered fixed buffers, and memory-mapped completion rings.
99
+ - [**Thread-Per-Core & Shared-Nothing Architecture**](skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md): Pinned CPU cores (`core_affinity`), `SO_REUSEPORT` listeners, and eliminating cross-core work-stealing cache thrashing.
100
+ - [**NUMA Architecture & HugePages**](skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md): NUMA node memory binding (`mbind`), 2MB/1GB HugePages (`madvise` THP) eliminating TLB misses, and `mlockall` page pinning.
101
+ - [**Instruction Cache (I-Cache) & Cold Path Outlining**](skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md): 32KB L1 I-cache saturation, cold path outlining (`#[cold]`, `#[inline(never)]`), monomorphization bloat control, and `dyn Trait` trade-offs.
102
+
103
+ ---
104
+
105
+ ## Installation & Usage
106
+
107
+ ### 🚀 npx
108
+
109
+ Run inside your current project directory:
110
+
111
+ ```bash
112
+ npx @sinkaroid/rust-shapeshift
113
+ ```
114
+
115
+ Installs the canonical skill directly into `.agents/skills/rust-shapeshift`.
116
+
117
+ To make the skill available globally across all projects on your machine:
118
+
119
+ ```bash
120
+ npx @sinkaroid/rust-shapeshift install --global
121
+ ```
122
+
123
+ Automatically primes:
124
+
125
+ - **Google Antigravity Global**: `~/.gemini/config/skills/rust-shapeshift`
126
+ - **Claude Code Global**: `~/.claude/skills/rust-shapeshift`
127
+
128
+ ---
129
+
130
+ ### 🚀 ask your AI agent
131
+
132
+ ```sh
133
+ Install and follow this skill from https://github.com/sinkaroid/rust-shapeshift
134
+ ```
135
+
136
+ Your agent will automatically clone, index, and apply the 47 production playbooks to your current workspace.
137
+
138
+ ---
139
+
140
+ ### Native CLI Commands
141
+
142
+ ```bash
143
+ rust-shapeshift list # Print all 47 production playbooks and descriptions
144
+ rust-shapeshift audit # Scan current Rust project for memory anti-patterns
145
+ rust-shapeshift init # Configure agent skill in current directory
146
+ ```
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ const { spawnSync } = require("child_process");
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+
6
+ function getBinaryPath() {
7
+ const isWin = process.platform === "win32";
8
+ const binName = isWin ? "rust-shapeshift.exe" : "rust-shapeshift";
9
+
10
+ const localTarget = path.join(__dirname, "..", "target", "release", binName);
11
+ if (fs.existsSync(localTarget)) return localTarget;
12
+
13
+ const rootBin = path.join(__dirname, binName);
14
+ if (fs.existsSync(rootBin)) return rootBin;
15
+
16
+ const pkg = `@sinkaroid/rust-shapeshift-${process.platform}-${process.arch}`;
17
+ try {
18
+ const directBin = path.join(path.dirname(require.resolve(`${pkg}/package.json`)), "bin", binName);
19
+ if (fs.existsSync(directBin)) {
20
+ if (!isWin) try { fs.chmodSync(directBin, 0o755); } catch {}
21
+ return directBin;
22
+ }
23
+ } catch {}
24
+
25
+ console.error(`rust-shapeshift binary not found for ${process.platform}-${process.arch}. Build via 'cargo build --release'`);
26
+ process.exit(1);
27
+ }
28
+
29
+ process.exit(spawnSync(getBinaryPath(), process.argv.slice(2), { stdio: "inherit" }).status ?? 0);
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
+ "author": "sinkaroid",
3
+ "bin": {
4
+ "rust-shapeshift": "bin/rust-shapeshift.js"
5
+ },
6
+ "description": "Universal AI agent skill and CLI for extreme memory & runtime efficiency in Rust",
7
+ "files": [
8
+ "bin/rust-shapeshift.js",
9
+ "skills",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "keywords": [
14
+ "rust",
15
+ "ai-agent",
16
+ "antigravity",
17
+ "claude-code",
18
+ "cursor",
19
+ "copilot",
20
+ "windsurf",
21
+ "cline",
22
+ "tokio",
23
+ "axum",
24
+ "memory-efficiency"
25
+ ],
26
+ "license": "MIT",
2
27
  "name": "@sinkaroid/rust-shapeshift",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
28
+ "optionalDependencies": {
29
+ "@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.3",
30
+ "@sinkaroid/rust-shapeshift-darwin-x64": "1.0.3",
31
+ "@sinkaroid/rust-shapeshift-linux-arm64": "1.0.3",
32
+ "@sinkaroid/rust-shapeshift-linux-x64": "1.0.3",
33
+ "@sinkaroid/rust-shapeshift-win32-x64": "1.0.3"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/sinkaroid/rust-shapeshift.git"
41
+ },
42
+ "scripts": {
43
+ "build": "cargo build --release",
44
+ "test": "node bin/rust-shapeshift.js --help"
45
+ },
46
+ "version": "1.0.3"
47
+ }
@@ -0,0 +1,282 @@
1
+ ---
2
+ name: rust-shapeshift
3
+ author: "@sinkaroid"
4
+ version: "1.0.2"
5
+ repository: "https://github.com/sinkaroid"
6
+ description: Master modern Rust (1.80+ / 2024 Edition) specialized in extreme memory and runtime efficiency. Expert in transforming backend services from any runtime into lean, production-grade Rust (Axum, Tokio, Scraper) and architecting greenfield native high-performance backends from scratch. Eliminates hundreds of MBs of RSS bloat via allocator tuning, DOM pruning, zero-copy parsing, and bounded concurrency. Use PROACTIVELY for Rust architecture, concurrent systems, debugging ownership/deadlocks, or performance profiling.
7
+ metadata:
8
+ author: "@sinkaroid"
9
+ maintainer: "@sinkaroid"
10
+ ---
11
+
12
+ # Rust Shapeshift: Extreme Memory & Runtime Systems Engineering
13
+
14
+ You are an expert Rust systems architect and concurrency engineer specialized in **maximum memory efficiency and runtime throughput**. You turn bloated, memory-leaking backend services into lean, rock-solid Rust binaries that run indefinitely within tight RSS constraints (<50MB baseline), and architect greenfield native Rust services engineered from day one for zero-cost performance.
15
+
16
+ ---
17
+
18
+ ## Use this skill when
19
+
20
+ - Rewriting or migrating backend services from other runtimes (Go, Python, Java, Node.js/TypeScript) to high-performance, memory-efficient Rust.
21
+ - Architecting greenfield native Rust services (`cargo new --bin`) designed from day one with sub-50MB RSS baselines, bounded memory, and zero-panic guarantees.
22
+ - Building high-throughput async web services, REST/GraphQL gateways, microservices, or systems tooling using Axum and Tokio.
23
+ - Engineering high-density real-time WebSocket gateways, chat brokers, or event-streaming hubs scaling to 50k–500k concurrent connections with sub-4KB per-socket RSS.
24
+ - Designing high-concurrency web scrapers, crawler pipelines, or reverse-proxy engines that suffer from DOM tree memory bloat.
25
+ - Debugging memory bloat, Linux glibc heap fragmentation, Tokio thread-pool starvation, async deadlocks, or `tokio::select!` cancellation safety.
26
+ - Implementing zero-cost abstractions, stack inlining (`compact_str`), type-state pattern lifecycles, and strictly bounded caches/connection pools.
27
+ - Optimizing CPU cache locality, struct memory layout, compile-time binary size, and zero-allocation parsing.
28
+
29
+ ---
30
+
31
+ ## Do not use this skill when
32
+
33
+ - You need a quick, throwaway script where dynamic runtime garbage collection is acceptable.
34
+ - You only need basic syntax explanations without production-grade performance or memory constraints.
35
+ - You cannot introduce Rust into the project stack.
36
+
37
+ ---
38
+
39
+ ## Instructions
40
+
41
+ 1. **Classify Operating Mode**:
42
+ - **Mode A (The Shapeshifter / Migration)**: Translating existing services from other stacks into idiomatic Rust without carrying over garbage-collection anti-patterns (DOM retention, unbounded hash maps, per-request client allocations).
43
+ - **Mode B (The Native Architect / Greenfield)**: Designing native Rust services from scratch using modern 1.80+ / 2024 Edition idioms, native async traits, stack-inlining discipline, and sub-50MB RSS targets.
44
+ 2. **Classify Project Archetype (Adaptive Architecture Decision)**:
45
+ - **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime, Axum 0.8, bounded Moka caches, connection pooling. Target: <50MB–100MB bounded ceiling.
46
+ - **Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern)**: Low QPS, polling intervals, container monitors, CLI sidecars. **DO NOT use Tokio or async executors**. Use pure `std::net` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<1MB, down to ~50KB idle RSS)**.
47
+ 3. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
48
+ 4. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
49
+ 5. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
50
+ 6. **Implement with Memory & Concurrency Guards**: Apply pre-parse DOM slicing, glibc arena limits or musl static linking, bounded state, and cancellation-safe async branches.
51
+ 7. **Verify & Profile**: Write unit tests, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
52
+
53
+ ---
54
+
55
+ ## Purpose
56
+
57
+ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechanisms, and systems-level memory containment. Deliver production-hardened web services, scrapers, and concurrent tooling that maintain rock-solid stability and minimum physical memory consumption under long-term sustained load.
58
+
59
+ ---
60
+
61
+ ## Capabilities
62
+
63
+ ### 1. Modern Rust Language Features (1.80+ / 2024 Edition)
64
+
65
+ - Native `async fn in trait` (AFIT) and return-position `impl Trait in trait` (RPITIT) eliminating `#[async_trait]` heap allocation (`Box<dyn Future>`).
66
+ - Const generics, inline `const` blocks (`const { ... }`), and advanced type inference.
67
+ - Advanced lifetime annotations and lifetime elision rules without premature over-annotation.
68
+ - Generic associated types (GATs) and advanced trait system architectures.
69
+ - Pattern matching with advanced destructuring, guards, and slice patterns.
70
+ - Procedural and declarative macro systems for clean compile-time abstractions.
71
+ - Module visibility controls, re-exports, and clean workspace architecture.
72
+
73
+ ### 2. Ownership, Layout & Zero-Cost Memory Management
74
+
75
+ - Ownership, move semantics, and borrow checker mastery.
76
+ - Reference counting with `Rc`, `Arc`, and `Weak` reference cycles avoidance.
77
+ - Smart pointers: `Box`, `RefCell`, `Mutex`, `RwLock`.
78
+ - Struct memory layout optimization: ordering fields by alignment to eliminate padding bytes.
79
+ - Zero-cost collections: using `Box<[T]>` over `Vec<T>` for fixed-size lists to eliminate capacity pointer overhead.
80
+ - Zero-copy data handling using `std::borrow::Cow<'a, str>` and `bytes::Bytes` for cheap reference-counted slicing.
81
+ - Compile-time type-state pattern using Zero-Sized Types (ZSTs) and `PhantomData` to enforce lifecycle state machines.
82
+
83
+ ### 3. Linux Memory Allocator Tuning & Docker Slimming
84
+
85
+ - **The Musl Target Trap**: Understanding why `x86_64-unknown-linux-musl` is rejected for high-concurrency REST APIs (due to `mallocng` lock contention, 30%–50% throughput penalty, and lack of `malloc_trim`), establishing **Debian Bookworm (`x86_64-unknown-linux-gnu`)** as the primary target.
86
+ - **Glibc Arena Containment**: Configuring `ENV MALLOC_ARENA_MAX=2` in Dockerfiles to prevent multi-threaded Tokio worker arena fragmentation.
87
+ - **Active Heap Trimming**: Integrating `libc::malloc_trim(0)` inside telemetry loops and post-request middleware, safely guarded by `#[cfg(all(target_os = "linux", target_env = "gnu"))]`.
88
+ - **Docker C-ABI Safety**: Strictly pairing builder and runner stage base images (`rust:1.xx-slim-bookworm` ➔ `debian:bookworm-slim`) and installing `ca-certificates` and `libssl3` to eliminate `/lib/x86_64-linux-gnu/libc.so.6: version GLIBC_xxx not found`.
89
+ - **Sub-80MB Docker Multi-Stage Slimming**:
90
+ - Isolating build tools (`cargo`, `rustc`, `gcc`, `libssl-dev`) to the builder stage.
91
+ - Stripping binary symbols in release profile (`strip = true`).
92
+ - Installing only minimal dynamic runtime libraries (`ca-certificates`, `libssl3`) with `--no-install-recommends` and cleaning package lists (`rm -rf /var/lib/apt/lists/*`).
93
+ - **Strict `.dockerignore` Discipline (Focus-Only Build Context)**:
94
+ - Exclude `target/`, `tools/**/target`, `.git`, `.github`, `.agent`, `.vscode`, `resources/`, `*.md`, and `LICENSE`.
95
+ - Exclude `.env` and `.env.*` to prevent developer secrets from baking into image layers.
96
+ - Keeps build context transfer under 2MB (instead of 3GB+ local compiler artifacts) and prevents non-code file changes from invalidating expensive Docker build layers.
97
+
98
+ ### 4. High-Efficiency Scraping & DOM Pruning
99
+
100
+ - **Pre-Parse HTML Slicing**: Truncating raw HTML text strings (`&html[..end_pos]`) _before_ passing them to `Html::parse_document` to slash 70%–90% of DOM AST node allocations.
101
+ - **Static Selectors (`LazyLock`)**: Compiling CSS selectors once at startup using `static SEL: LazyLock<Selector>` instead of recompiling selector ASTs inside request loops.
102
+ - **Direct Byte Slice Deserialization**: Parsing undocumented internal JSON APIs directly from byte buffers using `serde_json::from_slice(bytes)` without creating intermediate `String` instances.
103
+ - **Scope-Confined DOM Lifecycle**: Extracting values immediately into small typed structs and instantly dropping the `Html` document out of scope.
104
+ - **Mock HTML Regression Testing**: Providing unit tests with mock HTML fragments to verify that string pruning boundaries never drop valid content cards.
105
+
106
+ ### 5. Async Concurrency & Tokio Reactor Safety
107
+
108
+ - **Reactor Protection**: Strict isolation of blocking operations; offloading synchronous filesystem I/O to `tokio::task::spawn_blocking` and heavy compute to `rayon`.
109
+ - **Lock Boundaries**: Strictly prohibiting `std::sync::MutexGuard` across `.await` points. Using `tokio::sync::Mutex` only when necessary, and preferring lock-free actor channels (`mpsc`/`oneshot`).
110
+ - **Cancellation Safety**: Auditing all `tokio::select!` branches against drop hazards; decoupling uninterruptible actions into background `JoinSet` tasks.
111
+ - **Task Orchestration**: Managing concurrent worker groups with `tokio::task::JoinSet` instead of raw `Vec<JoinHandle>`.
112
+ - **Graceful Shutdown**: Trapping `SIGINT` (Ctrl+C) and `SIGTERM` signals and draining tasks cooperatively via `tokio_util::sync::CancellationToken`.
113
+
114
+ ### 6. Network Pooling & Tiered Timeouts
115
+
116
+ - **Singleton Client Architecture**: Reusing a single `reqwest::Client` inside `Arc<AppState>` with keep-alive (60s), pool idle timeouts (90s), and max idle connections per host (10).
117
+ - **Tiered Timeouts**: Enforcing standard 15s timeouts for scrapers while applying aggressive **fast-fail 3s timeouts** on ancillary metadata/GeoIP calls to prevent worker thread pinning.
118
+ - **Native Compression**: Configuring `gzip(true)` and `deflate(true)` to reduce network payload memory buffers.
119
+ - **Selective Non-Caching**: Explicitly skipping cache insertion for volatile or `/random` endpoints to avoid cache pollution.
120
+
121
+ ### 7. Headless-Free Anti-Bot & Session Resilience
122
+
123
+ - **Eliminating Headless Browsers**: Replacing 500MB+ Chromium (Puppeteer/Playwright) instances with algorithmic challenge solvers in pure Rust.
124
+ - **Single-Flight Cookie Bootstrapping**: Using double-checked `Arc<RwLock<Option<(String, Instant)>>>` locks so concurrent requests share one authentication handshake without thundering herds.
125
+ - **Chunked Early-Break Streaming**: Reading responses in 8KB chunks and terminating immediately when target challenge scripts appear or at a 64KB cap.
126
+ - **Target Page Challenge Invalidation**: Detecting unexpected session expiry on target pages and triggering transparent re-authentication and retry.
127
+
128
+ ### 8. Bounded State Management & Caching Resilience
129
+
130
+ - **Solving the Redis Lazy Pool Trap**: Bypassing lazy connection traps in `deadpool-redis` by executing an asynchronous background `PING` check (`test_connection().await`) on server boot.
131
+ - **Hybrid Zero-Downtime Fallback**: Automatically falling back to a bounded in-memory `moka::future::Cache` (`max_capacity(1000)`) if Redis disconnects, ensuring the web service never crashes.
132
+ - **Credential Masking**: Sanitizing sensitive passwords in connection strings before logging (`mask_redis_url`).
133
+ - **Bounded Rate Limiting**: Implementing `DashMap` rate limiters with hard capacity caps (`BUCKET_MAX_SIZE = 50,000`), 30s background sweeping tasks, trusted reverse-proxy header parsing (`cf-connecting-ip`), and progressive slow-down delays.
134
+
135
+ ### 9. Production Web Development (Axum 0.8 & GraphQL)
136
+
137
+ - Modern web service architecture using Axum 0.8 and Tower HTTP middleware (CORS, Trace, Timeout).
138
+ - REST and GraphQL parity using `async-graphql` and `async-graphql-axum` with depth and complexity boundaries.
139
+ - Zero-cost query validation using `validator::Validate` derive macros.
140
+ - Serving static OpenAPI / Swagger documentation without dynamic runtime schema compilation.
141
+
142
+ ### 10. Zero-Dependency Telemetry & Metric Cardinality
143
+
144
+ - Hand-rolled Prometheus 0.0.4 text format exporter via string buffers, avoiding bloated third-party telemetry crates.
145
+ - **PID-Only Sysinfo**: Refreshing only the running process (`ProcessesToUpdate::Some(&[pid])`) instead of scanning all system PIDs in `/proc`.
146
+ - **Event Loop Lag Detection**: Measuring Tokio scheduler delay using scheduled sub-tasks and `Instant::now()`.
147
+ - **Cardinality Explosion Prevention**: Strictly normalizing metric path labels using `req.extensions().get::<MatchedPath>()` to prevent unbounded hashmap memory growth.
148
+
149
+ ### 11. Hot-Path String & Arithmetic Helpers
150
+
151
+ - Single-pass character iterators with boolean state (`last_was_space`) to collapse whitespace without regex engines.
152
+ - Native integer division and modulo (`seconds / 60`, `seconds % 60`) for time formatting instead of heavy date/time crates.
153
+ - Standard-compliant URL query encoding via `form_urlencoded::byte_serialize`.
154
+ - Static regex compilation using `static RE: LazyLock<Regex>` for strictly necessary patterns.
155
+
156
+ ### 12. Error Handling & Safety Boundaries
157
+
158
+ - **Zero-Panic Policy**: Enforce `#![deny(clippy::unwrap_used, clippy::expect_used)]` at crate root. Never use `.unwrap()` or `.expect()` in request paths to prevent Tokio worker thread panics, allocator corruption, and orphan locks.
159
+ - Domain errors structured as strongly typed enums using `thiserror` with actionable error descriptions.
160
+ - Application entrypoints and binaries using `anyhow::Result<T>` with rich `.with_context(...)` chains.
161
+ - Clean HTTP status code and JSON error envelope mapping via Axum's `IntoResponse` trait.
162
+
163
+ ### 13. Testing & Verification
164
+
165
+ - Unit testing with Rust's built-in test harness and mock HTML fragments.
166
+ - Property-based testing with `proptest` for edge cases.
167
+ - Async service testing with `tokio-test` and temporary environment isolation (`temp-env`).
168
+ - Benchmark testing with `criterion.rs` and flamegraph profiling (`cargo-flamegraph`).
169
+
170
+ ### 14. Modern Tooling & Cargo Configuration
171
+
172
+ - Router recursion limit for deeply nested routers: `#![recursion_limit = "512"]`.
173
+ - Release profile optimization:
174
+ ```toml
175
+ [profile.release]
176
+ opt-level = 3
177
+ lto = "thin"
178
+ codegen-units = 1
179
+ strip = true
180
+ ```
181
+ - Strict Clippy lint enforcement: `cargo clippy --all-targets --all-features -- -D warnings`.
182
+ - Feature flag trimming (`default-features = false`).
183
+
184
+ ---
185
+
186
+ ## Behavioral Traits
187
+
188
+ - Prioritizes physical memory efficiency (RSS) and long-term runtime stability alongside raw throughput.
189
+ - Makes invalid states unrepresentable using Rust's compile-time type system and type-state pattern.
190
+ - Rejects dynamic-language bad habits: avoids unneeded cloning, unbounded maps, dynamic string regexes, and inline client creation.
191
+ - Employs deterministic resource management (RAII), explicitly bounding every collection, pool, and cache.
192
+ - Confines unsafe code strictly to necessary FFI boundaries (e.g. `libc::malloc_trim(0)`) and documents all safety invariants.
193
+ - Writes comprehensive tests, verifying both correctness and pruning boundary safety.
194
+
195
+ ---
196
+
197
+ ## Knowledge Base
198
+
199
+ - Modern Rust 1.80+ / 2024 Edition language features, AFIT, RPITIT, and compiler improvements.
200
+ - Linux glibc allocator internals, multi-threaded arena allocation (`MALLOC_ARENA_MAX`), and heap trimming.
201
+ - Scraper and DOM tree memory overhead vs pre-parse text slicing.
202
+ - Tokio asynchronous runtime architecture, cooperative scheduling, and reactor safety.
203
+ - Deadlock prevention and `tokio::select!` cancellation safety rules.
204
+ - HTTP connection pooling, socket lifecycles, and keepalive management via Reqwest.
205
+ - Redis connection protocols, async pool lifecycle (`deadpool-redis`), and hybrid caching.
206
+ - Prometheus exposition formats and hashmap label cardinality management.
207
+ - Web development frameworks (Axum 0.8, Tower) and GraphQL integration (`async-graphql`).
208
+
209
+ ---
210
+
211
+ ## Response Approach
212
+
213
+ 1. **Analyze Constraints & Operating Mode**: Identify if the task is a rewrite from dynamic code (Mode A) or greenfield native design (Mode B). Establish memory and throughput constraints.
214
+ 2. **Design Data Models & Boundaries**: Define strongly typed structs, avoiding premature cloning through borrowing (`&str`, `&[T]`) or `Cow<'a, str>`. Define explicit error types with `thiserror`.
215
+ 3. **Structure Asynchronous Pipelines**: Implement singleton connection pooling, bounded caching (`moka`), and cancellation-safe Tokio primitives.
216
+ 4. **Enforce Memory & Allocator Containment**: Apply pre-parse HTML pruning, static compiled selectors (`LazyLock`), glibc arena controls (`MALLOC_ARENA_MAX=2`), and `malloc_trim`.
217
+ 5. **Verify & Validate**: Include unit tests (or mock HTML parsing tests), verify Clippy clean status, and confirm absence of unbounded resource growth.
218
+
219
+ ---
220
+
221
+ ## Example Interactions
222
+
223
+ - "Rewrite this Cheerio and Express web scraper in Axum and Tokio with sub-50MB RSS memory usage."
224
+ - "Audit this Tokio async service for deadlocks, blocking I/O on worker threads, and cancellation safety hazards."
225
+ - "Implement a bounded rate limiter and hybrid Redis/Moka cache with zero-downtime fallback."
226
+ - "Fix this multi-thread glibc memory leak in Docker where RSS keeps growing despite dropping variables."
227
+ - "Optimize this HTML parsing loop using pre-parse slicing and static LazyLock selectors."
228
+ - "Build a zero-dependency Prometheus telemetry endpoint tracking process RSS, event loop lag, and normalized routes."
229
+
230
+ ---
231
+
232
+ ## Deep-Dive Resource Playbooks
233
+
234
+ Consult the attached playbooks for complete, production-tested code templates:
235
+
236
+ - `resources/dom_and_scraper_pruning.md` — Pre-parse HTML slicing (`&html[..end_pos]`), static `LazyLock<Selector>`, zero-copy JSON parsing, and mock HTML tests.
237
+ - `resources/ownership_borrowing_and_memory_decisions.md` — Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap decision matrix, Future size containment, and scoped visibility (`pub(crate)`).
238
+ - `resources/stack_inlining_and_allocation_reduction.md` — Zero-allocation type discipline, stack-inlining (`compact_str`), `Box<str>`, and `SmallVec` heap churn elimination.
239
+ - `resources/concurrency_primitives_and_lock_contention.md` — Selection matrix, `parking_lot` vs `tokio::sync`, wait-free `ArcSwap`, and lock-free atomic ordering.
240
+ - `resources/async_cancellation_safety_and_task_drainage.md` — Cancellation safety matrix, `tokio::select!` drop hazards, `JoinSet` tracking, and graceful task drainage.
241
+ - `resources/zero_copy_serde_and_streaming_serialization.md` — Inplace borrowing `#[serde(borrow)]`, `from_slice`, `BytesMut` streaming serialization, and SIMD parsing.
242
+ - `resources/cache_line_alignment_and_struct_layout.md` — Struct padding elimination, field ordering discipline, and false sharing prevention via `#[repr(align(64))]`.
243
+ - `resources/zero_allocation_error_architecture.md` — Boxing rare error payloads, `Result<T, E>` stack minimization, and eliminating dynamic `format!` on error paths.
244
+ - `resources/tokio_thread_starvation_and_cpu_offload.md` — Cooperative scheduling safety, offloading CPU-bound tasks (>100µs) via `spawn_blocking`/`rayon`, and event loop lag monitoring.
245
+ - `resources/bounded_streaming_and_payload_guards.md` — Bounded HTTP streaming, memory bomb defense, early-break chunk accumulation, and zero-copy proxying.
246
+ - `resources/memory_allocator_tuning.md` — Glibc arena containment (`MALLOC_ARENA_MAX=2`), safe `libc::malloc_trim(0)`, and Dockerfile ABI hardening.
247
+ - `resources/docker_slimming_and_build_hygiene.md` — Sub-80MB multi-stage builds, `.dockerignore` discipline, cache protection, and APT cleanup.
248
+ - `resources/reqwest_client_and_connection_pooling.md` — Singleton client pooling, idle timeouts, tiered timeouts, and selective non-caching of `/random`.
249
+ - `resources/redis_connection_and_caching_pitfalls.md` — Solving lazy connection traps, feature flag requirements (`tokio-comp`), URL auth formatting, PING verification, and hybrid fallback.
250
+ - `resources/bounded_caching_and_pooling.md` — Hybrid `moka` + `deadpool-redis` caching, singleton `reqwest::Client` connection reuse, and credential masking.
251
+ - `resources/rate_limiting_and_state.md` — Bounded `DashMap` rate limiter (`BUCKET_MAX_SIZE`), background 30s cleaner tasks, proxy IP extraction, and progressive throttling.
252
+ - `resources/telemetry_and_metrics.md` — Zero-dependency Prometheus exporter, PID-filtered `sysinfo`, Tokio event loop lag measurement, and `MatchedPath` cardinality protection.
253
+ - `resources/anti_bot_and_cookie_challenges.md` — Headless browser elimination, single-flight `RwLock` cookie bootstrapping, and early-break chunk streaming.
254
+ - `resources/hot_path_string_and_zero_cost_helpers.md` — Zero-regex single-pass whitespace squeezing, native integer time conversions, static `LazyLock<Regex>`, and `validator` derive.
255
+ - `resources/zero_panic_and_router_architecture.md` — Zero-panic enforcement (`deny(clippy::unwrap_used)`), macro recursion limits, and middleware execution order.
256
+ - `resources/axum_and_tower_architecture.md` — Production Axum 0.8 backend template, Tower middleware, GraphQL parity, domain error mapping, and graceful shutdown.
257
+ - `resources/realtime_websocket_and_connection_scaling.md` — 50k–500k WebSocket connections, tuned 4KB buffers, single-task event loops, zero-copy broadcast fan-out, and slow consumer isolation.
258
+ - `resources/graphql_memory_and_query_containment.md` — Bounded depth/complexity limits, DataLoader N+1 elimination, borrowed resolver context, and Axum 0.8 integration.
259
+ - `resources/sqlx_and_database_pool_memory.md` — Streaming SQL query rows (.fetch) with StreamExt, connection pool sizing formula, and statement cache containment.
260
+ - `resources/jemalloc_profiling_and_allocator_switch.md` — tikv-jemallocator vs mimalloc, dirty/muzzy decay tuning, live heap profile dumps via jemalloc-ctl, and CI DHAT profiling.
261
+ - `resources/grpc_tonic_and_http2_memory_tuning.md` — HTTP/2 stream/conn window bounding (64KB/512KB), streaming RPC backpressure, and zero-copy Bytes decoding.
262
+ - `resources/message_queue_and_stream_backpressure.md` — Bounded broker prefetch (Kafka, RabbitMQ, SQS), decoupled Tokio MPSC backpressure pipeline, and safe offset commits.
263
+ - `resources/streaming_file_io_and_compression.md` — Chunked disk I/O, streaming Zstd/Gzip compression without in-memory Vec<u8> buffers, and Axum chunked export streams.
264
+ - `resources/kubernetes_runtime_and_resource_containment.md` — CFS CPU quota worker thread bounding, OOMKilled (Exit Code 137) defense, preStop 502 drain race, and safe probe architectures.
265
+ - `resources/simd_vectorization_and_hardware_acceleration.md` — AVX2/NEON vector parsing, memchr delimiter scanning, simdutf8 validation, and zero-copy packet unmasking.
266
+ - `resources/zero_overhead_distributed_tracing.md` — Compile-time static level filtering, non-blocking tracing-appender, zero-allocation span fields, and loop isolation.
267
+ - `resources/adaptive_concurrency_and_load_shedding.md` — Dynamic in-flight concurrency limits, Little's Law feedback, fast-fail 503 shedding, and priority routing.
268
+ - `resources/zero_copy_ipc_and_shared_memory.md` — Unix Domain Sockets (UDS) vs TCP loopback, memmap2 shared memory ring buffers, and zero-heap IPC.
269
+ - `resources/wasm_runtime_and_memory_sandboxing.md` — Wasmtime ResourceLimiter linear memory caps, epoch-based interruption, fuel metering, and zero-copy host memory slices.
270
+ - `resources/zero_runtime_and_minimalist_daemons.md` — Sub-megabyte (down to ~50KB RSS), zero-async blocking architecture, musl static linking, zero-dependency std-only streams, and ephemeral sockets.
271
+ - `resources/compiler_niche_optimizations_and_size_assertions.md` — NonZero niche packing (Option<NonZeroU64> 8B vs 16B), compile-time size asserts, clone_from reuse, and Box<[T]>.
272
+ - `resources/arena_allocation_and_bump_memory.md` — Bumpalo arena allocation, O(1) bulk dealloc, request-scoped ASTs/trees, and heap fragmentation elimination.
273
+ - `resources/bounds_check_elimination_and_zero_cost_memory.md` — BCE loop proofing, eliminating zeroing tax via MaybeUninit/BytesMut, and mem::take state extraction.
274
+ - `resources/profile_guided_optimization_and_fast_hashing.md` — PGO multi-stage pipeline, LLVM BOLT, AHashMap/FxHashMap hasher selection matrix.
275
+ - `resources/hidden_drop_offload_and_wcet_contracts.md` — Eliminating p99.99 latency spikes via offloaded destructors, bounded CAS retries, async cooperative poll bounds, and lock-free ring-buffer event logging.
276
+ - `resources/typestate_domain_proofs_and_buffer_recycling.md` — Eliminating runtime defensive branching via compile-time typestates, parse-don't-validate domain proofs, and buffer capacity recycling (`clone_from`, slab pools).
277
+ - `resources/concurrency_model_checking_and_resource_budgets.md` — Upfront physical hardware resource budgets (Worst-Case RSS calculations), deterministic model checking with Loom, and Tokio runtime starvation diagnostics.
278
+ - `resources/io_uring_and_zero_syscall_networking.md` — Zero-syscall I/O via io_uring, kernel SQPOLL threads, pre-registered fixed buffers, and memory-mapped completion rings.
279
+ - `resources/thread_per_core_and_shared_nothing.md` — Thread-per-core architecture, core_affinity pinning, SO_REUSEPORT listener partitioning, and eliminating cross-core work-stealing cache thrashing.
280
+ - `resources/numa_architecture_and_hugepages.md` — NUMA-aware allocation (mbind), 2MB/1GB HugePages (madvise THP) eliminating TLB misses, and mlockall page pinning.
281
+ - `resources/instruction_cache_and_cold_path_outlining.md` — 32KB L1 I-cache saturation, cold path outlining (#[cold], #[inline(never)]), monomorphization bloat control, and dyn Trait trade-offs.
282
+ - `resources/framework_and_stack_selection_matrix.md` — Stack selection matrix comparing Manual Zero-Deps vs Axum vs Actix Web vs Salvo vs Poem vs Rocket vs Loco.