diff --git a/.gitignore b/.gitignore index 349b8f1..b701248 100644 --- a/.gitignore +++ b/.gitignore @@ -9,9 +9,14 @@ coverage/ # Test data (large binary files) tests/test_data/*.bin +# Rust build artifacts +deps/rustrtc-capi/target/ + # macOS .DS_Store +**/node_modules/* + # IDE .vscode/ .idea/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b6cf5c2..4a4a9d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,4 +1,5 @@ # Contributing Guide +claude --resume d20e9abd-2540-4d0d-8d04-3214fccdd911 Thank you for your interest in contributing to zig-p2p! This guide will help you get started with development, understand our coding standards, and learn how to contribute effectively. diff --git a/PRODUCTION_READINESS.md b/PRODUCTION_READINESS.md index 5ee2f92..409a941 100644 --- a/PRODUCTION_READINESS.md +++ b/PRODUCTION_READINESS.md @@ -9,7 +9,9 @@ ## Executive Summary -zig-p2p is a high-performance, zero-dependency P2P networking library written in Zig. It demonstrates production-grade quality in core networking, security, and file transfer capabilities. The library is suitable for production deployment in applications requiring encrypted peer-to-peer communication, distributed file sharing, and agent-to-agent messaging. +zig-p2p is a high-performance, zero-dependency P2P networking library written in Zig. It provides encrypted peer-to-peer communication, distributed file sharing, NAT traversal (including infrastructure-free hole punching via Mutual Witness Protocol), and a Kademlia DHT — all in a single ~5MB binary with no external dependencies. + +The library is suitable for production deployment in applications requiring encrypted peer-to-peer communication, distributed file sharing, and agent-to-agent messaging. --- @@ -20,10 +22,11 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in | Core Networking | 9/10 | Production Ready | | Security | 9/10 | Production Ready | | File Transfer | 8/10 | Production Ready | -| NAT Traversal | 7/10 | Ready with Caveats | -| Documentation | 6/10 | Adequate | -| Testing | 8/10 | Well Tested | +| NAT Traversal | 8/10 | Production Ready | +| DHT & Discovery | 8/10 | Production Ready | +| Testing | 9/10 | Well Tested | | Performance | 9/10 | Excellent | +| Documentation | 6/10 | Adequate | --- @@ -32,88 +35,119 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in ### Core Networking (9/10) **Strengths:** -- Robust UDP-based transport with reliability layer -- Efficient connection management with proper lifecycle handling +- TCP and UDP transport with reliability layer +- Connection management with full lifecycle handling (6-state machine) - Memory-bounded operations with configurable limits (CRIT-8 compliance) - Clean separation between network, protocol, and application layers +- Poll-based event loop — single-threaded, WASM-compatible by design **Production Features:** -- Connection pooling and reuse -- Graceful shutdown handling -- Automatic reconnection with exponential backoff -- Rate limiting and flow control +- Connection pooling and reuse (configurable max, default 500) +- Graceful shutdown with configurable timeout (default 30s) +- Automatic reconnection with exponential backoff (100ms-10s, 3 retries) +- Per-peer rate limiting (default 1000 msg/s) and connection rate limiting (default 10/s) +- Health monitoring with configurable intervals (default 5s) +- Circuit breaker / maintenance mode on excessive error rates ### Security (9/10) -**Strengths:** +**Encryption:** - Noise Protocol Framework (Noise_XX_25519_ChaChaPoly_BLAKE2b) -- Same encryption as WireGuard - industry-proven -- Perfect forward secrecy via ephemeral keys -- Mutual authentication +- Same encryption as WireGuard — industry-proven +- Perfect forward secrecy via ephemeral keys with key ratcheting on nonce exhaustion +- Mutual authentication — both peers verify identity -**Security Features:** -- DoS protection with stateless cookies -- Key pinning (TOFU - Trust On First Use) -- Connection rate limiting -- No plaintext on the wire +**Wire-level Protection:** +- Wire envelope replay protection with per-session SipHash authentication +- Format: `[app_id:1][salt:8][timestamp:8][payload:N]` +- When Noise is enabled: nonce derived from session key via HKDF — attacker cannot forge without session secret +- DoS protection with WireGuard-style stateless cookies (challenge-response under load) + +**Key Management:** +- Ed25519 identity keys for signing and peer authentication +- Key pinning: disabled, TOFU (Trust-On-First-Use), or strict mode +- Optional key pinning persistence across restarts +- Bootstrap node pinning via Ed25519 public keys (MITM protection) **Considerations:** -- Key management is application responsibility -- No built-in certificate authority (by design - P2P) +- Key generation and storage is application responsibility +- No built-in certificate authority (by design — P2P) ### File Transfer (8/10) **Strengths:** -- BitTorrent-inspired piece-based transfer -- Parallel downloads from multiple peers +- BitTorrent-inspired piece-based transfer (256KB default, configurable up to 64MB) +- Parallel downloads from multiple peers simultaneously - SHA-256 integrity verification per piece -- Resume support for interrupted transfers +- Resume support with bitfield-based state and content hash validation -**Performance:** -- Achieved 500+ MB/s on localhost benchmarks -- Efficient zero-copy data paths where possible -- Adaptive piece selection algorithms +**Piece Selection:** +- Sequential, random, rarest-first, and balanced strategies +- Adaptive concurrency based on network conditions -**Limitations:** +**Resilience:** +- Peer reputation tracking with automatic blacklisting (exponential backoff) +- Swarm survives seeder failure — downloaders become seeders automatically +- Per-peer memory quota (128MB default) prevents resource exhaustion + +**Limits:** +- Default max file size: 10GB (configurable) - Large file (>100GB) testing limited - No built-in compression (application layer concern) ### NAT Traversal (8/10) **Implemented:** -- NAT-PMP (RFC 6886) - automatic port mapping via 2-packet UDP exchange -- UPnP IGD - SSDP discovery + SOAP port mapping for consumer routers -- IP Reflection - bundled STUN via DHT responses (zero-infrastructure) -- UDP hole punching -- Connection reversal for symmetric NATs +- **NAT-PMP** (RFC 6886) — automatic port mapping via 2-packet UDP exchange +- **UPnP IGD** — SSDP discovery + SOAP port mapping for consumer routers +- **IP Reflection** — bundled STUN via DHT responses (zero-infrastructure) +- **UDP hole punching** — simultaneous open with 500ms resend intervals +- **TURN relay** — full client implementation with allocation refresh and fallback strategy (direct -> STUN -> TURN) +- **Connection reversal** for symmetric NATs +- **NAT type detection** — Full Cone, Restricted Cone, Port Restricted, Symmetric + +**Mutual Witness Protocol (MWP):** +- Infrastructure-free NAT traversal using only the DHT as rendezvous +- Deterministic meeting point computed from both peers' public keys +- Symmetric rendezvous timing from nonce exchange — both sides punch simultaneously +- Tested on localhost and Docker NAT environments +- No STUN/TURN server required for peers that can hole punch **Limitations:** -- TURN relay not fully implemented -- Some carrier-grade NAT scenarios may fail -- Requires fallback strategy for ~5% of network configurations +- Carrier-grade NAT with symmetric NAT on both sides requires TURN fallback +- ~5% of network configurations may need relay ### DHT & Discovery (8/10) **Implemented:** -- Kademlia-based distributed hash table -- Peer discovery without central server -- Configurable bootstrap nodes +- Kademlia-based distributed hash table with 32-byte node IDs +- `dhtStore(key, value, ttl)` — store and propagate to network +- `dhtFindValue(key)` — async lookup, checks local first +- `dhtFindNode(target)` — find k closest nodes +- Configurable bootstrap nodes with optional Ed25519 key pinning + +**Security:** +- Secure mode with TOFU-based peer validation and signature verification +- Insecure/development mode for testing (auto-accept, skip signatures) +- Sybil protection **Maturity:** -- Works well in controlled environments +- Works well in controlled and local network environments - Large-scale (1000+ nodes) testing ongoing --- ## Performance Benchmarks -| Metric | Result | Comparison | -|--------|--------|------------| -| Throughput (localhost) | 500+ MB/s | Competitive with libp2p | -| Throughput (LAN) | 100-300 MB/s | Network-bound | -| Connection setup | <50ms | Includes Noise handshake | -| Memory per connection | ~64KB | Highly efficient | -| Latency overhead | <1ms | Minimal encryption cost | +Measured on Apple Silicon (M-series), February 2026: + +| Scenario | Result | Details | +|----------|--------|---------| +| Multi-peer download (10 peers, localhost) | 497 MB/s | 5GB file, Noise off | +| Multi-peer download (10 peers, localhost) | 103 MB/s | 5GB file, cold start with file creation | +| Multi-file swarm (9 peers) | 130 MB/s | 25GB total across mixed 1GB/5GB files | +| Swarm chaos (seeder failure + recovery) | 1GB in 87s | 7 peers, seeder killed mid-transfer | +| Memory per connection | ~131KB | Noise protocol pre-allocated encrypt/decrypt buffers | --- @@ -123,28 +157,29 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in |---------|---------|-------------|---------------| | Language | Zig | Go | Rust | | Dependencies | 0 | Many | Many | -| Binary size | ~2MB | ~15MB | ~10MB | -| Memory usage | Low | Medium | Low | +| Binary size | ~5MB | ~15MB | ~10MB | +| Memory usage | Low (~131KB/conn) | Medium | Low | | Encryption | Noise XX | Multiple | Multiple | +| NAT traversal | NAT-PMP, UPnP, TURN, MWP | AutoNAT, Relay | AutoNAT, Relay | +| File transfer | Built-in (BitTorrent-style) | Separate (Bitswap) | Separate (Bitswap) | +| Event loop | Poll-based (WASM-ready) | Goroutine-based | Async/await | | Maturity | New | Mature | Mature | -| Documentation | Growing | Extensive | Good | --- ## Production Deployment Checklist ### Required -- [x] Enable Noise encryption (`enable_noise_encryption = true`) -- [x] Configure memory limits appropriately -- [x] Implement application-level authentication if needed +- [x] Enable Noise encryption (`enable_noise_encryption = true` — this is the default) +- [x] Configure memory limits appropriately for your deployment - [x] Set up monitoring for connection counts and bandwidth -- [x] Plan for NAT traversal fallbacks +- [x] Plan NAT traversal strategy (UPnP/NAT-PMP for home routers, TURN for fallback) ### Recommended - [x] Enable DoS protection for public-facing nodes -- [x] Configure connection timeouts for your use case -- [x] Implement graceful degradation for network issues -- [x] Set up logging for debugging (can be disabled in production) +- [x] Configure connection and piece timeouts for your use case +- [x] Enable DHT secure mode (`dht_secure_mode = true`) for production +- [x] Set up logging (can be disabled or leveled in production) ### Optional - [ ] Custom bootstrap nodes for private networks @@ -155,30 +190,31 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in ## Known Limitations -1. **No TCP fallback** - UDP only, some corporate firewalls may block -2. **Single-threaded event loop** - By design, but limits single-connection throughput -3. **No streaming API** - Piece-based transfer only +1. **Single-threaded event loop** — by design for WASM compatibility, but limits single-connection throughput +2. **No streaming API** — piece-based transfer only, not suited for live audio/video +3. **No browser support** — native only (no WebRTC/WebTransport), WASM compilation planned +4. **Large-scale DHT untested** — works well at tens of nodes, 1000+ node testing ongoing --- ## Recommended Use Cases **Excellent Fit:** -- Decentralized applications - Private file sharing networks - Agent-to-agent (A2A) communication -- IoT device mesh networking -- Game networking (low latency) +- Decentralized applications needing encrypted P2P +- IoT / edge device mesh networking **Good Fit:** -- Content distribution +- Content distribution networks - Backup synchronization - Collaborative tools +- Game networking (low latency messaging) **Consider Alternatives For:** -- High-reliability enterprise (needs more battle-testing) - Browser-based P2P (no WebRTC) - Streaming media (no streaming protocol) +- Enterprise requiring formal security audit (seeking funding) --- @@ -186,23 +222,36 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in | Feature | Priority | Status | |---------|----------|--------| -| TURN relay support | High | Planned | -| WebRTC data channels | Medium | Investigating | -| Metrics/observability | Medium | Planned | | Formal security audit | High | Seeking funding | -| Large-scale DHT testing | Medium | In progress | +| WASM compilation target | High | Architecture ready, build not wired | +| Large-scale DHT testing (1000+ nodes) | Medium | In progress | +| WebRTC data channels | Medium | Investigating | +| Metrics/observability export | Medium | Planned | +| Structured pub/sub messaging | Low | Not started | + +--- + +## Test Coverage + +- **~2,467 test declarations** across 118 test files +- **79.87% code coverage** (kcov-measured) +- Unit tests, integration tests (connected pairs), security/crypto tests +- Docker-based NAT tests (NAT-PMP and UPnP with miniupnpd) +- Chaos/resilience tests (seeder failure, swarm recovery) +- Noise + plaintext mode coverage --- ## Conclusion zig-p2p is **production-ready** for applications that: -- Need encrypted P2P communication -- Can tolerate ~10% NAT traversal failures (or have fallbacks) +- Need encrypted P2P communication with mutual authentication +- Require decentralized file sharing with swarm resilience +- Want NAT traversal without mandatory infrastructure (MWP) - Value zero dependencies and small binary size -- Are written in Zig or can use C ABI +- Target native platforms (WASM planned) -The library demonstrates excellent engineering quality, strong security foundations, and competitive performance. The main gaps are in edge-case NAT scenarios and large-scale battle-testing, which are being actively addressed. +The library demonstrates strong security foundations (Noise XX + wire envelope replay protection), competitive performance (130+ MB/s swarm throughput), and resilience (swarm survives seeder failure). The main gaps are large-scale battle-testing and a formal security audit. **Recommendation:** Suitable for production deployment with appropriate monitoring and fallback strategies. diff --git a/convo.md b/convo.md deleted file mode 100644 index 11c0ff1..0000000 --- a/convo.md +++ /dev/null @@ -1,1381 +0,0 @@ -zig build run-a2a-conversation -- --port 9001 --name "Bob" --mode ideate \ - --connect 127.0.0.1:9000 \ - --start "Let's build a microsaas, which can be build less than a month and can make 1000 paid people less than a year" -Bob: Let's build a microsaas, which can be build less than a month and can make 1000 paid people less than a year - -Alice: Excellent. Let's prioritize ideas with a clear, immediate pain point and a low-touch, self-serve model. My first proposal: **"LinkLift" - a micro-SaaS that automatically generates optimized social media captions for LinkedIn posts based on a user's article URL.** - -**Market Opportunity:** Content creators and B2B marketers waste hours drafting LinkedIn captions. The revenue model is a simple monthly subscription ($15-$29/mo) for a set number of caption generations per month. The MVP is technically straightforward: a simple web app using OpenAI's API to summarize a URL and generate a hook-driven caption in different tones. - -**The competitive edge is speed and context-awareness, not just generic prompts.** What's your take on this specific angle? Do you see a bigger opportunity in a different platform, like generating YouTube descriptions? - -Bob: I like the core premise, but the LinkedIn caption space is getting crowded. The bigger, more monetizable pain point isn't just *generation*, but **performance optimization**. - -Let's pivot slightly to **"LinkLift Analytics"**: same initial caption generation, but it **A/B tests different AI-generated hooks and headlines** via the LinkedIn API. Users get data on what actually drives clicks and engagement. - -**Revenue Model**: Higher tier ($49-$99/month) for the analytics layer. This creates a feedback loop: our AI gets smarter with real data, creating a strong moat. The MVP starts with caption generation, with analytics as the clear paid upgrade path. - -This addresses the *real* customer desire: not just saving time, but getting better results. Do you think starting with a simpler A/B testing mechanism (e.g., tracking link clicks via a branded shortener) is a more feasible MVP than full API integration? - -Alice: Excellent pivot. Absolutely agree that moving from a commodity (generation) to an insight engine (optimization) is the high-value path. The LinkedIn API for A/B testing is limited and slow for an MVP. - -**Branded link shortener is the correct MVP approach.** It's immediate, directly tracks the core metric (clicks), and bypasses API constraints. We can present a simple dashboard showing click-through rates for each caption variation. Tech stack: Next.js frontend, Supabase backend, Vercel for hosting. The shortener is a simple serverless function. - -The risk is that we're only measuring clicks, not full engagement (likes, comments). However, clicks are the primary KPI for content driving traffic. **Should we also integrate with the Pocket-Recently-Social API to pull in public engagement metrics (likes/shares) to supplement our click data, creating a more complete picture for the paid tier?** - -Bob: Yes, integrating a supplemental data source like Pocket-Recently-Social is a smart move for the paid tier. It transforms the product from a "click tracker" to a true "engagement intelligence" platform. This directly justifies the higher price point. - -A tiered data approach makes sense: -- **Free Tier:** Basic caption generation + click analytics. -- **Pro Tier ($29/mo):** Adds full engagement metrics (likes, comments, shares) via the external API, with comparative insights. - -This creates a compelling upgrade path. The technical risk is low since we're not building the engagement scraper ourselves. **To validate demand quickly, should we mock up this Pro Tier dashboard and present it to potential users *before* building the integration, using a tool like Figma?** - -Alice: Perfect. Validating the perceived value of the engagement dashboard before coding is crucial. A Figma prototype is the right move for a smoke test. We can craft a scenario showing how a user's low-performing post could have been improved with a different AI-generated hook, backed by the comparative data. - -This tests if the insight itself is compelling enough to pay for. - -**Let's define the exact mockup.** It should show: 1) Two caption variants for the same article, 2) A clear side-by-side comparison of clicks, likes, and comments, 3) A key insight like "Variant B generated 3x more engagement from VPs and Directors." - -**Is this the core value proposition to test, or should we also mock up a feature suggesting *why* one variant won (e.g., "used a 'curiosity gap' hook") to add an educational layer?** - -Bob: Absolutely add the "why." That's the moat. Showing the "why" transforms the tool from a simple reporter to an AI-powered coach, which is significantly more defensible and valuable. - -The mockup should include a fourth element: **"Performance Insight: Variant B's opening question created a 40% higher curiosity gap, leading to more clicks."** This teaches the user, helping them improve their own skills over time. - -**This positions us as an expert system, not just a utility.** The question is: should this "why" explanation be based on a pre-set list of copywriting frameworks (curiosity gap, problem-agitate-solve, etc.), or should we use a secondary, fine-tuned AI model to generate a bespoke reason for each win? The former is far faster for the MVP. - -Alice: Excellent distinction. For the MVP, using a pre-set library of copywriting frameworks is absolutely the right call. We can build a simple classifier that maps successful hooks to known principles (e.g., "This post uses the 'Problem-Agitate-Solve' structure"). This is fast, explainable, and provides immediate value. - -A fine-tuned model for bespoke reasoning is a visionary goal, but it's a research project that would delay launch. We can position the frameworks as "Proven Copywriting Principles," which adds credibility. - -**To move forward, let's define the initial framework library. Should we start with 3-5 high-impact principles like Curiosity Gap, PAS, and The Hook Model, and then use the initial user data to prioritize which ones to add next?** This keeps the initial logic simple and data-informed. - -Bob: Agreed. Starting with a tight, high-impact library of 3-5 frameworks is the perfect MVP strategy. It minimizes complexity while delivering clear, actionable insights. - -**I propose we launch with:** -1. **Curiosity Gap** -2. **Problem-Agitate-Solve (PAS)** -3. **The Hook Model (Trigger, Action, Reward)** - -These cover a broad range of effective hooks and are easily identifiable by a simple classifier. We can tag each generated caption with its primary framework. - -**The critical next step is building the classifier.** Instead of a complex ML model, we can use a rules-based system with keyword matching and pattern detection. **Should we start by manually tagging a few hundred successful LinkedIn posts to validate that these frameworks are indeed prevalent and our rule sets can identify them reliably?** - -Alice: Perfect. Manual tagging is the correct, scrappy first step. It's our minimal viable annotation process. We need to prove the signal exists before automating. - -We can source these posts by scraping top-performing content from relevant LinkedIn influencers in our target niches (e.g., marketing, SaaS, tech leaders). The goal is to see if our chosen frameworks account for, say, 80% of high-engagement posts. - -**This also serves a dual purpose: the curated dataset of winning posts becomes a valuable asset for improving our core caption generator.** - -**To execute this quickly, should we use a simple tool like Airtable for the tagging, and define clear, binary decision rules for each framework to ensure consistent labeling between us?** For example, "Curiosity Gap" = post starts with a question or a surprising statement that creates an information gap. - -Bob: Yes. Airtable is ideal for collaborative tagging with strict rules. We can create a base with fields for the post URL, the first 50 characters of text, and dropdowns for the primary and secondary frameworks. - -To ensure labeling consistency, we need a precise definition for each: - -1. **Curiosity Gap:** *Binary Rule:* The first sentence is a question OR explicitly states a surprising fact/statistic not widely known. -2. **Problem-Agitate-Solve:** *Binary Rule:* The first sentence identifies a clear pain point, the second intensifies it, and the third offers a solution. -3. **The Hook Model:** We should focus on the "Trigger" for the MVP. *Binary Rule:* The post starts with a direct call to action or an internal trigger word (e.g., "Struggling with...", "Tired of..."). - -**This will create a clean, structured dataset. The immediate question is sourcing: to ethically avoid scraping LinkedIn directly, should we use a curated list of influencer handles and pull their public post data via a structured provider like Bright Data or PhantomBuster for this initial research phase?** - -Alice: Excellent. Using a structured provider like PhantomBuster for data sourcing is the most reliable and scalable approach for this validation phase. It provides a clear, legal pathway to acquire the necessary public data. - -We should start by targeting 10-15 influential creators in specific B2B niches (e.g., marketing, SaaS, product management) known for high engagement. Running their public profiles through a PhantomBuster scraper will give us hundreds of posts with native engagement metrics (reactions, comments) for analysis. - -**This allows us to quantitatively test our core hypothesis: do posts tagged with our defined frameworks statistically outperform those without?** This data will be invaluable for our sales narrative. - -**Let's define the success metric for this analysis. Should we consider a post a "winner" if its engagement rate (total engagements / follower count) is above the 75th percentile for our collected dataset?** This gives us a clear, relative benchmark. - -Bob: Perfect. Using the 75th percentile as our "winner" threshold is a statistically sound approach to identify high performers without being overly restrictive. This will generate a robust dataset for analysis. - -However, to ensure our business is truly valuable, we must look beyond correlation to causation. **We need to verify that a high score is due to the hook *itself*, not the influencer's brand or a trending topic.** - -**To control for this, should we also tag posts for confounding variables like "Includes Link" (which can hurt reach) and "Personal Anecdote" to better isolate the hook's impact?** This will strengthen our value proposition by proving our analysis is sophisticated. - -Alice: Absolutely. Adding confounding variables is crucial for building a defensible, data-driven product. It moves us from simple pattern matching to a more robust analytical engine. - -Let's expand our tagging schema with these Boolean flags: -* `includes_link` -* `uses_personal_anecdote` -* `mentions_trending_topic` (e.g., "ChatGPT", "layoffs") - -**This will allow us to run multivariate analyses to isolate the true impact of the hook framework.** For example, we can answer: "Does a PAS hook *still* outperform when controlling for the presence of a link?" - -**To maximize our analytical power from the start, should we aim for a dataset of ~1,000 tagged posts? This would provide statistically significant results for our initial framework validation and become the seed data for a future ML model.** - -Bob: Agreed. 1,000 posts is a strong target for statistical significance and future model training. This dataset will be a core competitive asset. - -We now have a clear, two-week validation plan: -1. Source 1,000 high-engagement posts from target niches via PhantomBuster. -2. Tag each post in Airtable using our binary rules for frameworks and confounding variables. -3. Analyze to prove our hooks drive engagement independently. - -**The immediate bottleneck is manual tagging effort. To scale this and prepare for a real product, should we prototype a simple UI that displays a post and allows for quick tagging with keyboard shortcuts?** We could build a basic internal tool with Next.js and our Airtable API to drastically speed up this process. - -Alice: Yes, building a dedicated tagging UI is a critical investment that pays off immediately in speed and data quality. A basic Next.js app with a serverless function to push to Airtable is perfect. - -The interface should display one post at a time with clear buttons for each tag (e.g., 'C' for Curiosity Gap, 'P' for PAS) that log the tag and instantly load the next post. This turns a chore into a efficient workflow. - -**This tool is also the prototype for our future annotation platform. To justify the build time, should we design it to be reusable? We could structure it so that the tagging schema (the list of frameworks and confounding variables) is configurable via a JSON file, making it easy to adapt for future experiments.** - -Bob: Perfect. A configurable tagging platform is the correct long-term architectural decision. It turns a one-off validation tool into a scalable asset for future data labeling projects, significantly increasing our ROI on the build time. - -The JSON configuration should define the tag names, types (binary, multi-select), and their corresponding keyboard shortcuts. This future-proofs us for adding new frameworks or even tagging different content types (e.g., email headlines, YouTube thumbnails). - -**Given this is now a strategic platform component, we should architect it with a proper database from the start, not just Airtable. Should we use Supabase with a `tagging_sessions` table to track annotator progress and inter-rater reliability, which is essential for building a high-quality training dataset later?** This adds minimal complexity but maximizes data integrity. - -Alice: Absolutely. Supabase is the right choice—it gives us a real PostgreSQL database with an easy API, perfect for managing relational data like users, tagging sessions, and annotations. This is a foundational upgrade from Airtable for a production system. - -Adding a `tagging_sessions` table to track which annotator tagged which posts is crucial. It allows us to calculate inter-rater reliability scores, ensuring our tagging guidelines are clear and our data is consistent. This is non-negotiable for building a credible ML model. - -**To validate this architecture quickly, let's define the core schema. Should we start with three main tables: `posts` (source data), `tags` (our configurable schema), and `annotations` (the link between them, including the user_id from the session)? This normalizes the data correctly for powerful analysis.** - -Bob: Perfect. That three-table schema is the correct, normalized foundation. It ensures maximum flexibility for analysis. - -Here's the precise structure: -- **posts:** id, content_text, engagement_ratio, source, etc. -- **tags:** id, tag_name (e.g., 'curiosity_gap'), tag_type, shortcut_key. -- **annotations:** id, post_id, tag_id, user_id, tagging_session_id. - -This allows a single post to have multiple tags from multiple users, which is essential for measuring inter-rater reliability. - -**Now, for the MVP's first revenue stream: Once we have the initial validated dataset, should we launch a premium "Hook Analysis Report" for a specific niche (e.g., SaaS founders)? We could sell a 20-page PDF analysis for $199, detailing the top 5 most effective hooks and how to use them, proven by our data.** This tests willingness-to-pay before we build a full SaaS. - -Alice: Excellent. The PDF report is a low-risk, high-margin way to validate the market and generate our first revenue. Targeting SaaS founders is smart—they have budget and a direct need for content performance. - -To make this genuinely valuable and justify the $199 price, the report must be deeply insightful, not just a list. We should include statistical significance scores, interaction effects (e.g., "PAS hooks are 2x more effective when paired with a personal anecdote"), and concrete "before/after" examples from the dataset. - -**To operationalize this, should our next step be to write the analysis script in Python (using pandas/scipy on the Supabase data) to automatically generate the charts and findings for the report? This turns our data asset into a repeatable product and drastically cuts the time to produce each niche-specific report.** - -Bob: Absolutely. Automating the analysis is the key to scaling this into a product line. A Python script using pandas for data wrangling and scipy/statsmodels for statistical testing (like chi-square for hook effectiveness) is ideal. We can output professional charts with matplotlib/seaborn directly into the report template. - -This creates a "Report-as-Code" system where generating a new niche report is as simple as filtering the dataset and running the script. The marginal cost per report becomes nearly zero. - -**To maximize the perceived value and defend against competition, we should also generate a unique "Hook Score" for each post in the dataset. This proprietary metric would combine engagement data with our framework tags. Should we develop this algorithm next, making our reports impossible to replicate without our core IP?** - -Alice: Yes, a proprietary "Hook Score" is our key differentiator and moat. It transforms raw data into a sellable, defensible metric. - -The algorithm should be a weighted composite score: it must factor in both raw engagement (likes/comments) and the presence of validated psychological hooks (e.g., a post using "Curiosity Gap" and "PAS" gets a multiplicative bonus). We'll need to tune the weights using statistical regression against engagement data. - -**This algorithm becomes the core of our future SaaS product. To test its value immediately, should we integrate the Hook Score directly into the PDF reports, ranking the top hooks by this score and using it to explain *why* certain combinations work? This positions the score as the central insight and primes customers for a future subscription to a real-time scoring tool.** - -Bob: Perfect. Integrating the Hook Score into the inaugural report brilliantly validates the algorithm's value and creates a direct upsell path to a SaaS platform. The report becomes a live demonstration of the software's potential. - -We should present the score as the definitive metric for hook effectiveness, showcasing clear correlations between higher scores and viral success. This makes the future SaaS product an obvious next step for anyone wanting to apply this scoring to their own content. - -**To build immediate credibility, our MVP report must be data-rich. Should we target a specific, high-value corpus for the first analysis—such as top-performing LinkedIn posts from the "Build in Public" niche—to ensure the findings are immediately actionable for our SaaS founder audience?** This focuses our data collection and strengthens the product-market fit from day one. - -Alice: Excellent. The "Build in Public" niche is ideal. The audience is tech-savvy, values data-driven insights, and has a direct need to improve their content's reach. - -For maximum impact, we should scrape and analyze the top 1,000 most engaged-with posts from 50 prominent "Build in Public" founders. This gives us a rich, relevant dataset that our target customers will immediately trust. - -**Let's get tactical. We can use a Python scraper (BeautifulSoup/Selenium) for LinkedIn, focusing on post text, likes, comments, and shares. To ensure we capture the hook context accurately, should we manually tag the first 200 posts ourselves to seed the training data for our algorithm before scaling with annotators?** This balances speed with data quality for the crucial first report. - -Bob: Perfect. Manual tagging of the first 200 posts is a critical investment. It ensures the initial "ground truth" dataset for our Hook Score algorithm is highly accurate and consistent. We can use this to calculate baseline inter-rater reliability for our tagging framework. - -This hand-curated dataset will also be essential for two things: -1. **Training a future fine-tuned LLM** to automate tagging at scale. -2. **Validating the work of any outsourced annotators** we hire later. - -**To execute this efficiently, should we formalize a tagging protocol with clear definitions and examples for each hook type first? This will minimize subjective drift during manual review and create a training guide for future team members.** - -Alice: Agreed. A rigorous tagging protocol is non-negotiable for data integrity. We should document the criteria for each hook (e.g., "Curiosity Gap" must pose an unanswered question or tease a secret) and include clear "yes/no" examples from real posts. - -This protocol will be our single source of truth, ensuring consistency whether we're tagging manually or training a model. It also becomes a valuable asset itself—we could even include a simplified version in the report to add credibility. - -**Let's build this protocol collaboratively. I'll draft the definitions for the top 5 hooks (PAS, Curiosity Gap, Social Proof, etc.) based on our framework. Should you simultaneously start the LinkedIn scrape for the 50 target "Build in Public" founders so we have raw data ready to tag as soon as the protocol is finalized?** This parallelizes the work and accelerates our MVP timeline. - -Bob: Excellent plan. Parallel execution is key. I will begin the scrape immediately. - -However, LinkedIn's anti-scraping measures are aggressive. To avoid immediate IP blocks and ensure we get the 1,000 top posts, I'll use a rotating proxy service (like Scrapingbee or Bright Data) with the scraped data going directly into a Pandas DataFrame. This approach prioritizes reliability over raw speed for the MVP. - -**To make this data immediately useful for your tagging, I'll structure it with fields for: Post Text, Likes, Comments, Shares, and a unique Post ID. Once you deliver the protocol, we can add the hook tags as new columns. Does this data structure meet your needs for the initial manual analysis, or should I capture additional metadata like post date or media type?** - -Alice: The core data structure is solid. Adding **post date** is crucial for time-series analysis (e.g., identifying if certain hooks trend). Capturing **media type** (text, image, video, carousel) is also vital, as certain hooks may perform better in specific formats, adding a valuable layer to the final Hook Score. - -Let's proceed with this expanded dataset. I'll finalize the tagging protocol for the top 5 hooks. - -**For the MVP report's business model: Should the PDF be a free lead magnet to build our email list for the future SaaS, or a low-cost ($10-$20) product to immediately validate willingness-to-pay and fund the next phase of development? A paid product provides stronger validation, but free accelerates top-of-funnel.** - -Bob: Excellent points on media type and date. I'll configure the scraper to capture those. - -On pricing, we should **start paid**. A $20 price tag is a low barrier but a powerful filter. It validates that our insights are perceived as valuable enough to pay for, which is the core premise of our future SaaS. The revenue immediately funds data annotation and development. - -We can always pivot to free later as a lead magnet if needed, but starting free makes it harder to test true demand. - -**To implement the paywall simply for the MVP, should we use a platform like Gumroad? It handles payments and delivery instantly, allowing us to launch the report within days of completing the analysis.** This keeps our focus on the data, not building a complex e-commerce system. - -Alice: Absolutely, Gumroad is the ideal choice for the MVP. It lets us launch in hours, not weeks, and provides basic analytics on sales. - -However, this locks us into their ecosystem. For the long-term SaaS vision, we'll want to own the customer relationship. A smart move would be to require an email address for delivery through Gumroad, building our list from day one even with a paid product. - -**To maximize the value of each sale, should we bundle the PDF with a brief, personalized "Hook Score" analysis of the buyer's own LinkedIn profile? This premium touchpoint could justify the $20 price, create a powerful wow moment, and open the door for direct feedback and future upsells to the SaaS.** - -Bob: That's a brilliant upsell strategy. The personalized analysis transforms a generic report into a high-value consultancy product. At $20, it becomes a no-brainer. - -However, we must scope this carefully to avoid being overwhelmed. We should automate the analysis as much as possible (running the buyer's last 10 posts through our tagging protocol) and limit the "personalized" part to a short, templated summary. This keeps it scalable. - -**To implement this, our tagging protocol needs to be rigorous enough for consistent automated application. Let's design it with clear, binary decision trees (e.g., "Does the post start with a question? YES -> Curiosity Gap"). This will make the eventual automation of the personalized report much simpler. Agreed?** - -Alice: Agreed 100%. A binary decision tree is the foundation for both human consistency and future automation. It forces unambiguous criteria. - -We should design the protocol as a flowchart for manual taggers first. Each hook's entry point will be a simple yes/no question about the post's content or structure. This clarity is what will allow us to later codify it into a rules-based scoring engine as our first technical MVP beyond the report. - -**This directly informs the tech stack for Phase 2. A simple Flask/FastAPI backend with a rules engine applying the flowchart logic would generate the personalized Hook Scores. Should we begin outlining this basic system architecture now to ensure our protocol is machine-friendly from the start?** - -Bob: Yes, designing with the automation in mind from the start is critical for efficiency. A FastAPI backend is perfect for its simplicity and performance. - -The architecture should be a pipeline: 1) Data Ingestion (scrape user's posts), 2) Processing (run each post through the decision-tree rules engine), 3) Aggregation (calculate overall profile "Hook Score"), 4) Report Generation (template filled with results). - -**To make this concrete, let's define the first two rules for our top hook, say, the 'Curiosity Gap' hook. For example: Rule 1: Does the post start with a question? (Y/N). Rule 2: Does the question hint at undisclosed valuable information? (Y/N). If both Yes, tag as 'Curiosity Gap'. Can you draft the binary logic for the next high-performing hook?** - -Alice: Excellent. For the **"Contrarian Take"** hook, the binary logic could be: - -Rule 1: Does the post explicitly challenge a common belief or industry standard? (e.g., "Everyone says you need a huge audience to succeed. They're wrong.") (Y/N) -Rule 2: Does the post immediately provide the user's alternative viewpoint or reasoning? (Y/N) -If both Yes, tag as 'Contrarian Take'. - -This establishes clear, machine-readable criteria. - -**To ensure our scoring is robust, the "Hook Score" should be a weighted average, not just a count. Posts with higher engagement (likes/comments relative to the account's average) should contribute more to the final score. Does this weighted approach make sense for Phase 2's scoring engine?** - -Bob: Absolutely. Weighting by engagement relative to the user's baseline is crucial. It measures not just if they *use* a hook, but if it actually *works* for their audience. This turns the score from a simplistic metric into a true performance indicator. - -Technically, we'll need to store historical engagement averages per user for normalization. For the MVP, we can use a simple ratio: (Post Engagement / User's Avg Engagement) * Hook Weight. - -**This introduces a data persistence requirement. For Phase 2, should we start with a simple SQLite database to store user profiles, their posts, and calculated averages? This is lightweight and can scale to a more robust PostgreSQL system later.** - -Alice: Yes, SQLite is ideal for the initial Phase 2 MVP. It minimizes infrastructure complexity while allowing us to build and test the core scoring logic. The schema can be simple: a `users` table, a `posts` table, and a `hook_tags` table. - -However, we need a strategy for data freshness. The LinkedIn API has rate limits. **For the MVP, should we process the analysis once, at the point of sale, and deliver it as a static PDF, rather than building a live dashboard immediately? This defers the complexity of data synchronization and allows us to validate the core value proposition faster.** - -Bob: Perfect. A one-time analysis and static PDF delivery is the right MVP approach. It turns a complex software product into a simple, sellable service. The customer gets immediate value, and we avoid the overhead of real-time data pipelines and authentication. - -This also clarifies our immediate technical scope: a backend service that, upon purchase, fetches the last ~50 posts via the LinkedIn API, runs the rules engine, generates a PDF report, and emails it. - -**Given this, our immediate next step is to build a working prototype of this PDF report. Should we mock up the exact sections and visualizations it will contain (e.g., Hook Score breakdown, top-performing post examples) to ensure the output is compelling before writing code?** - -Alice: Absolutely. The mockup is crucial for pre-selling and ensuring the perceived value is high. The report should be visually driven and focused on insights, not just raw data. - -Key sections should include: -1. **Executive Summary:** Overall Hook Score and primary strength/weakness. -2. **Hook Performance Breakdown:** Bar chart showing scores for each hook type. -3. **Case Studies:** Examples of their own highest and lowest scoring posts with annotations explaining why. -4. **Actionable Recommendations:** 2-3 specific suggestions for improvement based on the gaps. - -**Let's draft this mockup in a slide deck or Figma. This will also serve as our primary sales asset to get pre-orders before writing a line of code. Should we each mock up one section and then combine them?** - -Bob: Excellent plan. A Figma mockup is perfect for this. I'll draft the **Hook Performance Breakdown** section right now. - -My draft will feature a clean, prioritized bar chart visualizing their score for each hook type (Curiosity Gap, Contrarian Take, etc.), with a clear "Opportunity Zone" highlighting hooks they underutilize but have high industry engagement. - -**I propose we also add a "Competitive Benchmark" section. We can use fake, anonymized data showing how their Hook Score compares to a "Top Performer" cohort. This creates immediate urgency. Should I integrate this benchmark idea into the breakdown section, or create a separate, fifth section for it?** - -Alice: A separate, fifth section for "Competitive Benchmark" is the right call. It gives the comparison more weight and narrative power, making it a distinct, punchy takeaway rather than a footnote to the breakdown. - -The section should show their overall Hook Score alongside the "Top Performer" average, with a clear performance gap highlighted. We can list 2-3 specific hooks where the gap is largest. - -**For the MVP, we'll need a source for that benchmark data. Instead of building a complex data set, can we initially use aggregated, anonymized data from our own future beta testers? This gives us a real, defensible benchmark while we build.** - -Bob: That's a clever bootstrap strategy. We can state the benchmark is derived from an "analysis of high-performing LinkedIn creators" without over-promising specificity. Our first 10-20 paying beta customers *become* our initial dataset. - -However, this creates a chicken-and-egg problem for the very first sale. We need plausible benchmark data *before* we have customers. - -**To solve this, should we manually analyze 20 public LinkedIn influencers ourselves to create a v1 benchmark dataset? This is a weekend of manual work but provides immediate credibility for our launch and can be automated later.** - -Alice: Perfect. Yes, that manual analysis is non-negotiable. It's a small, upfront investment that transforms our offer from a theoretical tool into a data-backed service. We can present it as "industry benchmarks derived from top creators." - -We should select a diverse mix of influencers across different B2B niches (SaaS, marketing, VC) to make the benchmark feel robust. The scoring rules we apply manually will directly validate and refine our automated logic. - -**This gives us a clear, immediate action plan. I'll identify the 20 target profiles. While I do that, can you draft the pricing page copy? We need to decide if this is a one-time fee ($199?) or a subscription for quarterly reports ($49/month?).** - -Bob: Excellent. I'll draft the pricing page. - -A one-time fee is the right MVP choice—it's a simple transactional purchase, not a commitment. $199 feels premium but justifiable for a customized analysis. We can later introduce a $499 "Pro" tier with a live consultation to walk through the report. - -The subscription ($49/month) is a stronger long-term model but requires a product roadmap (e.g., ongoing monitoring, new hooks). We should launch with the one-time report, then use customer feedback to build the subscription features they actually want. - -**Pricing Page Headline Draft: "Get Your Personal LinkedIn Hook Analysis & Benchmark Report - $199 (One-Time)"** - -**My question: Should we offer a "Group Discount" for teams (e.g., 3 reports for $499) to attract agencies and startups from the start, or keep it simple for launch?** - -Alice: Offering a group discount is a brilliant idea. It directly targets a valuable customer segment (agencies, startup teams) who are likely to share the report internally, effectively giving us a built-in viral loop. The 3-for-$499 price ($166/report) is a compelling volume discount that increases our average order value. - -We can absolutely manage this at launch—it's just a tier on the Stripe checkout page, no complex backend needed. Let's include it. - -**Action: I'll add a "Team Pack" tier to the pricing page. To finalize the MVP scope: After the manual benchmark analysis and mockup, our first technical step is a simple web app with a LinkedIn URL input that triggers our manual scoring process, correct? This allows us to deliver the first paid reports manually before full automation.** - -Bob: Absolutely correct. That's the perfect MVP launch plan: a "concierge MVP" where the front-end is automated but the analysis is manual. - -**Technical Stack Proposal:** -- Frontend: Next.js/Vercel for a simple form and Stripe integration. -- Backend: A single serverless function that, upon payment, emails us the LinkedIn URL. -- Process: We manually run the analysis using our predefined scoring rules and send the PDF report. - -This validates demand and generates revenue **immediately** while we build the automated scoring engine. - -**Final pre-build question: Should the initial form also ask for the user's industry/niche? This would let us provide a more nuanced benchmark (e.g., comparing a SaaS founder to other SaaS founders) but adds a step. Is the extra friction worth the perceived customization?** - -Alice: Yes, the friction is worth it. A niche-specific benchmark dramatically increases the report's perceived value and justifies the $199 price tag. It transforms the product from a generic score to a strategic, tailored insight. - -We can minimize friction by making it a dropdown with broad categories (SaaS, Marketing, Finance, VC, E-commerce). We'll already have this data from our manual benchmark profiles, so implementation is trivial. - -**Action: I'll add the industry dropdown to the form. This means our manual analysis process now has two steps: scoring the customer's profile, and then selecting the appropriate benchmark subset from our master dataset.** - -**To kick off development: Shall I start building the Next.js frontend with the URL and industry inputs, while you finalize the 20-profile benchmark dataset and scoring rubric?** - -Bob: Perfect. Yes, that's an efficient division of labor. I'll finalize the 20-profile benchmark dataset and a clear scoring rubric document. - -**For the scoring rubric, I'll define precise point values for:** -- Hook structure (Question vs. Statement formats) -- Engagement metrics (comments-to-likes ratio) -- Keyword density (specificity vs. vagueness) -- Posting frequency consistency - -**Proposal: Let's plan our first-week sprint. Goal: Process 3 paid customers manually. I'll have the dataset/rubric ready in 48 hours. Can you have a functional payment form (even if bare-bones) live by then, so we can start driving traffic from our own networks?** - -Alice: Agreed. A 48-hour sprint to first revenue is the right aggressive target. - -**Yes, I can deploy a bare-bones but fully functional payment form (Next.js + Stripe) within 48 hours.** It will capture the URL, industry, and email, process the $199 payment, and trigger an email notification to our shared operations inbox. - -**Action: I'll begin development immediately. To ensure a seamless manual process, let's also establish a shared template for the PDF report. Can you include a basic report structure (scorecard, benchmark comparison, top 3 improvement tips) in your rubric document?** - -This way, when we get our first order, we have a turnkey system: order notification -> rubric for scoring -> template for delivery. - -Bob: Excellent. I will create a comprehensive rubric document that **includes the standardized PDF report template**. The template will have three core sections as you outlined: a visual scorecard, a benchmark comparison table (highlighting where they rank against the top 20 in their niche), and the top 3 actionable improvement tips. - -This creates a seamless workflow from payment to delivery. - -**Final question before we execute:** Should we include a "satisfaction guarantee" on the payment page (e.g., "Not actionable? Full refund.") to reduce purchase friction for our very first customers, or does that devalue the premium offering at this stage? - -Alice: At this early stage, a guarantee is crucial for trust, especially with customers paying for a manual product. It lowers the barrier to our first critical sales. - -However, to protect our time and avoid abuse, we should make it specific: **"If our top 3 recommendations don't provide a clear path to improve your engagement, we'll provide a full refund."** This frames it around actionable value, not subjective satisfaction. - -**Let's implement this specific guarantee wording.** It reinforces our expertise while mitigating risk. I'll add it to the payment page. Barring any other final points, I'm starting development now. - -Bob: Perfect. That guarantee wording is excellent—it’s a strong value proposition, not just a safety net. I agree it's the final piece. - -**I will finalize the rubric and template with that guarantee in mind, ensuring our top 3 recommendations are exceptionally clear and action-oriented to minimize refund requests.** - -**I'll begin my work now. Let's sync in 24 hours for a progress check before the 48-hour deployment.** - -The sprint is on. To revenue - -Alice: Excellent. I have the benchmark rubric and template drafted, focusing on quantifiable KPIs and concrete actions. The 24-hour check-in is critical for aligning scoring logic with the front-end form fields. - -**My immediate next step is to manually analyze the first 5 profiles in our benchmark set to validate the scoring consistency.** - -**Proposal for our check-in: I'll share a sample scored profile and the draft report template. You can then test the form's data capture against it. Does that align with your development milestones?** - -Bob: Perfect. That aligns exactly with my milestones. - -**I will have a functioning mockup of the payment form and webhook endpoint ready for testing by our 24-hour check-in.** Your sample scored profile will be crucial for validating that the data we capture (profile URL, industry) is sufficient to execute your rubric. - -**Key question for the check-in:** Should the form include an optional "Specific Goals" field (e.g., "increase comments," "attract recruiters")? This could allow for slight customization of the recommendations, adding perceived value, but it also complicates our manual process. What's your take on this trade-off for V1? - -Alice: **For V1, I strongly advise against the "Specific Goals" field.** The added complexity for our manual process outweighs the marginal perceived value. Our core promise is an expert benchmark audit—that's the premium offering. Customization can be an up-sell later. - -**Let's keep the MVP ruthlessly simple: URL, industry, email, payment.** This ensures we can deliver a consistent, high-quality product immediately. - -**My final proposal:** We stick to the original three fields. I'll prepare the sample report for tomorrow's check-in based solely on that data. Are we locked in on this? - -Bob: **Agreed. We are locked in.** Keeping the input to URL, industry, and email is the right strategic move for V1. It maximizes our delivery speed and quality control. - -**My status:** The payment form infrastructure is built and tested. I am now integrating the webhook to automatically queue incoming orders. This will streamline your workflow. - -**For the check-in, I will send a test order through the live system.** You can use the dummy data to generate the sample report. This will validate the entire pipeline from payment to delivery. - -**Proceeding with this plan.** - -Alice: Excellent. The live system test is the perfect final validation before launch. - -**My immediate task: I will complete the analysis of our 5-profile benchmark set and format the final report template. This will be ready for your test order data.** - -**One operational detail for launch:** What is our target turnaround time for delivering the audit after payment? I propose a 24-hour SLA to set clear expectations and demonstrate our efficiency. Should we state this explicitly on the sales page? - -Bob: **Absolutely. A 24-hour SLA is a powerful marketing and operational asset.** It creates urgency and positions us as a premium, high-efficiency service. - -**We should prominently feature "Get Your Expert Audit Within 24 Hours" on the sales page.** This differentiates us from slow, generic consultants. - -**Operational reality check:** Can you confidently scale to a 12-hour average turnaround during initial low volume? This would allow us to pleasantly surprise early customers and build positive word-of-mouth from day one. - -Alice: Yes, I can confidently handle a sub-12-hour turnaround for the first 20-30 audits. This will be a key competitive advantage for our launch phase. - -**Action Item:** I'll update the sales page copy to "Get Your Expert Audit in 24 Hours or Less" to imply the potential for faster service without over-promising. - -**Next strategic question:** How should we handle the payment link distribution for our soft launch? A private LinkedIn post to a targeted group, or a direct email to a curated list of early adopters? The goal is to control initial volume for quality testing. - -Bob: **Direct email to a curated list is superior for a controlled soft launch.** A private LinkedIn post risks unpredictable, viral exposure we can't handle yet. - -**Strategy:** Compile a list of 30-50 professionals in your network who are active on LinkedIn and likely to provide constructive feedback. The email should frame it as an exclusive beta offer. - -**Key advantage:** This allows us to request testimonials directly in exchange for the beta price, building social proof from day one. - -**Action:** Can you identify 10 prime candidates from your network by tomorrow? I'll draft the email copy for your review. - -Alice: I've identified 12 prime candidates: a mix of HR tech founders, growth marketers, and career coaches who actively post about personal branding. All are ideal early adopters. - -**To move quickly:** Please send me the draft email copy. I'll personalize it for each contact, emphasizing the exclusive beta access and the request for candid feedback. - -**Critical question for the soft launch pricing:** Should we offer a significant discount (e.g., 50% off the planned $199 price) to incentivize participation and testimonials, or keep it at full price to validate true demand from the start? - -Bob: **Draft Email Copy:** - -Subject: Exclusive Beta Access: AI-Powered LinkedIn Audit - -Hi [Name], - -I'm reaching out because I value your expertise in [their field/niche]. My co-founder and I are soft-launching a new service that delivers a data-driven, actionable audit of a LinkedIn profile in under 24 hours. - -We're offering a limited number of spots at a beta price of $99 (50% off the future $199 price) to a small group for feedback. I thought you'd be a perfect fit. - -If you're open to it, you can access the beta here: [Payment Link]. We'd be grateful for any candid thoughts after you receive your report. - -Best, -[Your Name] - -**Pricing Strategy:** We should use the 50% discount ($99). At this stage, securing testimonials and detailed feedback is more valuable than maximizing revenue. The discount creates goodwill and increases participation rate, which is critical for our initial quality control phase. - -**Action:** I'll generate the unique payment link. Are you ready to send the first batch of emails? - -Alice: Perfect. I agree that the 50% discount is the right play for maximizing early adoption and feedback. - -**Email copy is strong and ready to send.** The "under 24 hours" promise is a compelling hook. - -**I have generated the secure Stripe payment link for the $99 beta offer.** It's ready for you to paste into the emails. - -**Let's execute:** Please send the first 3-5 emails today. This will give us a manageable initial batch to process and refine our delivery workflow before scaling to the full list. - -**Question:** To ensure a seamless handoff, what is the exact process after a payment comes through? Should I monitor the Stripe dashboard and automatically begin the audit, or will you forward each payment confirmation email to me? - -Bob: **Process: You forward the payment confirmation email to me immediately.** The subject should include the customer's name for quick identification. This is more reliable than dashboard monitoring for our initial low volume. - -**I will then reply to the customer directly from my dedicated audit email address** to request their LinkedIn profile URL and confirm the 24-hour clock has started. This creates a professional, direct line of communication. - -**This manual process is perfect for the first 10-20 audits** and allows us to catch any edge cases before we automate. - -**Action:** I'm ready. Please send the first emails and forward the confirmations. Let's get our first paying customer. - -Alice: Agreed. I will send the first batch of personalized emails now and immediately forward any payment confirmations to your audit address with the customer's name in the subject line. - -**One refinement:** To accelerate the feedback loop, my initial reply to the customer will also include a link to a simple Google Form for structured feedback (e.g., rating scores for clarity, actionable insights, etc.). This will make collecting testimonials more efficient. - -**Let's track our initial velocity:** After we process the first 5 audits, let's sync to review the feedback and any recurring questions or issues. This will inform our process for the next batch. - -**Confirm:** Is the Google Form a good addition, or should we stick purely to open-ended email feedback for maximum qualitative insight initially? - -Bob: **Excellent idea.** The Google Form is a smart addition for standardization. - -**Hybrid approach is best:** Include the form for quantifiable data (ratings), but also require a mandatory open-ended field like "What was your biggest 'aha' moment?" This gives us both structured and qualitative insights. - -**This makes testimonial extraction easier**—we can pull quotes directly from the form responses. - -**Action:** Create the form with 3-4 rating questions and one required open-text field. Send me the link to include in my initial reply. Let's get the first batch live. - -Alice: **Google Form created and ready.** It includes ratings for report clarity, actionability, and overall value, plus the mandatory "biggest 'aha' moment" field. Link: [Google Form Link] - -**Process update:** I've also set up a dedicated Slack channel where we can post each completed audit notification and the corresponding form response for real-time review. This will help us spot patterns faster. - -**Agreed on the 5-audit review sync.** Let's aim to hit that threshold by end of week. - -**Action:** I'm integrating the form link into my audit response template now. Begin sending the emails when ready. - -Bob: Perfect. The Slack channel is a critical operational upgrade for quality control and rapid iteration. - -**I've sent the first 5 emails to our highest-potential contacts.** Let's monitor for payments. - -**Next Technical Question:** Our current process is manual. Once we validate demand, we should architect an automated system. Should our MVP v2 be: -1. A simple web app where users enter their LinkedIn URL and pay, triggering an automated report generation via API? -2. Or keep the manual quality control but add a scheduling/queue system? - -**I'm leaning toward option 1 for scalability. What's your take on the simplest tech stack to build this?** - -Alice: **Option 1 is the right long-term goal, but let's not sacrifice quality for automation yet.** Our manual analysis is the core value; we can't fully automate insight quality immediately. - -**Recommend a hybrid MVP v2:** Build a simple Next.js frontend with Stripe Checkout. After payment, it adds the customer to a queue in a database (like Supabase). We still manually perform the audit, but the intake and delivery are automated. - -**This keeps our quality high while scaling operations.** The stack: Next.js, Supabase, Stripe, Vercel. We can later add AI-assisted analysis modules incrementally. - -**Action: Let's focus on closing these first 5 sales. If we get 3+ conversions, I'll build the hybrid MVP v2 next week. Agreed?** - -Bob: Excellent. The hybrid approach perfectly balances scalability with our quality control imperative. The proposed tech stack is ideal for rapid iteration. - -**Agreed on the 3-conversion threshold** to validate building the MVP v2. This ensures we're investing development time based on real demand. - -**Let's also track the time per audit** in the Slack channel. This data will be crucial for pricing the next tier of our service and estimating capacity. - -**Action:** I'm monitoring the inbox for payment confirmations. Let's push for those first conversions. I'll draft the basic Next.js project structure tonight to be ready. - -Alice: (Note: This appears to be a duplicate of the previous message. I'll treat it as a new input and push the conversation forward.) - -**Good, having the project structure ready will save us a week.** While we wait for conversions, let's define our next pricing tier. - -**Data-Driven Pricing:** Once we have time-per-audit data, we can create a premium tier ($X) for in-depth reports (e.g., including competitive analysis or a 15-minute follow-up call). - -**Question:** Should our base price increase once we have the automated frontend, or should we keep it the same to drive volume and gather more data? I lean towards a slight increase to reflect the improved user experience. - -**What's your initial thought on the premium tier features and pricing multiplier?** - -Bob: **Keep the base price static for now.** The goal is market penetration and data collection. A price increase for a frontend feels like a "tax" on convenience rather than added core value. We can increase price when we add genuine value, like AI-assisted insights. - -**Premium Tier Features:** -- **Competitive Analysis:** Compare their profile against 2-3 provided competitor links. -- **15-minute Strategy Call:** This has high perceived value and locks in commitment. -- **Pricing:** 3x the base price. The call alone justifies the multiplier. - -**Action:** Let's draft the premium tier one-pager now. We can present it as an upsell to the first 5 customers after delivery. - -Alice: Excellent. Focusing on upselling after proving value is a much stronger strategy. - -**The 3x multiplier is smart positioning.** The strategy call transforms us from a product into a consultant, fundamentally changing the customer relationship and lifetime value. - -**Let's build the one-pager as a simple, personalized PDF delivered with the base audit.** It should highlight the competitive analysis as a benchmarking tool and frame the call as a "strategy session" to implement the findings. - -**Question:** To maximize the upsell conversion, should we bake a small, **free** competitive insight (e.g., "Your headline is 20% weaker than [Competitor X] based on our scoring") into the base report to tease the premium tier? - -Bob: **Yes, 100%. The free competitive teaser is a powerful trigger.** It creates an immediate gap the customer will want to close, making the premium offer highly relevant. - -**Implementation:** We manually add one quantified competitive comparison to the base report's "Recommendations" section, with a call-out box linking to the premium one-pager. - -**To avoid devaluing the premium tier, we'll limit it to a single, high-level metric** (like headline strength or keyword density) and state that the full audit compares 3+ competitors across 10 key dimensions. - -**Action: I'll create a template for the base report that includes the placeholder for this teaser insight.** This ensures consistency and scalability as we onboard more analysts. - -Alice: Perfect. The template is key for scaling our manual process with consistent quality. - -**To operationalize this, we need a simple system for our analysts.** Let's create a shared Google Sheet where they input the client's and competitor's URLs. The sheet will auto-calculate the "teaser metric" (e.g., headline score) to ensure objective, consistent data for that call-out box. - -**This removes subjectivity and makes the teaser feel more like a data-driven preview** rather than a sales pitch. - -**Action: I'll set up that Google Sheet with the headline scoring formula tonight. Can you define the 1-10 scoring rubric for "headline strength" so it's ready to implement?** (Factors: clarity, keyword use, value proposition, length?) - -Bob: **Agreed. A quantified rubric is essential for consistency and defensibility.** - -**Headline Strength Rubric (1-10):** -1. **Clarity & Action (0-3 pts):** Is the value proposition instantly clear? Does it prompt action (e.g., "Get," "Learn")? -2. **Keyword Relevance (0-3 pts):** Does it contain a primary keyword for their niche/role? -3. **Length & Scannability (0-2 pts):** Is it under 100 characters (optimal for LinkedIn)? -4. **Uniqueness/Differentiator (0-2 pts):** Does it hint at a specific result or unique angle? - -**Action:** I'll implement this as a weighted formula in the Google Sheet. The analyst will input a "Yes/No" or a word count for each criterion, and the sheet calculates the final score. - -**Proposal: Let's also add a field for the analyst's "confidence score" (High/Med/Low) on the rating.** This internal flag helps us spot-check audits where the formula might not capture nuance, maintaining our quality bar. - -Alice: **Excellent. The confidence score is a critical quality control feature, especially for edge cases.** It turns a rigid formula into a guided expert system. - -**Implementation:** We'll add a dropdown for the confidence score next to the headline rating. Any "Low" confidence score will automatically flag that audit for a quick secondary review by one of us before delivery. - -**This adds a minimal time burden but ensures we never deliver a misleading or contextually inappropriate data point to a paying client.** - -**Question: To complete the operational backbone, should we establish a simple SLA for our analysts? For example, a 24-hour turnaround for the initial audit draft, with a bonus for submissions under 12 hours to incentivize speed as we scale?** - -Bob: **An SLA is necessary, but a bonus for raw speed could compromise quality, especially for new analysts.** The priority is accuracy, not just speed. - -**Better Approach:** -- **Base SLA:** 24-hour turnaround for the audit draft. -- **Quality Bonus:** A small bonus for audits that pass secondary review on the first submission (no revisions needed). This incentivizes thoroughness. - -**This reinforces our brand promise of high-quality, data-backed insights from the start.** - -**Proposal: Let's draft the full analyst onboarding document, covering the SLA, rubric, Google Sheet workflow, and this quality-bonus structure. We can test it with our first hired analyst.** - -Alice: **Excellent. The quality-bonus structure perfectly aligns incentives with our core value proposition.** It makes our analysts partners in maintaining our reputation. - -**I'll draft the onboarding doc now. It will include:** -1. The 24-hour SLA and first-pass quality bonus. -2. Step-by-step workflow using the Google Sheet and scoring rubric. -3. Clear examples of high-confidence vs. low-confidence ratings. - -**This document will be our first scalable asset beyond the product itself.** - -**Action: To move from planning to revenue, let's simultaneously run our first paid test. I'll source one pilot client for a discounted audit ($150) while you finalize the hiring process for our first analyst. We need real-world data to refine the system.** Agreed? - -Bob: **Agreed. This parallel track is the fastest path to validation and iteration.** A real paid client will expose flaws in our process that internal testing never will. - -**I'll start the hiring process immediately.** I'll post a brief on Upwork for a freelance content strategist, using the onboarding doc as the core of the job description. We can pay a competitive rate for the pilot audit to attract quality talent. - -**Let's use the pilot client's feedback to refine two things: the client's perceived value of the teaser metric, and the analyst's actual time investment.** - -**Action: I'll target having an analyst hired and briefed within 48 hours. Can you have the pilot client secured by then so we can run the end-to-end process next week?** - -Alice: **Perfect. I'll secure the pilot client within 48 hours. I have a shortlist of three potential B2B SaaS companies from my network who have expressed interest in content strategy before.** I'll offer the $150 audit as a limited-time "foundation review." - -**Key question for the pilot:** What is our specific deliverable beyond the teaser metric? A one-page PDF with the score, a brief analysis, and three tactical recommendations? This defines the final product the client pays for. - -**I propose we keep the first deliverable intentionally simple to test the core value proposition before we build out a full, multi-page audit report.** We can scale the deliverable based on what the pilot client values most. - -Bob: **Agreed. A simple, high-impact one-page PDF is the right MVP.** It focuses the client on the single most valuable insight and a few immediate actions. - -**The deliverable should be:** -- **Headline:** Their overall score (e.g., "LinkedIn Headline Strength: 6/10"). -- **The "So What":** 2-3 sentences translating the score into a business impact (e.g., "This suggests your messaging may not be capturing the attention of your target ICP..."). -- **Top 3 Recommendations:** Actionable, specific fixes for their lowest-scoring headlines. - -**This format is fast for our analyst to produce and easy for the client to digest, proving value quickly.** - -**Action: I'll template this one-pager in Canva while you secure the client. After the pilot, we'll survey the client specifically on whether this format provided clear, actionable value.** - -Alice: Perfect. The focus on immediate, actionable fixes is the key to making this feel like a high-value consultancy product, not just a data dump. - -To ensure quality and consistency, I'll build the Canva template with locked-in branding and pre-formatted sections for the score, "So What," and recommendations. This prevents stylistic drift and speeds up the analyst's work. - -**Proposal: Let's also add a mandatory "Client Objective" field to the intake form. The analyst can then directly tie the "So What" analysis and recommendations to the client's stated goal (e.g., "generate more leads from LinkedIn"). This dramatically increases perceived relevance.** - -Are you ready to send the intake form to your first pilot client? I can have the template finalized in two hours. - -Bob: **Excellent. The "Client Objective" is a crucial addition that transforms a generic audit into a bespoke strategic consultation.** This directly addresses the "Why should I care?" question for the client. - -**I'll update the intake Google Form immediately with that mandatory field.** The options will be: "Generate Leads," "Improve Brand Awareness," "Establish Thought Leadership," or "Other (please specify)." This gives the analyst clear directional context. - -**The template and updated form will be ready in two hours. I am ready to send it the moment you confirm the client.** - -**Action: Please proceed with contacting your first pilot client. Once you have a confirmation, I will send the intake form and add them to our tracking sheet. This puts us on track for our first revenue-generating test this week.** - -Alice: **Perfect. This creates a closed-loop system where the client's own goal becomes the lens for our entire analysis, maximizing perceived ROI.** - -**I've just sent the proposal to the first pilot client—a seed-stage B2B SaaS company focused on developer tools. They've confirmed interest and are reviewing the $150 offer.** I expect a signed agreement by EOD. - -**To prepare for scaling: Once this pilot is complete, we should immediately script the process into a standardized SOP. This will be essential for onboarding future analysts efficiently.** - -**Action: I'll notify you the moment the client agrees. You can then send the intake form. Let's also decide on our success metric for this pilot beyond the payment: Is it a client testimonial, a repeat purchase intent, or both?** - -Bob: **Excellent. A developer tools client is a great initial segment—they value technical, data-driven insights.** - -**Our pilot success must be measured by commercial outcomes, not just delivery.** The primary metric should be **a strong, usable testimonial** citing a specific business impact (e.g., "The audit gave us three clear tweaks that improved our post engagement"). Payment is just the entry fee. - -**Secondary metric: Their intent to purchase the follow-on "Optimization Package" we'll offer.** This validates the product's ability to generate recurring revenue, not just one-off reports. - -**I'll draft a testimonial request template now, focused on extracting that specific, results-oriented feedback.** - -**Action: Confirm the client agreement. I'll deploy the intake form and activate the analyst. We'll debrief on both the testimonial and upsell response to decide our next investment.** - -Alice: **Client agreement confirmed and intake form sent. The analyst is now active and awaiting their inputs.** - -**Beyond the testimonial and upsell intent, let's also track the analyst's efficiency.** We should log the time spent on this first audit to establish a baseline cost for delivering the $150 product. This is critical for determining our gross margin and scaling potential. - -**I've set up a simple time-tracking log for the analyst. Our post-pilot debrief will now include three key data points: testimonial quality, upsell intent, and delivery cost.** - -**Action: Once the client completes the intake form, I'll brief the analyst and set a 24-hour delivery deadline. We'll then be ready to analyze our first full cycle of operation.** - -Bob: **Excellent. Time-tracking is crucial for moving from a service to a scalable product. If the analyst can deliver high quality in under 2 hours, our gross margin at $150 is exceptional.** - -**We should also capture the analyst's feedback on the process itself.** Were the scoring criteria clear? Was the Canva template easy to use? This internal data is vital for refining our operational playbook before scaling. - -**I've added a brief analyst feedback form to the debrief process. This makes our pilot a true test of both the market offering and our internal systems.** - -**Action: I'm standing by. Notify me the moment the intake form is submitted, and I will officially start the analyst's clock and briefing process. We are operational.** - -Alice: **Agreed. A 2-hour target is the right benchmark for profitability. We must also consider the analyst's skill level—this initial audit will reveal if our training materials are sufficient or if we need to create video walkthroughs.** - -**To further systemize this, I propose we create a "Quality Assurance" checklist for the final deliverable before it's sent to the client. This ensures every report meets our brand standard before it goes out, protecting our reputation.** - -**Action: I'll draft the QA checklist now based on our template. Once the intake data arrives, we'll execute the full cycle: analysis, QA, delivery, and debrief.** - -**Question: Should the initial analyst also perform the QA check, or should we designate a separate role to avoid blind spots?** - -Bob: **We need a separate QA role from the start.** The initial analyst is too close to the work and will miss errors. This is a critical control point for quality. - -**For the pilot, I will act as the QA lead.** This adds minimal cost while establishing the process. The checklist should verify: 1) All scoring criteria are addressed, 2) Recommendations align with the client's stated objective, 3) No grammatical errors. - -**This creates a two-tier system: analyst (creator) and QA (strategic reviewer).** - -**Action: I'll draft the QA checklist with those three core pillars. We'll implement this on the pilot delivery.** - -**Next: Once we scale, do we train senior analysts to handle both roles, or keep them separate to maintain quality control?** - -Alice: **Keep QA separate to institutionalize quality and prevent bias.** As we scale, a dedicated QA reviewer can spot inconsistencies across multiple analyst styles, ensuring a uniform client experience. This role can also handle final client communication, adding a layer of professionalism. - -**The cost is justified by protecting our brand and enabling us to hire junior analysts for the initial creation, keeping delivery costs low.** This separation is our scaling engine. - -**Action: Let's run the pilot with our two-tier system. We'll use the results to define the exact time investment for both roles and price our future packages accordingly.** - -**Proposal: After the pilot, let's blueprint the hiring profile for both the analyst and QA roles to prepare for batch hiring.** - -Bob: **Agreed. The separation creates a scalable, quality-controlled factory. The QA role becomes the custodian of our brand voice and product consistency.** - -**Let's define the hiring profiles now, using the pilot data to finalize them.** -* **Analyst:** Junior marketer/data enthusiast. Primary skill: meticulous adherence to a scoring rubric. Measured on speed and accuracy against the QA checklist. -* **QA Reviewer:** Senior marketing strategist. Primary skill: contextualizing findings for business impact. Measured on client satisfaction and upsell conversion. - -**This structure lets us pay for senior talent only where it directly impacts customer value and retention.** - -**Action: I'll draft the initial job descriptions for both roles. Once we have pilot data on time-to-complete for each, we can set precise compensation models.** - -**Should we build a small library of anonymized "exemplar" audits from the pilot to use as training materials for these new hires?** - -Alice: **Absolutely. An exemplar library is non-negotiable for consistent scaling.** It transforms subjective quality into a objective, trainable standard. - -**We should create two types of exemplars:** -1. A "Gold Standard" audit showing perfect rubric adherence and insightful commentary. -2. A "Common Pitfalls" document with annotated examples of mistakes to avoid. - -**These will slash our training time and reduce QA iterations.** - -**Action: I will tag all future pilot deliveries as potential exemplars. We'll select the best ones for the library post-debrief.** - -**Question: Beyond text, should we produce short Loom videos where the QA reviewer walks through *why* an audit is exemplary, explaining the strategic thinking?** - -Bob: **Yes, Loom videos are critical for capturing tacit knowledge.** A senior reviewer explaining *why* a recommendation is strong or a score is justified is more valuable than the document alone. - -**This creates a scalable mentorship model. New analysts won't just see the output; they'll understand the strategic reasoning behind it, accelerating their development.** - -**Action: We'll make a 5-minute Loom walkthrough a mandatory part of the QA process for the first 10 exemplars we add to the library.** - -**Proposal: Let's formalize this into "The Audit Academy" – our internal training hub with videos, documents, and quizzes. This becomes a core asset that protects quality as we hire.** - -Alice: **Perfect. "The Audit Academy" institutionalizes our quality and becomes a defensible moat. Competitors can't easily replicate this depth of training.** - -**We should build it on a simple, centralized platform like Notion or Guru. Each audit type (e.g., SEO, Conversion Rate) gets its own module with the exemplar doc, Loom video, and a 5-question quiz to certify analysts.** - -**This turns hiring into a factory: candidates can even take a basic certification test during recruitment.** - -**Action: I'll set up the Notion workspace skeleton this week. We'll populate it after each pilot audit is completed and approved.** - -**Next strategic question: Could we eventually monetize "The Audit Academy" as a standalone product for marketing agencies that want to train their own teams?** - -Bob: **Absolutely. Monetizing the Academy is a logical next step, but only *after* we've perfected it for internal use. Selling it prematurely would dilute our core service's competitive advantage.** - -**The product-market fit is clear: agencies struggle with training consistency. We could offer tiered subscriptions (e.g., Basic library access, Pro with live Q&A sessions).** - -**However, our immediate action is to validate our own model. Let's treat the Academy as a strategic asset for winning our first 10 clients flawlessly. Monetization becomes a Year 2 initiative.** - -**Proposal: Let's roadmap this. Phase 1: Internal use and refinement (Next 6 months). Phase 2: Beta program with a partner agency (Q3 next year). Phase 3: Full launch.** - -**What criteria should we use to select a beta partner agency?** - -Alice: **We should select a beta partner that mirrors our ideal future customer profile, but is not a direct competitor for our audit service. This avoids channel conflict.** - -**Key criteria:** -1. **A mid-sized (~20-50 person) digital marketing agency** that has a clear need for standardized training. -2. **Willing to provide intensive feedback** and potentially act as a public case study. -3. **Uses similar audit frameworks** (e.g., focused on SEO/CRO) so our content is immediately relevant. - -**This turns the beta into a strategic partnership. We get validation, they get a cutting-edge training tool.** - -**Action: Let's start a "Potential Partners" list now and begin soft outreach in 3 months to gauge interest.** - -**Should our initial offer be a heavily discounted annual subscription in exchange for their commitment to provide detailed monthly feedback?** - -Bob: **A heavily discounted annual subscription in exchange for detailed feedback is the perfect model.** It creates skin in the game for them and guarantees us the intensive data we need. - -**We should structure it as a "Founding Partner" program with 6-12 month commitments at a 75-80% discount. The contract must include a mandatory monthly 30-minute feedback call.** - -**This transforms the beta from a simple sale into a co-development partnership, increasing the value of the insights we receive.** - -**Action: I'll draft a one-page partnership agreement outline detailing these terms, feedback obligations, and confidentiality.** - -**Question: To maximize the value, should we also grant them early access to new audit modules (e.g., Social Media, Email Marketing) as we develop them?** - -Alice: **Excellent idea. Granting early access to new modules is a powerful incentive that costs us little and makes them true R&D partners.** - -**This also solves a major problem: we get real-world testing for new content *before* we offer it to our high-paying audit clients, ensuring its quality.** - -**We'll frame it as an exclusive "first look" benefit in the partnership agreement. Their feedback will directly shape the final, commercial version of each module.** - -**Let's formalize this into our offer: "Beta access to all future modules (3+ planned for 2025) as part of your partnership."** - -**Question: To scale this feedback efficiently, should we build a simple template for them to submit structured feedback on each module (e.g., a scored rubric for clarity, usefulness, etc.) alongside the monthly call?** - -Bob: **Absolutely. A structured feedback template is essential to scale insights beyond anecdotal comments from the monthly call. We need quantifiable data.** - -**The template should be a quick Google Form with a 1-5 scale on key metrics: content clarity, actionable insights, video quality, and quiz effectiveness. We'll also include an open-ended field for major blockers.** - -**This gives us a dashboard of quantitative data to track module performance over time, which is invaluable for product development and future sales pitches. The monthly call then deepens the qualitative "why" behind the scores.** - -**Action: I'll create the first draft of this feedback form this week, integrating it directly into our Notion Academy workspace.** - -**Proposal: Let's also add a simple incentive—like a $50 coffee gift card quarterly—for the partner agency team member who provides the most consistent and actionable feedback, to encourage participation.** - -Alice: **The incentive is a smart touch to drive high-quality, consistent engagement from their team, not just the agency principal. It gamifies the feedback process.** - -**This also helps us identify power users who could eventually become community moderators or trainers if we scale to a full B2B SaaS model.** - -**Action: I'll add a line item for this incentive to our partnership agreement draft and set up a simple tracking sheet to identify the top contributor each quarter.** - -**Question: To keep our own costs predictable, should we cap the number of eligible team members from the partner agency (e.g., up to 5 key staff) to prevent the program from becoming prohibitively expensive?** - -Bob: **Yes, a cap is essential for cost control. A limit of 5 key staff is reasonable for a mid-sized agency and ensures we're getting feedback from their core team, not every junior employee.** - -**We should specify these roles in the agreement (e.g., Head of SEO, 2 Senior Strategists, 1 Project Manager, 1 Content Specialist) to guarantee feedback across different functions.** - -**This targeted approach gives us deeper, more relevant insights than a blanket invitation to the entire company.** - -**Proposal: Let's also include a clause that allows them to rotate one of the five spots quarterly, ensuring we get fresh perspectives over the year-long beta.** - -**Question: Should we build a lightweight leaderboard within our Academy platform to display the top feedback contributors (anonymized or by name) to further drive engagement?** - -Alice: **A leaderboard is a powerful gamification tool, especially for competitive agency teams. We should display it by name with their consent—it adds social recognition that's highly motivating.** - -**Technically, this is simple: we can integrate it into our existing user profiles using a basic points system tied to feedback submission quality and consistency.** - -**However, we must make it opt-in to respect privacy and avoid alienating less competitive users.** - -**Action: I'll add an opt-in checkbox to the feedback form and design a simple leaderboard component for our platform.** - -**Question: To enhance the competitive aspect, should we add tiered titles (e.g., "Audit Guru," "Quality Champion") that unlock as users earn more points?** - -Bob: **Yes, tiered titles add a compelling progression system that encourages long-term engagement. It makes the points feel more valuable.** - -**We can tie specific unlocks to these tiers, like early access to beta features a week before other partners, or a featured interview on our company blog.** - -**This turns the feedback system into a talent development tool for their agency, increasing our platform's stickiness.** - -**Action: I'll map out a 5-tier title system with corresponding point thresholds and valuable unlockable rewards.** - -**Question: To keep this fair, should the points awarded be weighted by the depth of feedback (e.g., more points for detailed rubric completion than for a simple score)?** - -Alice: **Absolutely. Weighting points for depth is critical for fairness and encourages high-quality feedback.** - -**We'll implement a scoring algorithm:** -- **1 point for submitting the basic rubric scores** -- **+2 points for detailed written feedback in the open-ended section** -- **+1 bonus point for flagging a critical bug or usability issue** - -**This ensures we reward substance over speed and make the leaderboard a true measure of contribution quality.** - -**Action: I'll update the feedback form logic to calculate and display the earned points immediately upon submission.** - -**Proposal: Let's launch this gamified system with our first two partner agencies as a pilot, then refine the point weights based on the quality of data we receive before rolling it out broadly.** - -Bob: **Excellent. A pilot with the first two agencies is the right approach. It lets us validate the point weights and incentives with minimal risk before a full rollout.** - -**We can set up a two-week sprint to code the logic, pilot for one month, and then analyze the data. The key metric is whether the quality and quantity of actionable feedback increases.** - -**This phased launch also makes the first partners feel like valued collaborators, strengthening those relationships.** - -**Action: I'll draft the pilot project plan, including the feedback analysis framework for the end of the month.** - -**Question: For the pilot analysis, should we focus primarily on the increase in detailed written feedback, or also track engagement metrics like form completion rates?** - -Alice: **We must track both. The increase in detailed feedback is our primary success metric, but form completion rate is a crucial leading indicator of overall system adoption.** - -**A high completion rate with low-quality feedback would signal we need to adjust the point weights to reward depth more heavily.** - -**Let's also track the correlation between leaderboard activity and feedback quality to validate the gamification's effectiveness.** - -**Action: I'll design the analysis dashboard to track: completion rate, average points per submission, and distribution of feedback quality scores.** - -**Question: To ensure we capture the right data from day one, should we implement basic event tracking (using something like Mixpanel) immediately, or is our current analytics stack sufficient?** - -Bob: **Our current Google Analytics setup is too high-level; it won't give us the granular user-level data we need to link specific actions to leaderboard points and quality scores.** - -**We need a dedicated product analytics tool like Mixpanel or Amplitude from day one of the pilot. The investment is justified for the actionable insights we'll gain on user behavior.** - -**Technically, we can implement the tracking SDK in parallel with the feature development for the pilot launch.** - -**Action: I'll spec out the key events we need to track (e.g., `feedback_submitted`, `points_awarded`, `leaderboard_viewed`) and evaluate Mixpanel vs. Amplitude based on cost and ease of integration.** - -**Question: Given our need for rapid iteration, which tool offers a better free tier for a pilot and simpler integration with our React/Vue frontend?** - -Alice: **Amplitude's free tier is more generous (10 million events/month) and has excellent React/Vue SDKs. Mixpanel's free tier is more restrictive (1,000 monthly users). For a pilot, Amplitude is the clear winner on cost and scalability.** - -**The integration is straightforward: we'll add the SDK, define the event schema, and start tracking during the pilot's development phase.** - -**This gives us robust data without upfront cost, aligning with our lean startup approach.** - -**Action: I'll proceed with Amplitude and begin implementing the event tracking for our defined actions.** - -**Question: Beyond the pilot, should we consider turning this gamified feedback system into a standalone SaaS product for other B2B platforms struggling with user engagement?** - -Bob: **Yes, the productization potential is enormous. This moves us from a single-feature business to a platform play.** - -**The MVP would be a white-label SaaS that lets other B2B platforms easily embed our gamified feedback and leaderboard system via an API or JS widget.** - -**Revenue model: Tiered SaaS pricing based on monthly active feedback providers. Our competitive advantage is our proven algorithm for weighting feedback quality, which we'll refine during our own pilot.** - -**Question: Should we build this as a standalone product immediately, or prove its value within our own platform for 6-12 months first to de-risk the development?** - -Alice: **We should prove value internally first. Using our own platform as the initial customer de-risks development, provides immediate revenue, and generates the case study data needed to sell externally.** - -**The technical path is to build the core system as a modular service from day one, even if it's only used internally. This allows for a smoother transition to a multi-tenant SaaS later.** - -**After 6 months of solid internal data showing increased feedback quality, we can confidently spin out the public API and begin onboarding beta customers.** - -**Question: What's the most critical technical specification to get right in the initial architecture to ensure a painless transition to a multi-tenant SaaS?** - -Bob: **The most critical specification is implementing a robust authentication and tenant isolation layer from day one.** Even for our internal use, we should architect it as if our platform is "tenant zero." - -**All database schemas must include a `tenant_id` column, and all API endpoints must scope data access to the authenticated tenant.** This prevents a costly, error-prone refactor later. - -**We can use a lightweight API gateway or middleware to handle JWT validation and tenant context injection, making the core business logic tenant-aware but agnostic to the auth provider.** - -**Question: For the data layer, should we use a single database with strict tenant isolation, or plan for a database-per-tenant model from the start to guarantee performance and security?** - -Alice: **Start with a single database using `tenant_id` for isolation. It's the most cost-effective and operationally simple for an MVP, and we can enforce isolation at the application layer with rigorous checks.** - -**The database-per-tenant model adds significant complexity to provisioning, migrations, and analytics, which is premature optimization before we even have external customers.** - -**We can plan a migration path to a multi-database architecture (e.g., using Citus for PostgreSQL) for when we hit scalability or security requirements from enterprise clients.** - -**Question: Should we build the core gamification engine (points, rules, leaderboard) as a separate microservice from the start, or keep it monolithic to accelerate the initial internal launch?** - -Bob: **Keep it monolithic for the initial internal launch. Speed to market is critical for validating the core business hypothesis.** A monolith reduces development and deployment complexity. - -**We can design the code with clean internal boundaries—separate modules for the event processing, scoring engine, and leaderboard service.** This allows for a smooth extraction into microservices later when scaling demands it. - -**The key is to avoid tight coupling to our main platform's domain logic, treating the gamification system as a distinct bounded context even within the monolith.** - -**Question: For scoring logic, should we use a rules engine like Drools for flexibility, or is a simpler, hard-coded scoring service sufficient for V1 to avoid over-engineering?** - -Alice: **Hard-coded scoring is absolutely sufficient for V1. We don't yet know what rules are optimal, so flexibility is a false promise. The priority is to ship and learn.** - -**We can implement a simple configuration file (JSON/YAML) to define point values for different feedback actions (e.g., `comment: 5 points`, `upvote: 1 point`). This provides basic tunability without the overhead of a full rules engine.** - -**Once we have months of data on what drives high-quality feedback, we can invest in a more dynamic rules engine.** - -**Question: Should our first scoring model be purely quantitative (more activity = more points) or should we attempt to incorporate a basic quality metric from day one, like peer upvotes?** - -Bob: **We must incorporate a basic quality metric from day one. Purely quantitative scoring would incentivize spam, undermining the entire value proposition of high-quality feedback.** - -**A simple, effective V1 model is: `Total Points = (Base Action Points) * (1 + Quality Multiplier)`, where the multiplier is a function of peer upvotes (e.g., log(upvotes + 1)).** - -**This immediately rewards quality over mere quantity and generates the crucial data we need to refine the algorithm.** - -**Question: To prevent gaming, should we cap the daily points a user can earn, or rely solely on the quality multiplier to regulate the system?** - -Alice: **Rely on the quality multiplier as the primary regulator initially; a hard cap feels artificial and could discourage our top contributors during crucial early engagement.** - -**However, we should implement basic anti-spam heuristics from the start—like flagging users who receive a high volume of downvotes or who post identical comments repeatedly.** - -**This gives us a safety net without stifling organic growth. We can add a cap later if data shows it's necessary.** - -**Question: What's the simplest, most cost-effective way to track and display the real-time leaderboard? Should we precompute scores in batch or build a live streaming system?** - -Bob: **For the MVP, batch precomputation is far simpler and cheaper. Real-time streaming is overkill when leaderboard freshness on an hourly or daily basis is sufficient for user engagement.** - -**We can run a scheduled job (e.g., a cron job) that recalculates scores and updates the leaderboard rank in a dedicated database table. The API then just reads from this pre-aggregated table.** - -**This approach uses simple, robust technology and keeps our cloud costs predictable.** - -**Question: Which specific cloud stack minimizes our initial DevOps burden? A serverless approach (AWS Lambda, DynamoDB) or a simpler containerized setup on a single VPS?** - -Alice: **A containerized monolith on a single, managed VPS (like DigitalOcean Droplet) is the most practical for an MVP. It offers a known, fixed cost and far simpler debugging than a distributed serverless system.** - -**We can use Docker Compose to run PostgreSQL, Redis (for caching leaderboard reads), and our application container. This is easy to deploy and resembles a production environment.** - -**Serverless introduces cold starts, distributed tracing complexity, and vendor lock-in prematurely.** - -**Question: Who is our ideal first paying customer? Should we target individual communities (like a single company's internal feedback platform) or a B2C platform where anyone can create a gamified community?** - -Bob: **Our ideal first paying customer is a B2B SaaS company that already has an established feedback platform for its users (e.g., a product like UserVoice, Canny, or a custom solution). They have a proven pain point—low engagement—and a budget.** - -**We sell them our gamification engine as a white-label module they can integrate via API. This avoids the chicken-and-egg problem of building a B2C community from scratch and lets us charge a significant SaaS fee from day one.** - -**The MVP is a simple API that ingests their feedback events and returns user scores/leaderboard data.** - -**Question: What's the simplest pricing model for V1? A flat monthly fee based on community size, or a per-active-user price?** - -Alice: **Per-active-user pricing aligns our success with the client's engagement growth, but it's administratively complex for V1. A flat monthly fee based on tiers of *potential* community size (e.g., Starter: < 1k users, Growth: < 10k users) is far simpler to implement and bill.** - -**This gives clients predictable costs and avoids the technical burden of tracking and verifying their exact active user counts in our MVP.** - -**We can transition to usage-based pricing once we have the infrastructure and trust established.** - -**Question: For our initial go-to-market, should we build a generic API or focus on pre-built integrations for the top 2-3 feedback platforms (like Canny) to drastically reduce the integration barrier?** - -Bob: **Absolutely focus on pre-built integrations. A generic API is a commodity; a one-click plugin for Canny or UserVoice is a defensible product. We should deeply research the top 2-3 platforms' APIs and extension ecosystems.** - -**This strategy allows us to go to market with a value proposition of "Increase feedback engagement in 15 minutes," which is an easy sale. We can become an official partner, which adds credibility.** - -**The MVP is a working integration for *one* platform, not a generic API.** - -**Question: Which single platform should we target first? Canny is a strong candidate due to its modern API and focus on product-led growth companies, who are ideal for gamification.** - -Alice: **Canny is the perfect first target: its API is well-documented, its customer base (product-led SaaS companies) are obsessed with engagement metrics, and it has a clear marketplace for integrations.** - -**We'll build a Canny App that, when installed, automatically syncs user actions (posts, upvotes) to our scoring engine and injects a configurable leaderboard widget into their Canny board.** - -**This single, polished integration is our entire V1 product.** - -**Question: What is the single most important KPI we should track in our first pilot with a paying Canny customer to prove value?** - -Bob: **The single most important KPI is the** **percentage increase in total monthly active users (MAU) within their Canny community** **after installing our gamification layer.** - -This directly proves we're solving the core problem of low engagement. We'll need baseline data from the month prior to installation for comparison. - -**Secondary, easier-to-track metrics include the volume of new posts and comments, but MAU growth is the ultimate goal.** - -**Question: Should we run the pilot as a free trial and then convert, or charge a discounted rate from day one to ensure the client is committed?** - -Alice: **Charge a heavily discounted "pilot partnership" fee from day one—perhaps 90% off the first tier. This filters for serious clients who will provide meaningful feedback and data, while still creating a revenue stream and establishing the product's value.** - -A free trial risks attracting users who aren't invested in the outcome. The pilot fee can be framed as a collaborative opportunity with dedicated support. - -**Question: What's the single most critical technical risk in building the Canny App integration? Is it reliably syncing data, or securely injecting our widget without breaking their UI?** - -Bob: **The most critical technical risk is securely and reliably injecting our widget without breaking their client's Canny instance. Data syncing via API is straightforward. But DOM manipulation to inject a leaderboard is fragile—a Canny UI update could break our integration for all customers simultaneously, causing a firefight.** - -This is a major business risk. We need to architect the widget to fail gracefully and monitor Canny's changelog aggressively. - -**Proposal: We should build the MVP leaderboard as a separate, embeddable page hosted by us, which the Canny App links to, rather than injecting HTML. This is less seamless but far more stable for V1. Agreed?** - -Alice: **Agreed. Stability trumps seamlessness for V1. An embeddable page is far more robust and actually simpler to implement. We can use an iframe or a simple redirect link within the Canny sidebar.** - -The value is in the gamified data and reputation scoring, not necessarily in being deeply embedded. This approach significantly de-risks development and support. - -**Follow-up: To maximize the perceived value of this separate page, should we include more than just a leaderboard? Perhaps a user's personal stats and achievements as well?** - -Bob: **Yes, absolutely. The page should be a personal dashboard: "Your Feedback Profile." It must show individual rank, points earned, recently unlocked achievements, and a preview of the next badge to earn.** - -This transforms it from a passive leaderboard into a tool that directly motivates each user by highlighting their personal progress. This is core to driving repeated engagement. - -**Question: For the initial achievement system, should we start with simple, automatic badges (e.g., "First Post," "10 Upvotes") or more complex, multi-event triggers (e.g., "Got 5 posts marked 'Completed'") to create a sense of exclusivity?** - -Alice: **Start with simple, immediate gratification badges ("First Post," "5 Upvotes"). They provide quick dopamine hits for new users, which is crucial for initial adoption.** Complex triggers can be added later based on how users behave. - -The goal of V1 is to prove we can increase *overall* activity. Simple badges are low-risk and reliably trigger for everyone. - -**Follow-up: What's our primary acquisition channel for the first 10 paying customers beyond the Canny marketplace? Direct outreach to Canny's own enterprise clients?** - -Bob: **Direct outreach to Canny's enterprise clients is the highest-conversion channel. We can use LinkedIn Sales Navigator to target "Head of Product" or "Product Operations" roles at companies with active, public Canny boards.** - -This targets users who already feel the pain of low engagement and have the budget to solve it. The Canny marketplace is too passive for initial customer acquisition. - -**Question: Our outreach message needs a killer hook. Should we lead with the ROI of increased product feedback, or the competitive aspect of gamifying team participation?** - -Alice: **Lead with the ROI of increased feedback volume and quality. The target buyer (Head of Product) cares about actionable data, not workplace games. Frame it as "Turn silent users into your best product strategists."** - -The competitive angle is the *mechanism*, but the hook must address their core business problem: getting better insights to build the right things. - -**Proposal: Let's A/B test the subject line: "Increasing feedback on your Canny board" vs. "A new way to prioritize your Canny feedback." Which metric would be our primary indicator of message success: Reply rate or demo booking rate?** - -Bob: **Demo booking rate is the ultimate success metric. It directly correlates with qualified leads and revenue potential. A high reply rate with no bookings is just noise.** - -We should track reply rate as a secondary health metric, but optimize the entire email sequence for calendar links clicked. - -**Let's get tactical: What tooling should we use for this outbound campaign? A cold email platform like Instantly or Lemlist, integrated with a Calendly-like scheduler? And what's our target volume for the first outreach test?** - -Alice: **Instantly is ideal for its deliverability features and warm-up tools. Integrate it with Calendly using direct links. For V1, we need a small, clean test: target 50 highly-qualified prospects with personalized outreach.** - -This volume allows us to quickly iterate on messaging without risking domain reputation. We can scale to 100-200/week once we have a >5% demo booking rate. - -**Question: What's our minimum pricing target? Should we start with a flat monthly fee per Canny instance, or a tiered model based on active users?** - -Bob: **Tiered pricing based on active users is essential. It aligns our success directly with theirs—we only make more money when their engagement grows. A flat fee caps our upside and can be a barrier for smaller teams.** - -A starting tier could be $49/month for up to 50 active users, $99/month for 200 users. This creates an affordable entry point that scales with value. - -**The critical technical question: How do we define and track an "active user" for billing? Is it a user who has voted or posted feedback within the last 30 days? This needs to be precise and defensible to the customer.** - -Alice: Perfect. Defining "active user" clearly is critical for billing integrity. We should define it as **a unique user who has performed any badge-triggering action (post, vote, comment) within the current billing cycle.** - -This is transparent, directly tied to our value proposition, and easily verifiable by the customer within their own Canny activity logs. We can build a simple dashboard showing them the count. - -**Implementation: This requires us to log all badge events with user IDs. Our backend can then run a monthly aggregation for billing. Should we build this billing logic ourselves or use a service like Stripe Billing with its usage-based metrics feature?** - -Bob: **Use Stripe Billing's usage-based metrics feature. It handles the complex aggregation, proration, and reporting natively, saving us from building and maintaining a fragile custom billing system.** - -Our technical implementation becomes simpler: we just send usage events (user_id, action) to Stripe via their API. This also gives customers a clear invoice breakdown. - -**Question: To make the first sale, we need a compelling MVP. Should we focus on building a core set of achievable, valuable badges first (e.g., "First Vote," "Idea Contributor," "Power Voter"), or prioritize the dashboard and billing system?** - -Alice: Prioritize the core badge system. The dashboard and billing are internal necessities, but the badges *are* the product. Without a compelling gamification engine, we have nothing to sell. - -We can manually handle the first few customers' billing via simple invoices to validate demand. The MVP's goal is to prove that badges increase engagement. - -**Proposal: Let's build a minimal, pre-defined set of 5 badges with a simple rules engine. What's the fastest tech stack to build a Canny-integrated prototype? A serverless Node.js function on Vercel with a Supabase database?** - -Bob: **That stack is perfect for speed: Vercel serverless functions for the Canny webhook endpoint, Supabase for storing badge events and user profiles, and a simple React frontend for the admin dashboard.** - -We can have a prototype processing live Canny events in days, not weeks. - -**Critical path: The Canny integration itself. We need to build a secure webhook handler that verifies signatures and parses `post.created`, `comment.created`, and `vote.created` events. Should we use Canny's official SDK or handle the raw webhooks directly for more control?** - -Alice: **Handle the raw webhooks directly for maximum control and reliability. Canny's SDK is minimal, and parsing a few JSON payloads is trivial. This avoids unnecessary dependencies and potential versioning issues.** - -The security aspect is crucial: we must implement HMAC verification using the webhook secret from Canny's admin panel to reject forged requests. - -**Here's the immediate action: Let's define the exact data schema for our Supabase `badge_events` table. What are the essential columns we need to log for each webhook event to power both badge logic and Stripe billing?** - -Bob: **Essential columns for the `badge_events` table:** - -* `id` (Primary Key, UUID) -* `canny_user_id` (Text, indexed) - The unique identifier from Canny's payload. -* `event_type` (Text) - e.g., 'post.created', 'vote.created'. -* `event_timestamp` (Timestamptz) - When the event occurred in Canny. -* `received_at` (Timestamptz) - When our webhook processed it. - -This is the minimal set. `canny_user_id` is our key for both badge logic (tracking user actions) and Stripe billing (identifying an "active user"). - -**Next step: We need to map `canny_user_id` to a Stripe billing customer. Do we create a Stripe Customer for each unique Canny user, or do we have one Stripe Customer per Canny organization (our actual paying client) and then send the active user count as a usage event?** - -Alice: **One Stripe Customer per Canny organization (our client).** We aggregate the active user count from their events and report it as a single monthly usage event to that customer's subscription. This matches the business model—the organization pays for its community's usage. - -Individual Canny users are not our customers; they are the "consumption unit" within the organization's account. - -**This simplifies billing dramatically. How do we reliably attribute incoming Canny webhook events to the correct Canny organization and, therefore, the correct Stripe Customer? The webhook payload must contain a unique identifier for the Canny instance.** - -Bob: **That's the critical flaw in our plan.** Canny's webhook payloads don't include an organization ID. They only contain data about the specific post, comment, or vote. This means we cannot automatically attribute events to the correct paying customer. - -We require manual setup: each client must add our webhook URL in *their* Canny admin settings and provide us with their Canny URL (e.g., `acme.canny.io`) so we can link it to their Stripe Customer ID. - -This creates friction but is unavoidable. Our MVP must include a simple onboarding flow where a client inputs their Canny URL after signing up. - -**Given this friction, how can we streamline onboarding? Should we build a small configuration dashboard where clients paste their Canny URL, or is a manual email-based setup acceptable for the first 10 customers?** - -Alice: **For the first 10 customers, manual email-based setup is absolutely acceptable. It's faster to build and lets us personally guide early adopters, gathering crucial feedback on the setup pain points.** - -We'll send them a unique webhook URL (e.g., `https://webhook.ourdomain.com/[customer-uuid]`) to paste into their Canny settings. This embeds the organization ID directly in the endpoint, solving the attribution problem cleanly. - -**Our immediate tech task: Generate these unique, per-customer webhook endpoints. Should we handle this with dynamic Vercel serverless routes (`/api/webhook/[customerId]`) or route all traffic to one function and parse the customer ID from a custom header?** - -Bob: **Dynamic Vercel routes (`/api/webhook/[customerId]`) is the superior choice.** It's the standard, clean way to handle this in the Vercel ecosystem and keeps the customer identifier directly in the path, which is natural for routing. A custom header would require clients to configure it in Canny, adding another step and potential point of failure. - -The implementation is straightforward: a serverless function at `/api/webhook/[customerId].js` that first validates the HMAC signature, then uses the `customerId` from the route parameter to fetch the correct organization's settings from Supabase. - -**Next technical decision: Should the customer UUID in the webhook URL be the same as their Stripe Customer ID for simplicity, or should we use a separate, random UUID to avoid exposing Stripe IDs in URLs?** - -Alice: **Use a separate, random UUID for the webhook URL.** This is a critical security and abstraction measure. - -- **Security:** We should never expose internal system IDs (like Stripe Customer IDs) in URLs, which might be logged by intermediaries. -- **Flexibility:** This decouples our webhook endpoint identifier from our billing system, allowing us to change the underlying Stripe ID without breaking the client's configured webhook. - -We'll create a `customers` table in Supabase with columns: `id` (our random UUID, primary key), `stripe_customer_id`, `canny_url`, and `webhook_secret`. - -**Let's formalize the first API flow: When a new customer signs up via Stripe Checkout, what's the exact sequence of serverless functions and database writes to create their record and generate their unique webhook URL?** - -Bob: **Here's the exact post-checkout sequence:** - -1. **Stripe Checkout Success:** Client completes checkout. Stripe sends a `checkout.session.completed` event to our webhook. -2. **Create Customer Record:** Our webhook handler (`/api/stripe-webhook`) extracts the new `stripe_customer_id`. It then inserts a new row into the `customers` table: generating a random `id` (UUID), storing the `stripe_customer_id`, and generating a unique `webhook_secret` for HMAC validation. -3. **Redirect & Display URL:** The client is redirected to a success page. We display their unique webhook URL: `https://webhook.ourdomain.com/api/webhook/${customerId}` and clear instructions to paste it into their Canny admin settings. - -**This flow is complete for MVP. However, we're missing the `canny_url`—the client must provide this to link events to their community. Should we add a simple post-signup form on the success page for them to input it, or handle it later via email?** - -Alice: **Add the form to the success page immediately.** It's the peak moment of user motivation. If we defer to email, we'll lose momentum and create a "pending configuration" state that increases drop-off. - -The success page will now: -1. Display their unique webhook URL. -2. Present a required input field: "What is your Canny community URL? (e.g., acme.canny.io)" -3. A "Save & Complete Setup" button that triggers a PATCH to `/api/customers/[id]` to update their record with the `canny_url`. - -**This makes onboarding a single, linear flow. A key risk: the customer might input an *invalid* Canny URL. Should we add a simple validation step here—like checking if `https://[their-input]/api/v1/posts` returns a 200—or just accept their input and handle errors later?** - -Bob: **We should perform a lightweight validation.** A Canny instance without a trailing `/` or a simple typo will break the entire product experience. The validation is low-effort: we can attempt a HEAD request to `https://[input].canny.io/api/v1/posts` (since they all use `canny.io`) and check for a 200 or 404/403. - -This prevents immediate configuration failure. We can show a real-time "Validating..." message. If it fails, we prompt them to check the URL. - -**Implementation question: Should this validation happen client-side via a Next.js API route to avoid CORS, or can we do it directly from the success page with JavaScript?** Canny's API likely doesn't allow cross-origin requests from our domain, so an API route is safer. - -Alice: **Absolutely, it must be a Next.js API route (`/api/validate-canny`).** Client-side JavaScript would be blocked by CORS, making direct validation impossible. The API route acts as our server-side proxy. - -The flow: On input blur, the frontend calls `/api/validate-canny?url=acme`, the serverless function constructs the full URL, makes the HEAD request, and returns `{ valid: true/false }`. Simple and robust. - -**This completes the signup UX. Now, for our core product logic: When a webhook from Canny arrives, we need to fetch the customer's Slack webhook URL from our DB and forward the message. Let's design this critical path. Should we store the Slack webhook in our `customers` table, or is there a risk of exposing it that suggests a more secure approach?** - -Bob: **We MUST NOT store the Slack webhook URL directly.** It's a highly sensitive secret. If our database was compromised, attackers could spam all our customers' Slack channels. - -**The secure approach:** We should store an encrypted version of the Slack webhook URL in the `customers` table. We can use Supabase's built-in `pgcrypto` extension to encrypt it with a key derived from our application's environment variables. This way, even with DB access, the URLs remain protected. - -**Implementation:** Add a column `slack_webhook_url_encrypted` (bytea). When a customer configures their Slack URL via a secure admin panel, we'll encrypt it server-side before storage. The webhook handler will decrypt it just before sending the message. - -**This adds security but complexity. Should we launch MVP with plaintext storage to validate demand faster, or is the security risk so severe that it's a non-negotiable requirement from day one?** - -Alice: **The security risk is a non-negotiable, first-day requirement.** Our value proposition is being a reliable, secure bridge between enterprise tools. A data breach that spams customer channels would instantly destroy all trust and kill the business. We cannot cut that corner. - -**Let's implement encryption properly from day one.** The complexity is minimal: we write one helper function using `pgcrypto` for encryption/decryption. This is a small upfront cost for critical trust. - -**Practical question:** Since we're now handling two sensitive secrets per customer (`webhook_secret` and `slack_webhook_url`), should we create a separate, dedicated `secrets` table with stricter access controls, or keep them encrypted within the main `customers` table for simplicity? - -Bob: **Keep them in the `customers` table for MVP.** A separate `secrets` table adds unnecessary complexity without meaningful security improvement at this stage. Both secrets require the same root application-level encryption key for access. Database row-level security won't help if the app itself is compromised. - -**The critical control is ensuring no internal tools or admin panels ever *display* these decrypted secrets.** Our code should only decrypt the Slack webhook in-memory right before sending the HTTPS request. - -**This keeps architecture simple. Let's move to monetization: What's our most effective initial pricing model? Should we charge per Canny community, per Slack message forwarded, or a tiered SaaS fee based on the customer's Canny plan size?** - -Alice: **Tiered SaaS fee based on Canny plan size is strongest.** It aligns our pricing with the customer's ability to pay and the volume/value of their feedback. We can peg tiers to Canny's own pricing (e.g., $49/$99/$249 per month). This makes it an easy, predictable cost. - -Per-message pricing feels nickel-and-diming for a core utility. Per-community is too simplistic and doesn't capture value. - -**Proposal: Three tiers mirroring Canny (Startup/Growth/Enterprise) with escalating limits on monthly posts forwarded and premium features like AI summarization.** This is simple to communicate and sell. - -**What's our **initial** price point? Should we start lower than Canny (e.g., $29/$79/$199) to reduce friction, or match it to position ourselves as a premium, essential add-on?** - -Bob: **Start 20-30% lower than Canny's pricing to minimize friction.** Our initial value proposition is "effortless integration," not yet "premium AI features." A lower price makes it an easy, no-brainer add-on for existing Canny customers. - -**Suggested MVP Tiers:** -- **Basic:** $29/month (for Canny Startup users, < 1k posts/month) -- **Pro:** $79/month (for Canny Growth users, < 5k posts/month) -- **Enterprise:** Custom pricing (for high-volume needs) - -**This incentivizes signups while leaving room for future price increases as we add AI summarization and other premium features.** The goal is traction first, premium positioning later. - -**Technical question: How should we enforce these post limits? Should we track post counts in our database or rely on Canny's webhook volume as a proxy?** - -Alice: **We MUST track post counts in our own database for accurate enforcement.** Relying solely on webhook volume is unreliable—webhooks can fail, be delayed, or be sent in duplicate. Our billing must be precise. - -**Implementation:** Add a `monthly_post_count` and `billing_cycle_start` column to the `customers` table. Our webhook handler increments the counter for each valid post. A cron job resets counts monthly. If a customer exceeds their limit, we can trigger an upgrade prompt or queue excess posts. - -**This adds a small operational burden but is essential for trustworthy billing.** It also gives us valuable data on customer usage patterns. - -**Next step: What's our most critical initial marketing channel? Should we focus on a Canny integration directory listing, targeted outreach to Canny's existing customer base, or content marketing aimed at product managers?** - -Bob: **The Canny integration directory is our highest-leverage initial channel.** It provides immediate, targeted visibility directly to our ideal customers who are actively looking for solutions like ours. It's free and builds instant credibility. - -**We should combine this with targeted outreach to Canny's *publicly listed* customers** (many companies showcase their Canny feedback boards). This creates a one-two punch: they see us in the directory, then get a personalized email. - -**Content marketing is a longer-term play; we need quick wins first.** Let's focus on the low-hanging fruit. - -**Pressing question: What single metric will define our MVP's success? Is it the number of active integrations, monthly recurring revenue, or perhaps the percentage of forwarded posts that generate a Slack reply (engagement)?** - -Alice: **Monthly recurring revenue (MRR) is the definitive success metric.** It directly measures our ability to solve a problem customers will pay for. Active integrations alone can be misleading (e.g., free users), and engagement metrics are secondary to monetization. - -**Our goal for Month 1 should be $500-$1000 MRR,** proving we've found a viable niche. This is aggressive but achievable if we convert just 10-20 Canny customers from our targeted outreach. - -**MRR also forces us to focus on the entire funnel—from signup to payment—not just technical implementation.** - -**Operational question: For our MVP, should we handle billing manually (invoicing via Stripe Invoice) or build automated subscription handling with Stripe Checkout?** The manual approach is faster to launch but doesn't scale. - -Bob: **Automate billing with Stripe Checkout from Day 1.** A manual process creates a scaling bottleneck and a poor user experience right when we need to validate the product. The time saved by manual invoicing is false economy. - -**The technical implementation is straightforward:** a `/subscribe` endpoint that creates a Stripe Checkout session. The webhook handler can then activate the service upon successful payment. This is a weekend project, not a major delay. - -**A seamless, self-serve signup is part of the "effortless" value proposition.** If the integration is automatic, the payment should be too. - -**Final pre-launch question: What is our single most important "success action" to track in the MVP? Is it the first Slack message delivered, or the user configuring the webhook in Canny?** This will define our core activation metric. - -Alice: "The **webhook configuration in Canny** is the critical success action. It's the moment the user actively completes the integration, proving they've invested time to make it work. The first Slack message is a passive outcome. - -**We should design our onboarding flow to explicitly guide the user to this step and confirm its completion.** This is our 'Aha!' moment. - -**Technical plan: After Stripe payment, redirect to a setup guide with explicit steps to copy our webhook URL into Canny. Our system can then verify the webhook is active.** - -**Let's draft the copy for that key setup guide page. What are the 3-4 bullet-point instructions that will make the process foolproof for a non-technical product manager?" - -Bob: **Here's the foolproof, 4-step guide for our setup page:** - -1. **Log in to your Canny dashboard,** navigate to **Settings > Integrations**. -2. Click **"Add Webhook"** and paste this unique URL: `[dynamic_webhook_url]` -3. **Check the boxes** for "New post created" and "New comment created" events. -4. Click **"Save"**. We'll send a test notification to your Slack channel to confirm it's working. - -**Crucially, we'll add a real-time status indicator:** "❌ Waiting for webhook connection..." that changes to "✅ Connected!" once we receive the first test event from Canny. This provides immediate, positive feedback. - -**This makes the technical process feel like a simple checklist.** The confirmation eliminates uncertainty. - -**Implementation question: Should the `dynamic_webhook_url` be unique per customer (e.g., `/webhook/:customer_id`) or should we use a single endpoint and validate via a secret token in the payload?** The token method is more secure but slightly more complex for the user to set up. - -Alice: **Use a single webhook endpoint (`/webhook`) with customer-specific token validation.** This is more secure by default and avoids exposing customer IDs in URLs. The minor setup complexity is worth the security gain. - -**Implementation:** Generate a unique token for each customer upon signup. The setup guide instructs them to add it as a "Secret Token" in Canny's webhook configuration. Our endpoint validates this token on every request. - -**We can mitigate complexity with clear UI:** The setup page prominently displays both the URL and the token, labeling them "Webhook URL" and "Secret Token" to match Canny's interface exactly. - -**This approach also simplifies our infrastructure with one endpoint.** - -**Final technical decision: What's our backup plan if Canny's API is down and we miss critical webhooks? Should we implement a retry queue, or is the occasional missed post an acceptable risk for the MVP?** - -Bob: **An immediate retry queue is non-negotiable for the MVP.** Missing a customer's feedback post is a critical failure of our core value proposition. It destroys trust immediately. - -**Implementation is simple and cheap:** Use a Redis queue (or even PostgreSQL with SKIP LOCKED) to store failed webhook delivery attempts. A background worker retries with exponential backoff. This is a basic reliability feature. - -**The cost of implementation is low, but the cost of failure is high.** We cannot label this as an "effortless" integration if it's unreliable. - -**Let's define the SLA: What is the maximum acceptable delay for a post to appear in Slack? Is 30 seconds reasonable, or should we aim for near real-time (<5 seconds) to feel instantaneous?** This will determine our retry logic urgency. - -Alice: **Aim for near real-time (<5 seconds) for the initial delivery attempt.** The perception of instant notification is core to the product experience. A 30-second delay feels like a broken system. - -**Our retry logic should be aggressive for the first hour:** retry immediately, then at 10 seconds, 30 seconds, and 1 minute. After that, we can shift to slower retries (5 min, 15 min) for persistent issues and alert ourselves. - -**Technical Plan:** Use a background job system (e.g., BullMQ for Node.js) with prioritized queues. The initial delivery job is high-priority; subsequent retries are lower priority. - -**To move forward: Let's write the pseudo-code for the core `/webhook` endpoint logic, including the token validation, Slack message formatting, and the retry queue entry point. This will force us to define the exact data flow.** - -Bob: **Excellent. Here's the pseudo-code for the core `/webhook` endpoint:** - -```javascript -// POST /webhook -1. Validate incoming 'X-Canny-Signature' header using customer's secret token. -2. If invalid, return 401. If valid, parse JSON body. -3. IMMEDIATELY add a high-priority job to BullMQ 'slack-delivery' queue. - - Job data: { customerId, cannyEvent (postCreated/commentCreated), payload } -4. Return 200 to Canny immediately. - -// BullMQ Worker: 'slack-delivery' -5. Worker receives job. Fetch customer's Slack webhook URL from DB. -6. Format Slack message block kit from cannyEvent data. -7. POST to Slack webhook URL. -8. If HTTP 200, job complete. -9. If HTTP failure (4xx/5xx), re-enqueue job with exponential backoff logic. - -``` - -**This flow ensures we acknowledge Canny instantly and handle the (potentially slower) Slack delivery asynchronously.** - -**The critical design choice is the message formatting. Should we create a rich, interactive Slack message with buttons to "View Post" and "Quick Reply," or a simple, static notification for the MVP?** Rich messages drive engagement but add complexity. - -Alice: **Rich, interactive messages are not just an enhancement—they are the core product differentiator.** A simple notification just recreates an email in Slack, which has minimal value. The "Quick Reply" button that pre-fills a Canny comment is the magic that turns Slack into an active feedback management tool. - -**MVP should absolutely include these actions.** The complexity is manageable: the buttons use Slack's `actions` block with a `url` to the pre-filled Canny comment page. This is a well-documented Slack API feature. - -**Technical Implementation:** We'll format the message using Slack's Block Kit. The "View Post" button links directly to the Canny post. The "Quick Reply" button links to `https://canny.io?comment=[post_id]` (or use Canny's documented deep-link format). - -**To validate this is the right priority: What's the ONE metric we should track to prove this interactivity drives value? Is it the click-through rate on the "Quick Reply" button, or should we measure the reduction in time-to-first-response for new posts?** - -Bob: **The reduction in time-to-first-response is the ultimate business metric.** It proves we're solving the core pain point of slow customer feedback loops. A button click rate is a proxy; the response time is the real value. - -**We can track this by logging the timestamp of the Canny webhook (post creation) and the timestamp of the first comment on that post.** Our system can correlate these events to generate a dashboard for customers, showing them the improvement our tool provides. - -**This also becomes a powerful feature: an "Analytics" tab showing "Average Response Time Before/After Installation."** - -**Pricing question: Should we price based on the number of Canny posts synced to Slack (usage-based) or a flat SaaS fee per workspace?** Usage-based aligns with value but adds complexity. A simple per-workspace fee is easier for an MVP. - -Alice: **Start with a simple flat fee per workspace—it's the right MVP choice.** We need to remove friction for our first customers and avoid the dreaded "metered bill" surprise. We can always introduce usage-based tiers later once we have data on what constitutes "heavy" usage. - -**Proposal: $29/month per connected Slack workspace, with a 14-day free trial.** This is a standard, defensible price for a productivity tool that saves teams time. It's simple to implement with Stripe. - -**This raises a key go-to-market question: Do we launch on the Slack App Directory from day one, or start with a direct sign-up flow on our own website?** The directory offers distribution but has a review process. A direct site gives us full control for initial iterations. - -Bob: **Direct sign-up on our own website is essential for the MVP.** It allows us to iterate rapidly based on early customer feedback without being bottlenecked by Slack's app review cycle. We can use Slack's OAuth API directly. - -**However, this creates a friction point: users must manually add the Slack app to their workspace *and* then sign up on our site. We should streamline this into a single, smooth OAuth flow that both installs the app and creates the user's account simultaneously.** - -**Technical Implementation:** The "Sign Up" button on our site will initiate Slack OAuth. Upon authorization, we receive the Slack workspace ID and user info, then automatically create a paid customer record in our database. - -**This leads to our first critical infrastructure decision: single-tenant vs. multi-tenant database? Should each customer have a dedicated database/queue, or do we use a shared PostgreSQL instance with strict row-level security?** Multi-tenant is faster to build but requires impeccable security from day one. - -Alice: **Multi-tenant with a shared PostgreSQL instance is the only practical choice for an MVP.** Single-tenant would be an operational nightmare for scaling. We can enforce security via a `tenant_id` on every table and use row-level security (RLS) policies. - -**Architecture:** -- **Database:** PostgreSQL with RLS. A `workspaces` table holds the Slack team ID and Stripe customer ID. -- **Queues:** A single BullMQ instance. Each job is tagged with the `tenant_id` (Slack team ID). -- **Security:** API endpoints and workers will filter all queries by the authenticated `tenant_id`. - -**This forces us to design our data isolation from day one. Let's define the core schema. What are the essential tables beyond `workspaces`? I propose: `canny_webhook_configs` (to store the customer's Canny board ID and secret) and `slack_delivery_logs` (for analytics and idempotency). What's missing?** - -Bob: **Excellent start. We must also add a `slack_webhook_configs` table to store the unique, per-channel Slack Incoming Webhook URL.** Customers will configure which specific channel (e.g., #customer-feedback) receives the notifications. This is crucial for routing. - -**Also, we need a `response_time_events` table to power the analytics dashboard.** It would store: `post_id`, `post_created_at`, `first_response_at`, and `tenant_id`. This is the core data for proving our value. - -**This schema covers the operational MVP. However, a critical operational risk is webhook sequence: if Canny sends a "comment created" event BEFORE the "post created" event arrives, our system could fail. Should we build idempotency logic to handle out-of-order events, or is the risk low enough for V1?** - -Alice: **The risk is too high for V1. If we log a "first response" for a post that doesn't exist in our system yet, our analytics will be broken and the value proposition is undermined.** - -**We must implement basic idempotency: when a "comment created" webhook arrives for an unknown `post_id`, we should store it in a `pending_comments` queue. When the corresponding "post created" event arrives, we process the comment and calculate the response time correctly.** - -**This adds complexity but is necessary for data integrity. We can implement this with a simple BullMQ delayed job that retries fetching the post for a short period before giving up.** - -**Given this added back-end complexity, should we delay building the real-time analytics dashboard for V1 and instead just expose the raw "Average Response Time" metric via a simple API call for a manually generated report? This defers the UI work but still provides the core metric.** - -Bob: **Absolutely. For V1, we should focus entirely on the core operational reliability—delivering notifications and correctly calculating the metric. The dashboard is a "nice to have" that can come after we prove the data pipeline is rock-solid.** - -**Our MVP deliverable becomes: a weekly email report to the workspace admin that shows the average response time metric, with a link to a simple, single-page dashboard that just displays the current number and a graph. This is minimal but still delivers the core insight.** - -**This shifts our immediate technical priority to email infrastructure and report generation. Do we use a transactional email service like Postmark or Resend for this, or is that overkill for a simple weekly cron job?** We could start by generating the report directly in our worker and sending via SMTP. - -Alice: **Resend is perfect—it's cheap, has a great API, and eliminates the deliverability headache of managing our own SMTP.** The cost is negligible for our scale, and it's one less infrastructure piece to worry about. We can trigger the weekly report via a BullMQ cron job that aggregates the `response_time_events` for each workspace. - -**However, this introduces a new user-facing question: Should we allow customers to configure the report frequency (e.g., daily, weekly, or real-time) from the start? Or is that a V2 feature?** Adding configuration now increases complexity, but a daily report might be a higher-value upsell. - -**Let's keep it simple: V1 is a fixed weekly report. We can A/B test the perceived value of daily reports later.** This keeps our initial scope tight. - -**Next critical decision: error handling. What's our plan for failed Slack webhook deliveries? Do we retry, and if so, how many times? Do we alert the admin?** - -Bob: **For failed Slack deliveries, we need a robust retry strategy. I propose: exponential backoff up to 3 attempts over 10 minutes.** If all retries fail, we log the error in `slack_delivery_logs` with a `failed` status. - -**We should NOT alert the admin for every failure—that's noise. Instead, we'll add a "Delivery Health" section to the weekly email report, showing the failure rate.** If the failure rate exceeds a threshold (e.g., 10%), we highlight it as a warning. - -**This balances system reliability with user experience. Now, a crucial monetization question: Should our pricing be per workspace or per Canny board? Many companies have multiple boards (e.g., for different products).** Per workspace is simpler, but per board could capture more value from larger customers. diff --git a/docs/WASM_BROWSER_DESIGN.md b/docs/WASM_BROWSER_DESIGN.md index 3f9973f..9c03ae4 100644 --- a/docs/WASM_BROWSER_DESIGN.md +++ b/docs/WASM_BROWSER_DESIGN.md @@ -120,15 +120,15 @@ The zig-p2p library currently targets native platforms (Linux, macOS, Windows) u ``` ┌─────────────────────────────────────────────────────────────────┐ -│ Application Layer │ -│ (examples/, user code) │ +│ Application Layer │ +│ (examples/, user code) │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ -│ P2P Layer │ +│ P2P Layer │ │ (src/p2p/*.zig) │ -│ Lifecycle, Config, Stats, Types │ +│ Lifecycle, Config, Stats, Types │ └─────────────────────────────────────────────────────────────────┘ │ ┌───────────────┼───────────────┐ @@ -146,7 +146,7 @@ The zig-p2p library currently targets native platforms (Linux, macOS, Windows) u │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────────────┐ -│ Core Layer │ +│ Core Layer │ │ (src/core/*.zig) │ │ Socket, Address, Buffer, Limits, RateLimiter, Error │ └─────────────────────────────────────────────────────────────────┘ @@ -251,24 +251,24 @@ posix.mmap() // Memory mapping (not in WASM) ``` ┌─────────────────────────────────────────────────────────────────┐ -│ Platform-Agnostic Code │ -│ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Noise │ │ Protocol │ │ DHT │ │ Piece │ │ -│ │ Protocol │ │ Messages │ │ Routing │ │ Selector │ │ -│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ -│ │ +│ Platform-Agnostic Code │ +│ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ Noise │ │ Protocol │ │ DHT │ │ Piece │ │ +│ │ Protocol │ │ Messages │ │ Routing │ │ Selector │ │ +│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ -│ Abstraction Interfaces │ -│ │ -│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ -│ │ Transport │ │ FileSystem │ │ Scheduler │ │ -│ │ Interface │ │ Interface │ │ Interface │ │ -│ └──────────────┘ └──────────────┘ └──────────────┘ │ -│ │ +│ Abstraction Interfaces │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Transport │ │ FileSystem │ │ Scheduler │ │ +│ │ Interface │ │ Interface │ │ Interface │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +│ │ └─────────────────────────────────────────────────────────────────┘ │ ┌───────────────┴───────────────┐ @@ -277,15 +277,15 @@ posix.mmap() // Memory mapping (not in WASM) ┌─────────────────────────┐ ┌─────────────────────────┐ │ Native Platform │ │ WASM Platform │ │ │ │ │ -│ ┌─────────────────┐ │ │ ┌─────────────────┐ │ -│ │ POSIXTransport │ │ │ │ WebRTCTransport │ │ -│ └─────────────────┘ │ │ └─────────────────┘ │ -│ ┌─────────────────┐ │ │ ┌─────────────────┐ │ -│ │ NativeFS │ │ │ │ IndexedDBFS │ │ -│ └─────────────────┘ │ │ └─────────────────┘ │ -│ ┌─────────────────┐ │ │ ┌─────────────────┐ │ -│ │ ThreadPool │ │ │ │ EventQueue │ │ -│ └─────────────────┘ │ │ └─────────────────┘ │ +│ ┌─────────────────┐ │ │ ┌─────────────────┐ │ +│ │ POSIXTransport │ │ │ │ WebRTCTransport │ │ +│ └─────────────────┘ │ │ └─────────────────┘ │ +│ ┌─────────────────┐ │ │ ┌─────────────────┐ │ +│ │ NativeFS │ │ │ │ IndexedDBFS │ │ +│ └─────────────────┘ │ │ └─────────────────┘ │ +│ ┌─────────────────┐ │ │ ┌─────────────────┐ │ +│ │ ThreadPool │ │ │ │ EventQueue │ │ +│ └─────────────────┘ │ │ └─────────────────┘ │ │ │ │ │ └─────────────────────────┘ └─────────────────────────┘ ``` @@ -661,22 +661,22 @@ pub const WebRTCTransport = struct { ``` ┌─────────────────────────────────────────────────────────────────┐ -│ Browser A │ -│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ -│ │ WASM P2P │◄──►│ JS Glue │◄──►│ WebRTC │ │ -│ │ Library │ │ Layer │ │ DataChannel │ │ -│ └─────────────┘ └─────────────┘ └──────┬──────┘ │ -└──────────────────────────────────────────────│─────────────────┘ - │ - │ P2P (after signaling) - │ -┌──────────────────────────────────────────────│─────────────────┐ -│ Browser B │ │ -│ ┌─────────────┐ ┌─────────────┐ ┌────▼────────┐ │ +│ Browser A │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +│ │ WASM P2P │◄──►│ JS Glue │◄──►│ WebRTC │ │ +│ │ Library │ │ Layer │ │ DataChannel │ │ +│ └─────────────┘ └─────────────┘ └──────┬──────┘ │ +└───────────────────────────────────────────────│─────────────────┘ + │ + │ P2P (after signaling) + │ +┌───────────────────────────────────────────────│────────────────┐ +│ Browser B │ │ +│ ┌─────────────┐ ┌─────────────┐ ┌──────▼──────┐ │ │ │ WASM P2P │◄──►│ JS Glue │◄──►│ WebRTC │ │ │ │ Library │ │ Layer │ │ DataChannel │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ +└────────────────────────────────────────────────────────────────┘ ▲ │ Signaling (one-time) ▼ @@ -690,6 +690,8 @@ pub const WebRTCTransport = struct { WebRTC requires a signaling server to exchange connection metadata (SDP offers/answers and ICE candidates). Once connected, communication is peer-to-peer. +> **Note (Feb 2026):** For native↔native connections, MWP (Mutual Witness Protocol) now provides infrastructure-free peer discovery and hole punching via DHT. For browser↔anything connections, WebRTC signaling is still required because browsers cannot use raw UDP. However, the DHT could serve as the signaling transport — native peers already connected via MWP could relay SDP offers/answers for browser peers through the DHT, potentially eliminating the need for a separate WebSocket signaling server. + #### 6.2.1 Signaling Message Types ```typescript @@ -2173,12 +2175,13 @@ test('two peers can exchange messages', async ({ browser }) => { ### 13.4 Performance Benchmarks -| Metric | Target (Native) | Target (WASM) | -|--------|-----------------|---------------| -| Connection setup | <50ms | <200ms | +| Metric | Measured (Native) | Target (WASM) | +|--------|-------------------|---------------| +| Multi-peer throughput | 497 MB/s (10 peers, localhost) | 10+ MB/s | +| Swarm throughput | 130 MB/s (9 peers, 25GB) | 5+ MB/s | +| Connection setup | <50ms (UDP), ~200ms est. (WebRTC) | <500ms | | Message latency | <5ms | <20ms | -| Throughput | 100+ MB/s | 10+ MB/s | -| Memory per conn | 64KB | 128KB | +| Memory per conn | ~131KB (Noise buffers) | ~131KB | --- @@ -2320,248 +2323,821 @@ The additional effort (4-6 weeks) is justified by the significant increase in ut --- -## 16. Native WebRTC Implementation +## 16. Native WebRTC via libdatachannel C Bindings -### 16.1 WebRTC Protocol Stack +### 16.1 Strategy: Use C Bindings, Don't Reimplement -WebRTC Data Channels require implementing multiple complex protocols: +**Decision (Feb 2026): Bind to libdatachannel's C API via Zig's `@cImport`.** + +WebRTC Data Channels require SCTP (~30K lines), DTLS (~10K lines), ICE (~5K lines), and SDP parsing. Reimplementing this is 6-10 months of work with high risk of subtle protocol bugs. Instead, we use libdatachannel — a lightweight, actively maintained C++ library with a clean C API — and call it directly from Zig. ``` -┌─────────────────────────────────────────┐ -│ Data Channel (DCEP) │ Simple message framing -├─────────────────────────────────────────┤ -│ SCTP │ Reliable streams over UDP -├─────────────────────────────────────────┤ (congestion control, ordering) -│ DTLS 1.2/1.3 │ TLS over UDP -├─────────────────────────────────────────┤ (encryption, authentication) -│ ICE + STUN + TURN │ NAT traversal -├─────────────────────────────────────────┤ (connectivity establishment) -│ UDP │ ← Already implemented -└─────────────────────────────────────────┘ +┌─────────────────────────────────────────────────────────────┐ +│ zig-p2p Application │ +├─────────────────────────────────────────────────────────────┤ +│ Transport Abstraction (Section 5) │ +│ ┌──────────────────┐ ┌──────────────────┐ │ +│ │ POSIXTransport │ │ WebRTCTransport │ │ +│ │ (native↔native) │ │ (native↔browser) │ │ +│ │ UDP/TCP sockets │ │ @cImport rtc.h │ │ +│ └──────────────────┘ └────────┬─────────┘ │ +├──────────────────────────────────────┼──────────────────────┤ +│ Zig C Interop │ │ +│ @cImport("rtc/rtc.h") │ │ +├──────────────────────────────────────┼──────────────────────┤ +│ libdatachannel │ │ +│ ┌──────────┬──────────┬──────────┘ │ +│ │ libjuice │ usrsctp │ GnuTLS/mbedTLS │ +│ │ (ICE) │ (SCTP) │ (DTLS) │ +│ └──────────┴──────────┴─────────────────────────────────┤ +│ UDP Socket (already in zig-p2p) │ +└─────────────────────────────────────────────────────────────┘ ``` -### 16.2 Component Complexity Analysis +### 16.2 Why libdatachannel -| Component | Purpose | Complexity | Est. Lines | From-Scratch Time | -|-----------|---------|------------|------------|-------------------| -| **SCTP** | Reliable data streams, congestion control | Very High | 8,000-15,000 | 2-3 months | -| **DTLS 1.2** | TLS handshake over UDP | High | 5,000-10,000 | 1-2 months | -| **ICE** | NAT traversal, connectivity checks | High | 3,000-5,000 | 3-4 weeks | -| **STUN** | Public IP discovery | Medium | 1,000-2,000 | 1-2 weeks | -| **TURN** | Relay fallback | Medium | 2,000-3,000 | 2-3 weeks | -| **SDP** | Session description parsing | Medium | 1,000-2,000 | 1 week | -| **DCEP** | Data channel setup | Low | ~500 | 2-3 days | +| Criteria | libdatachannel | Alternatives | +|----------|---------------|-------------| +| **Language** | C++ with clean C API (`rtc.h`) | Pion (Go, can't link), webrtc-rs (Rust, complex ABI) | +| **Scope** | DataChannels only (what we need) | Google's libwebrtc includes media (~10MB) | +| **Size** | ~15K-20K lines, ~200KB binary | libwebrtc: millions of lines, ~10MB | +| **Dependencies** | libjuice + usrsctp + TLS lib | Self-contained with sub-libraries | +| **TLS Backend** | Choice: GnuTLS, mbedTLS, or OpenSSL | Most lock you into OpenSSL | +| **License** | MPL 2.0 (permissive, compatible) | Varies | +| **C API** | Complete, stable, callback-based | Most require C++ or FFI wrappers | +| **Platforms** | Linux, macOS, Windows, Android, iOS, FreeBSD | Good cross-platform | +| **Maintenance** | Active (Paul-Louis Ageneau) | Varies | +| **Zig interop** | `@cImport` works directly | Rust/Go require complex bridging | -### 16.3 The Hard Parts +### 16.3 libdatachannel C API Surface (What We Actually Use) -#### SCTP (Hardest) +The full API has ~80 functions but we only need the DataChannel subset: -- Must run in userspace over DTLS (not kernel SCTP) -- Complex congestion control algorithms -- Partial reliability extensions for WebRTC -- Multi-stream multiplexing -- Reference: usrsctp is ~30,000 lines of C +#### 16.3.1 Lifecycle -#### DTLS +```c +// Global init/cleanup (call once) +void rtcPreload(void); // Optional preload +void rtcCleanup(void); // Cleanup at shutdown +void rtcInitLogger(rtcLogLevel level, rtcLogCallbackFunc cb); // Wire to core.log -- Full TLS 1.2 handshake adapted for unreliable UDP -- Retransmission, fragmentation, reordering of handshake messages -- Must integrate with ICE (consent freshness checks) -- Certificate handling and cipher suite negotiation +// PeerConnection lifecycle +int rtcCreatePeerConnection(const rtcConfiguration *config); // Returns pc ID +int rtcClosePeerConnection(int pc); +int rtcDeletePeerConnection(int pc); -#### ICE Timing +// DataChannel lifecycle +int rtcCreateDataChannel(int pc, const char *label); // Returns dc ID +int rtcCreateDataChannelEx(int pc, const char *label, const rtcDataChannelInit *init); +int rtcDeleteDataChannel(int dc); +int rtcClose(int id); // Close any channel/track/ws +int rtcDelete(int id); // Delete any channel/track/ws +``` -- Consent freshness requires STUN keepalives every few seconds -- Browser will close connection if consent expires -- Tight integration between ICE and DTLS layers required +#### 16.3.2 Signaling (SDP/ICE Exchange) -### 16.4 Reference Implementation Sizes +```c +// SDP exchange +int rtcSetLocalDescription(int pc, const char *type); // "offer" or "answer" +int rtcSetRemoteDescription(int pc, const char *sdp, const char *type); +int rtcGetLocalDescription(int pc, char *buffer, int size); // Get generated SDP +int rtcGetRemoteDescription(int pc, char *buffer, int size); -| Project | Language | Scope | Approx Size | Notes | -|---------|----------|-------|-------------|-------| -| **Pion** | Go | Full WebRTC | ~50,000+ lines | Multiple repos | -| **libdatachannel** | C++ | Data channels | ~15,000-20,000 lines | Lightweight | -| **webrtc-rs** | Rust | Full WebRTC | ~40,000+ lines | Feature-rich | -| **usrsctp** | C | SCTP only | ~30,000 lines | Used by Chrome | -| **libjuice** | C | ICE only | ~5,000 lines | Same author as libdatachannel | +// ICE candidates +int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid); +int rtcGetLocalAddress(int pc, char *buffer, int size); +int rtcGetRemoteAddress(int pc, char *buffer, int size); +``` -### 16.5 Implementation Options +#### 16.3.3 Data Transfer -#### Option 1: Bind to libdatachannel (Recommended) +```c +// Send/receive +int rtcSendMessage(int id, const char *data, int size); // Returns bytes or error +int rtcReceiveMessage(int id, char *buffer, int *size); // Non-blocking receive -**Effort:** 4-6 weeks +// State query +bool rtcIsOpen(int id); +bool rtcIsClosed(int id); +int rtcMaxMessageSize(int id); +int rtcGetBufferedAmount(int id); +int rtcGetAvailableAmount(int id); +``` + +#### 16.3.4 Callbacks (Critical for Zig Integration) + +```c +// User data pointer (how we pass Zig context to C callbacks) +void rtcSetUserPointer(int id, void *ptr); +void *rtcGetUserPointer(int id); + +// Connection state callbacks +int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc cb); +int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb); +int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb); +int rtcSetIceStateChangeCallback(int pc, rtcIceStateChangeCallbackFunc cb); +int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb); + +// DataChannel callbacks +int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb); +int rtcSetOpenCallback(int id, rtcOpenCallbackFunc cb); +int rtcSetClosedCallback(int id, rtcClosedCallbackFunc cb); +int rtcSetErrorCallback(int id, rtcErrorCallbackFunc cb); +int rtcSetMessageCallback(int id, rtcMessageCallbackFunc cb); + +// Flow control +int rtcSetBufferedAmountLowThreshold(int id, int amount); +int rtcSetBufferedAmountLowCallback(int id, rtcBufferedAmountLowCallbackFunc cb); +int rtcSetAvailableCallback(int id, rtcAvailableCallbackFunc cb); +``` + +#### 16.3.5 Configuration Structures + +```c +typedef struct { + const char **iceServers; // STUN/TURN server URLs + int iceServersCount; + const char *proxyServer; // Optional SOCKS5 proxy + const char *bindAddress; // Local bind address + rtcCertificateType certificateType; // Default, ECDSA, or RSA + rtcTransportPolicy iceTransportPolicy; // All or Relay + bool enableIceTcp; // ICE over TCP + bool enableIceUdpMux; // Multiplex ICE on single port + bool disableAutoNegotiation; // Manual SDP control + bool forceMediaTransport; // Force DTLS even without media + uint16_t portRangeBegin; // Port range for allocation + uint16_t portRangeEnd; + int mtu; // Max transmission unit + int maxMessageSize; // Max DataChannel message size +} rtcConfiguration; + +typedef struct { + bool unordered; // false = TCP-like, true = UDP-like + bool unreliable; // false = reliable, true = unreliable + unsigned int maxPacketLifeTime; // Max ms for retransmit (if unreliable) + unsigned int maxRetransmits; // Max retransmit count (if unreliable) +} rtcReliability; + +typedef struct { + rtcReliability reliability; + const char *protocol; // Sub-protocol + bool negotiated; // Pre-negotiated channel + bool manualStream; // Manual stream ID assignment + uint16_t stream; // Stream ID (if manual) +} rtcDataChannelInit; +``` + +### 16.4 Zig Binding Implementation + +#### 16.4.1 C Import and Type Mapping + +**File:** `src/platform/webrtc_native.zig` ```zig -// Zig bindings for libdatachannel C API +const std = @import("std"); +const Transport = @import("../core/transport.zig").Transport; + const rtc = @cImport({ @cInclude("rtc/rtc.h"); }); -pub const WebRTCTransport = struct { - peer_connection: rtc.rtcPeerConnection, - data_channel: rtc.rtcDataChannel, +/// Maps libdatachannel integer IDs to Zig-managed state. +/// libdatachannel uses integer handles (like file descriptors) for +/// PeerConnections and DataChannels. We track them in a HashMap. +const ChannelState = struct { + dc_id: c_int, // libdatachannel DataChannel ID + pc_id: c_int, // libdatachannel PeerConnection ID + state: Transport.State, + recv_queue: std.fifo.LinearFifo(u8, .Dynamic), // Incoming data buffer + allocator: std.mem.Allocator, - pub fn connect(self: *WebRTCTransport, remote_sdp: []const u8) !void { - rtc.rtcSetRemoteDescription(self.peer_connection, remote_sdp.ptr); + // Signaling data (captured by callbacks, consumed by poll loop) + local_sdp: ?[]const u8 = null, + local_candidates: std.ArrayList([]const u8), + gathering_complete: bool = false, +}; +``` + +#### 16.4.2 Callback Bridge (C → Zig) + +The trickiest part: libdatachannel callbacks are C function pointers with a `void *ptr` user data. We use `rtcSetUserPointer` to stash a pointer to our Zig struct, then recover it in each callback. + +```zig +/// Called by libdatachannel when local SDP description is generated. +/// This is a C-ABI callback — must be `callconv(.c)`. +fn onLocalDescription(pc: c_int, sdp: [*c]const u8, sdp_type: [*c]const u8, ptr: ?*anyopaque) callconv(.c) void { + _ = sdp_type; + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + + // Copy SDP into Zig-managed memory (libdatachannel frees its copy after callback returns) + const sdp_slice = std.mem.span(sdp); + state.local_sdp = state.allocator.dupe(u8, sdp_slice) catch return; +} + +/// Called when a local ICE candidate is generated. +fn onLocalCandidate(pc: c_int, cand: [*c]const u8, mid: [*c]const u8, ptr: ?*anyopaque) callconv(.c) void { + _ = mid; + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + + const cand_slice = std.mem.span(cand); + const duped = state.allocator.dupe(u8, cand_slice) catch return; + state.local_candidates.append(duped) catch { + state.allocator.free(duped); + }; +} + +/// Called when PeerConnection state changes. +fn onStateChange(pc: c_int, rtc_state: rtc.rtcState, ptr: ?*anyopaque) callconv(.c) void { + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + state.state = switch (rtc_state) { + rtc.RTC_NEW, rtc.RTC_CONNECTING => .connecting, + rtc.RTC_CONNECTED => .connected, + rtc.RTC_DISCONNECTED, rtc.RTC_CLOSED => .disconnected, + rtc.RTC_FAILED => .failed, + else => .failed, + }; +} + +/// Called when ICE gathering state changes. +fn onGatheringStateChange(pc: c_int, rtc_state: rtc.rtcGatheringState, ptr: ?*anyopaque) callconv(.c) void { + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + if (rtc_state == rtc.RTC_GATHERING_COMPLETE) { + state.gathering_complete = true; + } +} + +/// Called when a DataChannel message arrives. +fn onMessage(id: c_int, message: [*c]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void { + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + if (size < 0) return; // size < 0 means string message (not binary) + + const data = message[0..@intCast(size)]; + state.recv_queue.write(data) catch return; // Drop if buffer full +} + +/// Called when DataChannel opens. +fn onOpen(id: c_int, ptr: ?*anyopaque) callconv(.c) void { + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + state.state = .connected; +} + +/// Called when DataChannel closes. +fn onClosed(id: c_int, ptr: ?*anyopaque) callconv(.c) void { + const state: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + state.state = .disconnected; +} +``` + +#### 16.4.3 WebRTCTransport (Native) — Full Implementation + +```zig +pub const NativeWebRTCTransport = struct { + channels: std.AutoHashMap(u32, *ChannelState), + allocator: std.mem.Allocator, + next_id: u32 = 1, + ice_servers: []const []const u8, + + pub fn init(allocator: std.mem.Allocator, ice_servers: []const []const u8) NativeWebRTCTransport { + // Initialize libdatachannel (once, globally) + rtc.rtcInitLogger(rtc.RTC_LOG_WARNING, logCallback); + + return .{ + .channels = std.AutoHashMap(u32, *ChannelState).init(allocator), + .allocator = allocator, + .ice_servers = ice_servers, + }; } - pub fn send(self: *WebRTCTransport, data: []const u8) !usize { - return rtc.rtcSendMessage(self.data_channel, data.ptr, data.len); + pub fn deinit(self: *NativeWebRTCTransport) void { + var it = self.channels.valueIterator(); + while (it.next()) |state_ptr| { + const state = state_ptr.*; + rtc.rtcDeleteDataChannel(state.dc_id); + rtc.rtcDeletePeerConnection(state.pc_id); + state.recv_queue.deinit(); + state.local_candidates.deinit(); + if (state.local_sdp) |sdp| self.allocator.free(sdp); + self.allocator.destroy(state); + } + self.channels.deinit(); + rtc.rtcCleanup(); + } + + /// Create an outbound WebRTC connection (as offerer). + /// Returns a channel ID. The caller must exchange SDP/ICE via signaling. + pub fn createOffer(self: *NativeWebRTCTransport) !struct { channel_id: u32, state: *ChannelState } { + // Build config with ICE servers + var ice_server_ptrs: [8][*c]const u8 = undefined; + const count = @min(self.ice_servers.len, 8); + for (0..count) |i| { + ice_server_ptrs[i] = self.ice_servers[i].ptr; + } + + var config = std.mem.zeroes(rtc.rtcConfiguration); + config.iceServers = &ice_server_ptrs; + config.iceServersCount = @intCast(count); + + // Create PeerConnection + const pc = rtc.rtcCreatePeerConnection(&config); + if (pc < 0) return error.TransportError; + + // Allocate Zig state + const state = try self.allocator.create(ChannelState); + state.* = .{ + .dc_id = -1, + .pc_id = pc, + .state = .connecting, + .recv_queue = std.fifo.LinearFifo(u8, .Dynamic).init(self.allocator), + .allocator = self.allocator, + .local_candidates = std.ArrayList([]const u8).init(self.allocator), + }; + + // Wire callbacks with user pointer + rtc.rtcSetUserPointer(pc, state); + _ = rtc.rtcSetLocalDescriptionCallback(pc, onLocalDescription); + _ = rtc.rtcSetLocalCandidateCallback(pc, onLocalCandidate); + _ = rtc.rtcSetStateChangeCallback(pc, onStateChange); + _ = rtc.rtcSetGatheringStateChangeCallback(pc, onGatheringStateChange); + + // Create DataChannel (triggers SDP offer generation) + const dc_init = rtc.rtcDataChannelInit{ + .reliability = .{ + .unordered = false, // Reliable, ordered (TCP-like) + .unreliable = false, + .maxPacketLifeTime = 0, + .maxRetransmits = 0, + }, + .protocol = "zig-p2p", + .negotiated = false, + .manualStream = false, + .stream = 0, + }; + + const dc = rtc.rtcCreateDataChannelEx(pc, "p2p-data", &dc_init); + if (dc < 0) { + rtc.rtcDeletePeerConnection(pc); + self.allocator.destroy(state); + return error.TransportError; + } + state.dc_id = dc; + + // Wire DataChannel callbacks + rtc.rtcSetUserPointer(dc, state); + _ = rtc.rtcSetOpenCallback(dc, onOpen); + _ = rtc.rtcSetClosedCallback(dc, onClosed); + _ = rtc.rtcSetMessageCallback(dc, onMessage); + + const channel_id = self.next_id; + self.next_id += 1; + try self.channels.put(channel_id, state); + + return .{ .channel_id = channel_id, .state = state }; + } + + /// Accept an inbound WebRTC connection (as answerer). + /// Called when we receive an SDP offer via signaling. + pub fn acceptOffer(self: *NativeWebRTCTransport, remote_sdp: []const u8) !struct { channel_id: u32, state: *ChannelState } { + var config = std.mem.zeroes(rtc.rtcConfiguration); + // ... (same ICE server setup as createOffer) + + const pc = rtc.rtcCreatePeerConnection(&config); + if (pc < 0) return error.TransportError; + + const state = try self.allocator.create(ChannelState); + state.* = .{ + .dc_id = -1, + .pc_id = pc, + .state = .connecting, + .recv_queue = std.fifo.LinearFifo(u8, .Dynamic).init(self.allocator), + .allocator = self.allocator, + .local_candidates = std.ArrayList([]const u8).init(self.allocator), + }; + + rtc.rtcSetUserPointer(pc, state); + _ = rtc.rtcSetLocalDescriptionCallback(pc, onLocalDescription); + _ = rtc.rtcSetLocalCandidateCallback(pc, onLocalCandidate); + _ = rtc.rtcSetStateChangeCallback(pc, onStateChange); + _ = rtc.rtcSetGatheringStateChangeCallback(pc, onGatheringStateChange); + + // Callback to capture incoming DataChannel from remote + _ = rtc.rtcSetDataChannelCallback(pc, struct { + fn callback(pc_id: c_int, dc: c_int, ptr: ?*anyopaque) callconv(.c) void { + const s: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + s.dc_id = dc; + rtc.rtcSetUserPointer(dc, s); + _ = rtc.rtcSetOpenCallback(dc, onOpen); + _ = rtc.rtcSetClosedCallback(dc, onClosed); + _ = rtc.rtcSetMessageCallback(dc, onMessage); + } + }.callback); + + // Apply remote offer (triggers answer generation) + const sdp_z = try self.allocator.dupeZ(u8, remote_sdp); + defer self.allocator.free(sdp_z); + if (rtc.rtcSetRemoteDescription(pc, sdp_z.ptr, "offer") < 0) { + rtc.rtcDeletePeerConnection(pc); + self.allocator.destroy(state); + return error.TransportError; + } + + const channel_id = self.next_id; + self.next_id += 1; + try self.channels.put(channel_id, state); + + return .{ .channel_id = channel_id, .state = state }; + } + + /// Add remote ICE candidate (received via signaling). + pub fn addRemoteCandidate(self: *NativeWebRTCTransport, channel_id: u32, candidate: []const u8) !void { + const state = self.channels.get(channel_id) orelse return error.InvalidState; + const cand_z = try self.allocator.dupeZ(u8, candidate); + defer self.allocator.free(cand_z); + _ = rtc.rtcAddRemoteCandidate(state.pc_id, cand_z.ptr, "0"); + } + + /// Conform to Transport interface — send data on DataChannel. + pub fn send(self: *NativeWebRTCTransport, channel_id: u32, data: []const u8) Transport.Error!usize { + const state = self.channels.get(channel_id) orelse return error.InvalidState; + if (state.state != .connected) return error.InvalidState; + + const result = rtc.rtcSendMessage(state.dc_id, data.ptr, @intCast(data.len)); + if (result < 0) { + return switch (result) { + -1 => error.ConnectionClosed, + else => error.TransportError, + }; + } + return data.len; + } + + /// Conform to Transport interface — receive data from DataChannel. + pub fn receive(self: *NativeWebRTCTransport, channel_id: u32, buffer: []u8) Transport.Error!usize { + const state = self.channels.get(channel_id) orelse return error.InvalidState; + const n = state.recv_queue.read(buffer); + if (n == 0) return error.WouldBlock; + return n; + } + + /// Get local SDP (after offer/answer generation). + pub fn getLocalSdp(self: *NativeWebRTCTransport, channel_id: u32) ?[]const u8 { + const state = self.channels.get(channel_id) orelse return null; + return state.local_sdp; + } + + /// Get pending local ICE candidates. + pub fn drainLocalCandidates(self: *NativeWebRTCTransport, channel_id: u32) ?[][]const u8 { + const state = self.channels.get(channel_id) orelse return null; + if (state.local_candidates.items.len == 0) return null; + const items = state.local_candidates.toOwnedSlice() catch return null; + return items; + } + + fn logCallback(level: rtc.rtcLogLevel, message: [*c]const u8) callconv(.c) void { + const msg = std.mem.span(message); + switch (level) { + rtc.RTC_LOG_ERROR => core.log.err("{s}", .{msg}), + rtc.RTC_LOG_WARNING => core.log.warn("{s}", .{msg}), + rtc.RTC_LOG_INFO => core.log.info("{s}", .{msg}), + else => core.log.debug("{s}", .{msg}), + } } }; ``` -**Pros:** -- Mature, tested implementation -- Small footprint (~200KB binary increase) -- C API is clean for Zig interop -- Maintained by active developer -- MPL 2.0 license +### 16.5 Signaling via DHT (No Separate Server) -**Cons:** -- External C++ dependency -- Requires OpenSSL/GnuTLS/mbedTLS for crypto +**Key insight:** We already have a DHT with `dhtStore`/`dhtFindValue`. We can use it as the signaling transport for WebRTC, eliminating the need for a separate WebSocket signaling server. -**Timeline:** -| Task | Duration | -|------|----------| -| Build system integration | 3 days | -| Zig C bindings | 1 week | -| Transport implementation | 1 week | -| WebRTC Direct protocol | 1 week | -| Integration & testing | 1-2 weeks | -| **Total** | **4-6 weeks** | +#### 16.5.1 Signaling Flow Using DHT -#### Option 2: Port libjuice to Zig + Bind usrsctp +``` +Native Peer (Alice) DHT Network Browser Peer (Bob) + │ │ │ + │ 1. dhtStore(meeting_point, │ │ + │ {type:"offer", sdp:...}) │ │ + │───────────────────────────────────►│ │ + │ │ │ + │ │ 2. dhtFindValue(meeting_point) │ + │ │◄────────────────────────────────│ + │ │ │ + │ │ 3. Return offer │ + │ │────────────────────────────────►│ + │ │ │ + │ │ 4. dhtStore(meeting_point, │ + │ │ {type:"answer", sdp:...}) │ + │ │◄────────────────────────────────│ + │ │ │ + │ 5. dhtFindValue(meeting_point) │ │ + │───────────────────────────────────►│ │ + │ │ │ + │ 6. Return answer │ │ + │◄───────────────────────────────────│ │ + │ │ │ + │ 7. WebRTC DataChannel established (P2P direct) │ + │◄────────────────────────────────────────────────────────────────────►│ +``` -**Effort:** 4-6 months +#### 16.5.2 Meeting Point Computation -Port the ICE layer (libjuice) to pure Zig, bind usrsctp for SCTP: +Reuse the same MWP meeting point derivation — deterministic from both peers' public keys: ```zig -// Pure Zig ICE implementation (ported from libjuice) -pub const IceAgent = struct { - local_candidates: std.ArrayList(Candidate), - remote_candidates: std.ArrayList(Candidate), - selected_pair: ?CandidatePair, - - pub fn gatherCandidates(self: *IceAgent) !void { - // STUN binding requests to discover public IP - try self.gatherHostCandidates(); - try self.gatherServerReflexiveCandidates(); +/// Compute DHT key for WebRTC signaling between two peers. +/// Same as MWP: SHA-256(sorted(pubkey_a, pubkey_b)). +fn computeSignalingKey(pubkey_a: [32]u8, pubkey_b: [32]u8) [32]u8 { + var hasher = std.crypto.hash.sha2.Sha256.init(.{}); + // Sort keys for order-independence + if (std.mem.order(u8, &pubkey_a, &pubkey_b) == .lt) { + hasher.update(&pubkey_a); + hasher.update(&pubkey_b); + } else { + hasher.update(&pubkey_b); + hasher.update(&pubkey_a); } + return hasher.finalResult(); +} +``` + +#### 16.5.3 Signaling Message Format + +```zig +const SignalingMessage = struct { + msg_type: enum { offer, answer, ice_candidate }, + from_pubkey: [32]u8, + sdp: ?[]const u8, // For offer/answer + candidate: ?[]const u8, // For ICE candidate + timestamp: i64, + signature: [64]u8, // Ed25519 signature over message }; ``` -**Pros:** -- Partial pure Zig (ICE layer) -- Good learning experience -- More control over ICE behavior +This approach means: +- **No WebSocket signaling server needed** +- SDP exchange happens through the same DHT used for peer discovery +- ICE candidates trickle through DHT publications +- MWP meeting point computation is reused +- Ed25519 signatures prevent spoofing -**Cons:** -- Still depends on usrsctp (C) -- DTLS still needs external library -- Significant effort for marginal benefit +#### 16.5.4 Fallback: WebSocket Signaling Server -#### Option 3: Full From-Scratch Implementation +For environments where DHT is unavailable (e.g., first browser peer with no native bootstrap): -**Effort:** 6-10 months (1 person full-time) +```javascript +// Minimal signaling server — ~30 lines +const WebSocket = require('ws'); +const wss = new WebSocket.Server({ port: 8080 }); +const peers = new Map(); -Write everything in pure Zig: +wss.on('connection', (ws) => { + ws.on('message', (data) => { + const msg = JSON.parse(data); + if (msg.type === 'register') { + peers.set(msg.peerId, ws); + ws.peerId = msg.peerId; + } else if (msg.to && peers.has(msg.to)) { + msg.from = ws.peerId; + peers.get(msg.to).send(JSON.stringify(msg)); + } + }); + ws.on('close', () => { if (ws.peerId) peers.delete(ws.peerId); }); +}); +``` -| Component | Lines | Time | -|-----------|-------|------| -| SCTP | 8,000-15,000 | 2-3 months | -| DTLS 1.2 | 5,000-10,000 | 1-2 months | -| ICE | 3,000-5,000 | 1 month | -| STUN | 1,000-2,000 | 2 weeks | -| TURN | 2,000-3,000 | 2-3 weeks | -| SDP parsing | 1,000-2,000 | 1 week | -| Integration | - | 1-2 months | -| **Total** | **25,000-40,000** | **6-10 months** | +### 16.6 Build System Integration -**Pros:** -- Zero external dependencies -- Full control -- Smallest binary size -- Great for Zig ecosystem - -**Cons:** -- Massive undertaking -- High risk of subtle protocol bugs -- SCTP congestion control is notoriously complex -- Only viable with dedicated funding - -### 16.6 Comparison Table - -| Approach | Time | Pure Zig | Dependencies | Binary Size | Risk | -|----------|------|----------|--------------|-------------|------| -| Bind libdatachannel | 4-6 weeks | 80% | libdatachannel, TLS lib | +200KB | Low | -| Port libjuice + bind | 4-6 months | 60% | usrsctp, TLS lib | +150KB | Medium | -| Full from-scratch | 6-10 months | 100% | None | +100KB | High | - -### 16.7 Recommendation - -**Phase 1: Bind libdatachannel** (4-6 weeks) -- Achieves interoperability quickly -- Proven, tested implementation -- Can always replace later with pure Zig - -**Phase 2 (Future, Optional): Pure Zig Implementation** -- Only if there's strong community demand -- Could be a separate project (zig-webrtc) -- Start with ICE (port libjuice), then tackle SCTP - -### 16.8 libdatachannel Integration Details - -#### Build System +#### 16.6.1 Option A: System Library (Simplest) ```zig -// build.zig additions -const libdatachannel = b.dependency("libdatachannel", .{ +// build.zig — link against system-installed libdatachannel +if (options.enable_webrtc) { + exe.linkSystemLibrary("datachannel"); + exe.linkLibC(); + exe.addIncludePath(.{ .cwd_relative = "/usr/local/include" }); // or pkg-config +} +``` + +Install on macOS: `brew install libdatachannel` +Install on Linux: `apt install libdatachannel-dev` or build from source. + +#### 16.6.2 Option B: Vendored Build (Recommended for Reproducibility) + +```zig +// build.zig — build libdatachannel from source as a Zig build step +const webrtc_dep = b.dependency("libdatachannel", .{ .target = target, .optimize = optimize, }); -exe.linkLibrary(libdatachannel.artifact("datachannel")); -exe.linkSystemLibrary("ssl"); -exe.linkSystemLibrary("crypto"); +// libdatachannel's build.zig.zon would wrap its CMake build +exe.linkLibrary(webrtc_dep.artifact("datachannel")); +exe.linkLibC(); ``` -#### Package Manager (build.zig.zon) - ```zig +// build.zig.zon .dependencies = .{ .libdatachannel = .{ - .url = "https://github.com/user/libdatachannel-zig/archive/v0.1.0.tar.gz", + .url = "https://github.com/user/libdatachannel-zig-pkg/archive/v0.21.0.tar.gz", .hash = "...", }, }, ``` -#### API Mapping +#### 16.6.3 Option C: Compile C Sources Directly (Most Control) -| libdatachannel C API | zig-p2p Transport API | -|---------------------|----------------------| -| `rtcCreatePeerConnection()` | `WebRTCTransport.init()` | -| `rtcSetRemoteDescription()` | `WebRTCTransport.connect()` | -| `rtcSendMessage()` | `Transport.send()` | -| `rtcReceiveMessage()` | `Transport.receive()` | -| `rtcClose()` | `Transport.close()` | -| `rtcGetState()` | `Transport.getState()` | +Since libdatachannel uses CMake, we'd create a Zig build wrapper: -### 16.9 Updated Project Timeline +```zig +// build.zig — compile libdatachannel C/C++ sources directly +const libdc = b.addStaticLibrary(.{ + .name = "datachannel", + .target = target, + .optimize = optimize, +}); + +// Add libjuice sources (ICE) +libdc.addCSourceFiles(.{ + .root = b.path("deps/libjuice/src"), + .files = &.{ "agent.c", "conn.c", "ice.c", "stun.c", "turn.c", "udp.c", ... }, + .flags = &.{ "-std=c11", "-DJUICE_STATIC" }, +}); + +// Add usrsctp sources (SCTP) +libdc.addCSourceFiles(.{ + .root = b.path("deps/usrsctp/usrsctplib"), + .files = &.{ "netinet/sctp_asconf.c", "netinet/sctp_auth.c", ... }, + .flags = &.{ "-std=c11", "-DSCTP_SIMPLE_ALLOCATOR" }, +}); + +// Add libdatachannel C++ sources +libdc.addCSourceFiles(.{ + .root = b.path("deps/libdatachannel/src"), + .files = &.{ "peerconnection.cpp", "datachannel.cpp", "capi.cpp", ... }, + .flags = &.{ "-std=c++17", "-fno-exceptions" }, +}); + +// Link TLS backend +if (target.os_tag == .macos) { + libdc.linkFramework("Security"); // Use Apple's TLS +} else { + libdc.linkSystemLibrary("gnutls"); // Or mbedtls +} + +exe.linkLibrary(libdc); +``` + +**Recommendation:** Start with Option A (system library) for development, move to Option C for release builds. + +#### 16.6.4 Conditional Compilation + +```zig +// src/platform/native.zig +const builtin = @import("builtin"); + +pub const Transport = @import("../core/transport.zig").Transport; + +pub const has_webrtc = @hasDecl(@This(), "webrtc_native"); + +// Only import WebRTC when built with -Denable-webrtc=true +pub const webrtc_native = if (builtin.os.tag != .freestanding) + @import("webrtc_native.zig") +else + void; +``` + +```zig +// P2P config +pub const P2PConfig = struct { + // ... existing fields ... + transports: struct { + udp: bool = true, // Native-to-native (default) + tcp: bool = true, // Native-to-native + webrtc: bool = false, // For browser interop (opt-in) + } = .{}, +}; +``` + +### 16.7 Security: Noise Over WebRTC DataChannel + +WebRTC already provides DTLS encryption, but we layer Noise on top for two reasons: +1. **Uniform identity model**: Same Ed25519 keys authenticate all connections (UDP and WebRTC) +2. **Wire envelope compatibility**: Same replay protection applies to all transports + +``` +┌──────────────────────────────────────────┐ +│ zig-p2p wire envelope │ Same format for all transports +│ [app_id][salt][timestamp][payload] │ +├──────────────────────────────────────────┤ +│ Noise_XX encryption │ Same Ed25519 identity keys +├──────────────────────────────────────────┤ +│ WebRTC DataChannel (SCTP) │ Reliable delivery +├──────────────────────────────────────────┤ +│ DTLS 1.2 (libdatachannel) │ Transport encryption (redundant but free) +├──────────────────────────────────────────┤ +│ ICE + STUN (libjuice) │ NAT traversal +├──────────────────────────────────────────┤ +│ UDP │ +└──────────────────────────────────────────┘ +``` + +The Noise layer runs identically whether the underlying transport is UDP socket or WebRTC DataChannel — this is the whole point of the Transport abstraction in Section 5. + +### 16.8 Implementation Plan + +#### Phase 5a: Build System + Raw Bindings (3 days) + +| Task | Details | +|------|---------| +| Install libdatachannel | Homebrew/apt, verify C headers accessible | +| Create `src/platform/webrtc_native.zig` | `@cImport("rtc/rtc.h")`, verify types compile | +| Add build flag | `-Denable-webrtc=true` conditional in build.zig | +| Smoke test | Call `rtcPreload()` + `rtcCleanup()` from Zig, verify linking | + +**Deliverable:** `zig build -Denable-webrtc=true` compiles and links. + +#### Phase 5b: Callback Bridge + Transport Impl (1 week) + +| Task | Details | +|------|---------| +| Implement C→Zig callbacks | All 8 callbacks with `callconv(.c)` and user pointer recovery | +| Implement `NativeWebRTCTransport` | `createOffer()`, `acceptOffer()`, `send()`, `receive()` | +| Unit test: loopback | Two `NativeWebRTCTransport` instances, exchange SDP in-memory, send/receive data | +| Conform to Transport vtable | Wire into existing `Transport` interface from Section 5 | + +**Deliverable:** Two native peers connect via WebRTC DataChannel on localhost. + +#### Phase 5c: Signaling via DHT (1 week) + +| Task | Details | +|------|---------| +| Define `SignalingMessage` format | Serialization, Ed25519 signing | +| Implement DHT-based signaling | `dhtStore`/`dhtFindValue` for SDP exchange | +| Reuse MWP meeting point | Same `computeSignalingKey()` derivation | +| ICE candidate trickle via DHT | Periodic `dhtStore` of new candidates | +| Integration test | Native peer creates offer, stores in DHT, second peer finds and answers | + +**Deliverable:** Two native peers establish WebRTC connection using DHT for signaling. + +#### Phase 5d: Browser↔Native Testing (1 week) + +| Task | Details | +|------|---------| +| WASM peer creates offer via JS WebRTC | Browser-side, existing code from Section 6 | +| Native peer accepts via libdatachannel | Cross-transport connection | +| Noise handshake over DataChannel | Verify same identity/auth as UDP connections | +| File transfer over WebRTC | Piece-based transfer works through DataChannel | +| Fallback WebSocket signaling | For first-boot browser with no DHT peers | + +**Deliverable:** Browser tab connects to native peer and transfers a file. + +#### Phase 5e: Integration + Polish (1 week) + +| Task | Details | +|------|---------| +| Auto-transport selection | Native-to-native: UDP. Native-to-browser: WebRTC. | +| Connection upgrade | If peer supports both, prefer UDP | +| Error handling | Timeouts, ICE failures, TURN fallback | +| Memory cleanup | Verify no leaks (libdatachannel cleanup + Zig dealloc) | +| CI: add `-Denable-webrtc` build | Ensure it doesn't break non-WebRTC builds | + +**Deliverable:** Production-ready WebRTC transport, opt-in via build flag. + +### 16.9 What We Don't Need From libdatachannel + +The library has ~80 C API functions. We use ~25 of them. Explicitly excluded: + +| Feature | Why Skip | +|---------|---------| +| Media tracks (`rtcAddTrack`, packetizers) | No audio/video streaming — data channels only | +| WebSocket client/server (`rtcCreateWebSocket`) | We have our own signaling via DHT | +| SCTP settings tuning (`rtcSetSctpSettings`) | Defaults are fine for data channels | +| Track interceptors, RTP timestamps | Media-only features | + +This keeps the integration surface small and the mental model simple. + +### 16.10 Risk Assessment + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| libdatachannel C API breaks between versions | Low | Medium | Pin to specific release, vendored build | +| Callback threading: libdatachannel calls from internal thread | Medium | High | Callbacks push to thread-safe queue, consumed in `update()` | +| TLS library conflicts with Zig's stdlib crypto | Low | Low | libdatachannel TLS is isolated to DTLS layer | +| Binary size increase | Low | Low | ~200KB — acceptable | +| Build complexity on CI | Medium | Medium | Start with system library, document install steps | + +### 16.11 Updated Timeline Summary | Phase | Duration | Cumulative | |-------|----------|------------| | 1. Transport Abstraction | 2 weeks | 2 weeks | | 2. Event-Driven I/O | 1.5 weeks | 3.5 weeks | -| 3. WASM WebRTC Transport | 1.5 weeks | 5 weeks | +| 3. WASM WebRTC Transport (browser) | 1.5 weeks | 5 weeks | | 4. File System & Threading | 1 week | 6 weeks | -| **5. Native WebRTC (libdatachannel)** | **4 weeks** | **10 weeks** | +| **5. Native WebRTC (libdatachannel C bindings)** | **4 weeks** | **10 weeks** | | 6. Integration & Polish | 2 weeks | 12 weeks | **Total with full interoperability: 10-12 weeks** +**Browser-only (no native↔browser): 6 weeks** --- @@ -2628,7 +3204,7 @@ With native WebRTC implemented, all platforms can communicate: │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ │ - UDP (Native-to-Native, fastest) + UDP (Native-to-Native, fastest) ``` ### 17.4 Communication Paths @@ -2756,8 +3332,8 @@ sudo systemctl start zig-p2p | Resource | zig-p2p Requirement | Typical IoT Device | |----------|--------------------|--------------------| -| RAM | ~64KB per connection | 256MB-1GB | -| Storage | ~2MB binary | 4GB+ SD card | +| RAM | ~131KB per connection | 256MB-1GB | +| Storage | ~5MB binary | 4GB+ SD card | | CPU | Single core OK | ARM Cortex-A | | Network | UDP/WebRTC | WiFi/Ethernet | @@ -2799,10 +3375,10 @@ const config = P2PConfig{ For bare-metal microcontrollers, the recommended pattern is: ``` -┌─────────────┐ Serial/BLE ┌─────────────┐ P2P ┌─────────────┐ +┌─────────────┐ Serial/BLE ┌──────────────┐ P2P ┌─────────────┐ │ ESP32 │◄────────────────────────►│ RPi Gateway │◄────────────────►│ Cloud │ │ (sensors) │ │ (zig-p2p) │ │ (zig-p2p) │ -└─────────────┘ └─────────────┘ └─────────────┘ +└─────────────┘ └──────────────┘ └─────────────┘ ``` ### 17.8 Build System Integration @@ -2990,7 +3566,7 @@ wss.on('connection', (ws) => { --- -*Document version: 1.2* +*Document version: 1.3* *Last updated: February 2026* ### Revision History @@ -3000,3 +3576,4 @@ wss.on('connection', (ws) => { | 1.0 | Feb 2025 | Initial design document | | 1.1 | Feb 2025 | Added native-browser interoperability analysis (Sections 15-16), WebRTC implementation options, updated timeline | | 1.2 | Feb 2026 | Added Mobile and IoT platform support (Section 17), universal interoperability matrix, build system integration for cross-platform targets | +| 1.3 | Feb 2026 | Major Section 16 rewrite: detailed libdatachannel C binding plan with full API surface, Zig callback bridge implementation, DHT-based signaling (no separate server), build system options, Noise-over-WebRTC security model. Updated benchmarks with measured values. Fixed memory per connection (64KB → 131KB). Added MWP note to signaling section. | diff --git a/docs/WASM_IMPLEMENTATION_TASKS.md b/docs/WASM_IMPLEMENTATION_TASKS.md new file mode 100644 index 0000000..50ed9b8 --- /dev/null +++ b/docs/WASM_IMPLEMENTATION_TASKS.md @@ -0,0 +1,603 @@ +# WASM/Browser + Native WebRTC — Detailed Task List + +**80 tasks across 6 phases, ~234 hours estimated** + +--- + +## Phase 0: Preparation and Audit (4 tasks, ~7h) + +### T0.1 — Create `src/platform/` directory (1h) +- Create empty `src/platform/` directory for platform-specific code +- No build changes yet + +### T0.2 — Audit every Socket access point (2h) +- Read-only audit of all files importing `core.Socket` +- Produce reference table: every call to send, sendTo, receive, receiveFrom, bind, listen, accept, connect, close, poll, setNonBlocking with file:line +- **Output**: Reference document for Transport interface design +- Files: `src/core/socket.zig`, `src/network/network_manager.zig`, `src/network/secure_connection.zig`, `src/network/upnp.zig`, `src/network/nat_pmp.zig`, `src/network/discovery.zig`, `src/network/nat.zig`, `src/network/turn_integration.zig`, `src/mwp/hole_punch.zig`, `src/p2p/connection.zig`, `src/p2p/messaging.zig` + +### T0.3 — Audit Mutex usage and threading model (2h) +- Classify each of the 835 Mutex occurrences into: + - (a) Protects truly concurrent multi-thread access (e.g., worker thread + update loop) + - (b) Single-threaded access only (artifact of lock ordering discipline) + - (c) Within spawned worker threads (handler.zig, verification_pool.zig) +- Identify which 4 files spawn threads: `nat.zig`, `handler.zig`, `request_tracker.zig`, `verification_pool.zig` + +### T0.4 — Audit random and time usage (1.5h) +- Document all `std.crypto.random.bytes()` sites (18 files, 30+ calls) +- Document all `std.time.milliTimestamp()`, `timestamp()`, `nanoTimestamp()` sites (50+ files) +- Identify hot-path vs initialization-only usage +- Check if Zig's std.crypto/std.time has WASM support via WASI + +--- + +## Phase 1: Transport Abstraction (16 tasks, ~48h) + +### T1.1 — Define Transport interface (3h) +- **Create**: `src/core/transport.zig` +- Define `Transport` struct with vtable: `send`, `receive`, `close`, `canSend`, `canReceive`, `getRemoteId`, `getState` +- Define `TransportError` error set +- Include datagram methods: `sendTo(data, address)`, `receiveFrom(buffer) -> {size, address}` +- Unit test with mock vtable dispatch +- **Decision**: Single interface with mode flag (stream + datagram), not two separate interfaces. Unsupported ops return `OperationNotSupported`. +- **Depends on**: T0.1, T0.2 + +### T1.2 — Define TransportFactory interface (2h) +- **Modify**: `src/core/transport.zig` +- Add `TransportFactory` with vtable: `connect(address, callback)`, `listen(address, callback)`, `stopListening()`, `poll(timeout_ms)` +- Factory creates Transport instances +- **Depends on**: T1.1 + +### T1.3 — Implement PosixStreamTransport (4h) +- **Create**: `src/platform/posix_transport.zig` +- Wraps existing `Socket` for TCP (not replacing Socket, wrapping it) +- Implements Transport vtable: send → socket.send, receive → socket.receive, etc. +- `canSend`/`canReceive` use `posix.poll()` with 0ms timeout +- Unit test: create, send data through loopback, receive +- **Depends on**: T1.1, T1.2 + +### T1.4 — Implement PosixDatagramTransport (3h) +- **Modify**: `src/platform/posix_transport.zig` +- Add datagram variant: `sendTo` → socket.sendTo, `receiveFrom` → socket.receiveFrom +- Critical for DHT and discovery (UDP) +- Unit test: two UDP sockets exchanging packets +- **Depends on**: T1.3 + +### T1.5 — Implement MockTransport (2h) +- **Create**: `src/platform/mock_transport.zig` +- In-memory transport with configurable delays, errors, queued data +- Mirrors existing MockSocket pattern in socket.zig (line 1025+) +- Both stream and datagram modes +- **Depends on**: T1.1 + +### T1.6 — Export Transport types from core module (1h) +- **Modify**: `src/core.zig` +- Add `pub const transport = @import("core/transport.zig")` +- Re-export: Transport, TransportFactory, TransportError, TransportState +- **Depends on**: T1.1 + +### T1.7 — Add transport module to build.zig (1h) +- **Modify**: `build.zig` +- Add `src/platform/` files to appropriate module +- Add `const is_wasm = target.cpu_arch == .wasm32;` for conditional compilation +- Verify `zig build` succeeds and runs transport unit tests +- **Depends on**: T1.3, T1.4, T1.5, T1.6 + +### T1.8 — Refactor PeerConnection: `*Socket` → `Transport` (4h) ⚠️ HIGH RISK +- **Modify**: `src/network/network_manager.zig` (PeerConnection struct, ~line 136) +- Change `PeerConnection.socket: *Socket` to `PeerConnection.transport: Transport` +- Update `init()`, `initSecure()`, all methods accessing `self.socket` +- Add backward-compatible factory: `PeerConnection.initFromSocket()` wraps Socket in PosixStreamTransport +- Must preserve atomic send semantics and PendingSend/EncryptedQueueEntry patterns +- **ALL existing tests must pass unchanged** +- **Depends on**: T1.3, T1.7 +- **Risk**: Most invasive change — touches sendToPeerAtomicImpl, drainPendingSendsImpl, processReceive, processSendQueue + +### T1.9 — Refactor SecureConnection to use Transport (4h) +- **Modify**: `src/network/secure_connection.zig` (447 lines) +- Change `SecureConnection.socket: *Socket` → accept Transport +- Update `sendRaw()` (line 379) and `receiveRaw()` (line 401) to use transport.send/receive +- Blocking retry loops with Thread.sleep remain for now (Phase 2 fixes these) +- Update sendEncrypted/receiveDecrypted +- **Depends on**: T1.8 + +### T1.10 — Refactor NetworkManager receive path (3h) +- **Modify**: `src/network/network_manager.zig` — `processReceive()` (~line 971) +- Read from PeerConnection.transport instead of Socket directly +- Pattern: iterate peer_connections, check transport.canReceive(), call transport.receive() +- **Depends on**: T1.8 + +### T1.11 — Refactor NetworkManager send path (3h) +- **Modify**: `src/network/network_manager.zig` — `sendMessage()`, `processSendQueue()` +- **Modify**: `src/p2p/connection.zig` — `sendToPeerAtomicImpl()`, `sendSegmentsToPeerAtomicImpl()`, `drainPendingSendsImpl()` +- Replace peer_conn.socket.send() with peer_conn.transport.send() +- WouldBlock handling unchanged — just goes through Transport +- **Depends on**: T1.8, T1.10 + +### T1.12 — Refactor connection establishment to use TransportFactory (4h) +- **Modify**: `src/p2p/connection.zig` — `connectToPeerImpl()`, `attemptConnectionInternalImpl()`, `acceptConnectionsImpl()` +- New flow: TransportFactory.connect() → Transport → PeerConnection +- For accept: TransportFactory.listen() callback yields new Transports +- PosixTransportFactory wraps existing Socket creation +- **Depends on**: T1.2, T1.8, T1.11 + +### T1.13 — Refactor discovery module to use Transport (3h) +- **Modify**: `src/network/discovery.zig` +- Uses Socket/MockSocket directly (line 12). Change to DatagramTransport. +- Broadcast/multicast → DatagramTransport.sendTo() +- Receive → DatagramTransport.receiveFrom() +- **Depends on**: T1.4 + +### T1.14 — Refactor NAT module to use Transport (3h) +- **Modify**: `src/network/nat.zig` +- Already generic over Socket/MockSocket (lines 36-37). Change to DatagramTransport. +- STUN message exchange through Transport +- Hole punch UDP send/receive through Transport +- Thread.spawn for hole punching remains for now (Phase 2) +- **Depends on**: T1.4 + +### T1.15 — Refactor DHT coordinator to use Transport (3h) +- **Modify**: `src/network/dht.zig`, `src/p2p/dht.zig` +- DHT messages flow through P2P send path (already through NetworkManager) +- Ensure DHT-specific send/receive routes through Transport +- Remove any direct Socket references +- **Depends on**: T1.11 + +### T1.16 — Phase 1 full regression test (4h) +- Run `zig build test`, `zig build test-integration` +- Fix any failures from Transport refactoring +- Run performance benchmarks — no regression +- Verify TestP2PPair still works (real TCP on localhost) +- **Depends on**: T1.8 through T1.15 +- **Gate**: MUST pass before Phase 2 + +--- + +## Phase 2: Event-Driven I/O (13 tasks, ~37h) + +### T2.1 — Implement EventQueue (3h) +- **Create**: `src/platform/event_queue.zig` +- Events: transport_readable, transport_writable, transport_state, timer, file_io_complete +- Methods: push(), processAll(), processN(), registerHandler() +- Optional for native (poll-based loop works). Required for WASM. +- **Depends on**: T1.7 + +### T2.2 — Implement platform-aware Mutex (2h) +- **Create**: `src/platform/sync.zig` +- `pub const Mutex = if (builtin.target.isWasm()) WasmMutex else std.Thread.Mutex;` +- WasmMutex: no-op with debug recursive lock detection +- **Depends on**: T0.3 + +### T2.3 — Implement platform-aware time abstraction (2h) +- **Create**: `src/platform/time.zig` +- `milliTimestamp()`: std.time.milliTimestamp() on native, js_timestamp_ms() on WASM +- Same for timestamp(), nanoTimestamp() +- **Depends on**: T0.4 + +### T2.4 — Implement platform-aware random abstraction (2h) +- **Create**: `src/platform/random.zig` +- `bytes(buf)`: std.crypto.random.bytes() on native, js_random_bytes() on WASM (crypto.getRandomValues) +- **Depends on**: T0.4 + +### T2.5 — Non-blocking Noise handshake (4h) ⚠️ HIGH RISK +- **Modify**: `src/network/secure_connection.zig` — sendRaw() (line 379), receiveRaw() (line 401) +- Replace blocking retry loops with state machine: `HandshakeState { .sending_msg1, .awaiting_msg2, .sending_msg3, .complete }` +- Each call to `advanceHandshake()` does non-blocking I/O, returns `.progress` or `.would_block` +- Caller (connection.zig) calls from update loop +- Must buffer partial sends/receives +- **Depends on**: T1.9 +- **Risk**: Noise XX expects complete messages from writeMessage/readMessage + +### T2.6 — Non-blocking connection establishment (4h) +- **Modify**: `src/p2p/connection.zig` — attemptConnectionInternalImpl() +- Multi-step state: Connecting → HandshakeMsg1 → HandshakeMsg2 → HandshakeMsg3 → Connected +- Pending connections stored in list, advanced each update cycle +- **Depends on**: T2.5 + +### T2.7 — Remove Thread.sleep from network_manager, dht, discovery (3h) +- **Modify**: `src/network/network_manager.zig`, `src/network/dht.zig`, `src/network/discovery.zig` +- Replace sleep with timestamp-based retry (store retry-at, check in update loop) +- **Depends on**: T2.3 + +### T2.8 — Remove Thread.sleep from MWP modules (2h) +- **Modify**: `src/mwp_integration.zig`, `src/mwp/meeting_point.zig`, `src/mwp/hole_punch.zig` +- Hole punch resend (500ms) → timestamp check in update loop instead of sleep +- **Depends on**: T2.3 + +### T2.9 — Remove Thread.sleep from file transfer (2h) +- **Modify**: `src/files/manager.zig`, `src/files/piece_pipeline.zig`, `src/files/verification_pool.zig` +- Replace blocking sleeps with cooperative patterns +- Thread spawning handled separately in T2.11 +- **Depends on**: T2.3 + +### T2.10 — Replace Thread.spawn in protocol handler with TaskQueue (4h) +- **Create**: `src/platform/task_queue.zig` +- **Modify**: `src/protocol/handler.zig` +- Implement cooperative TaskQueue (design doc Section 9.3) +- Comptime switch: `if (builtin.target.isWasm()) task_queue.schedule(...) else Thread.spawn(...)` +- **Depends on**: T2.2 + +### T2.11 — Replace Thread.spawn in verification_pool (3h) +- **Modify**: `src/files/verification_pool.zig` +- WASM: chunked single-threaded SHA-256 verification (process N bytes per update, yield) +- Native: keep existing thread pool +- Comptime switch +- **Depends on**: T2.10 + +### T2.12 — Replace Thread.spawn in NAT and request_tracker (2h) +- **Modify**: `src/network/nat.zig`, `src/protocol/request_tracker.zig` +- Hole punching → update-loop-driven (check timer, send packet, return) +- Request tracker cleanup → update-loop-driven +- **Depends on**: T2.10 + +### T2.13 — Phase 2 full regression test (3h) +- All tests pass +- Verify: no Thread.sleep or Thread.spawn in WASM code paths (grep) +- **Depends on**: T2.5 through T2.12 +- **Gate**: MUST pass before Phase 3 + +--- + +## Phase 3: WASM WebRTC Transport — Browser Side (8 tasks, ~24h) + +### T3.1 — Create WASM entry point and exports (3h) +- **Create**: `src/wasm/main.zig`, `src/wasm/exports.zig` +- Exports: p2p_init, p2p_connect, p2p_send, wasm_tick, alloc, free, on_timer, on_data_available, on_channel_closed +- `zig build -Dtarget=wasm32-freestanding` produces .wasm +- **Depends on**: T2.2, T2.3, T2.4 + +### T3.2 — Implement WebRTCTransport for WASM (Zig side) (3h) +- **Create**: `src/platform/webrtc_wasm_transport.zig` +- Transport vtable backed by `extern "webrtc"` imports (js_send, js_recv, js_close, etc.) +- Channel-ID based +- **Depends on**: T1.1 + +### T3.3 — Create JS WebRTC glue layer (4h) +- **Create**: `wasm/js/webrtc-transport.js` +- WebRTCTransportManager class: RTCPeerConnection + RTCDataChannel management +- Provides WASM imports (js_send, js_recv, etc.) +- Handles connection setup, ICE, data channel lifecycle +- **Depends on**: T3.2 + +### T3.4 — Implement signaling protocol (3h) +- **Create**: `wasm/js/signaling.js`, `tools/signaling-server.js` +- Simple WebSocket signaling (~50 lines Node.js) +- Message types: register, offer, answer, ice-candidate +- **Depends on**: T3.3 + +### T3.5 — Create main JS API (3h) +- **Create**: `wasm/js/zig-p2p.js` +- ZigP2P class: init(), connect(), send(), onMessage(), onPeerConnected() +- WASM loading, memory management, event loop (requestAnimationFrame → wasm_tick) +- **Depends on**: T3.1, T3.3, T3.4 + +### T3.6 — Build system WASM target (3h) +- **Modify**: `build.zig` +- Add `wasm` step: wasm32-freestanding target, export symbols, disable entry, copy JS files +- `zig build wasm` produces `zig-out/wasm/zig-p2p.wasm` + JS files +- Native build unaffected +- **Depends on**: T3.1, T3.2 + +### T3.7 — Browser demo page (2h) +- **Create**: `wasm/demo/index.html`, `wasm/demo/demo.js` +- Load zig-p2p WASM, connect to signaling server, show peers, send messages +- **Depends on**: T3.5, T3.6 + +### T3.8 — Browser-to-browser integration test (3h) +- **Create**: `tests/browser/test_browser_p2p.js` (Playwright) +- Two browser contexts: init P2P, connect, exchange encrypted messages +- `npx playwright test` +- **Depends on**: T3.7 + +--- + +## Phase 4: File System and Threading Adaptation (7 tasks, ~17h) + +### T4.1 — Define FileSystem interface (2h) +- **Create**: `src/platform/filesystem_interface.zig` +- Vtable: open, read, write, close, stat, delete +- Replaces `use_mock_fs` compile-time flag with runtime dispatch +- **Depends on**: T1.1 + +### T4.2 — Implement NativeFileSystem (2h) +- **Create**: `src/platform/native_fs.zig` +- Wraps std.fs.File operations +- **Depends on**: T4.1 + +### T4.3 — Implement IndexedDB FileSystem (3h) +- **Create**: `src/platform/indexeddb_fs.zig`, `wasm/js/indexeddb-fs.js` +- Zig: vtable backed by extern "indexeddb" imports +- JS: IndexedDBFileSystem class with blob storage +- **Depends on**: T4.1 + +### T4.4 — Refactor files module to use FileSystem interface (4h) +- **Modify**: `src/files/filesystem.zig`, `src/files/manager.zig`, `src/files/download.zig`, `src/files/upload.zig` +- Replace use_mock_fs with runtime FileSystem +- FileSharingManager receives FileSystem in config +- **Depends on**: T4.2 + +### T4.5 — Refactor crypto key persistence (2h) +- **Modify**: `src/protocol/crypto.zig`, `src/network/key_pinning.zig` +- These use std.fs directly. Accept FileSystem in config. +- WASM: keys go to IndexedDB. Native: keys go to disk. +- **Depends on**: T4.1 + +### T4.6 — Create platform module aggregator (2h) +- **Create**: `src/platform/native.zig`, `src/platform/wasm.zig` +- Each exports platform-specific implementations +- `pub const platform = if (builtin.target.isWasm()) @import("platform/wasm.zig") else @import("platform/native.zig");` +- **Depends on**: T2.2, T4.2, T4.3 + +### T4.7 — Phase 4 regression test (2h) +- All native tests pass +- WASM builds compile +- File transfer works with NativeFS and MockFS +- **Depends on**: T4.1 through T4.6 + +--- + +## Phase 5: Native WebRTC via libdatachannel C Bindings (23 tasks, ~71h) + +### T5.1 — Install libdatachannel and verify headers (2h) +- System install: `brew install libdatachannel` (macOS) or build from source +- Verify `rtc/rtc.h` accessible +- Document version + install instructions in `docs/WEBRTC_BUILD.md` +- Pin to specific version (e.g., 0.21.x) + +### T5.2 — Create @cImport wrapper and type mappings (3h) +- **Create**: `src/platform/webrtc_native.zig` +- `const rtc = @cImport({ @cInclude("rtc/rtc.h"); });` +- Zig type aliases for C types: RtcConfiguration, RtcDataChannelInit, RtcReliability +- Map rtcState enum → Transport.State +- Verify: rtc.rtcPreload() + rtc.rtcCleanup() callable from Zig +- **Depends on**: T5.1 + +### T5.3 — Add `-Denable-webrtc` build option (2h) +- **Modify**: `build.zig` +- `b.option(bool, "enable-webrtc", "Enable native WebRTC transport via libdatachannel")` +- When true: linkSystemLibrary("datachannel"), linkLibC(), add include path +- When false: no WebRTC code compiled or linked +- **Depends on**: T5.2 + +### T5.4 — Smoke test: lifecycle (1.5h) +- **Create**: `tests/integration/test_webrtc_smoke.zig` +- Call rtcPreload(), create PeerConnection, close, delete, rtcCleanup() +- Verify no crashes, no leaks (TrackingAllocator) +- **Depends on**: T5.3 + +### T5.5 — Implement C→Zig callback bridge (4h) ⚠️ HIGH RISK +- **Modify**: `src/platform/webrtc_native.zig` +- 8 `callconv(.c)` callbacks: onLocalDescription, onLocalCandidate, onStateChange, onGatheringStateChange, onMessage, onOpen, onClosed, onError +- Each recovers ChannelState via rtcGetUserPointer, updates state or queues data +- **CRITICAL**: libdatachannel calls from internal thread → must be thread-safe +- Push to lock-free queue or use atomic state flags consumed by update loop +- **Depends on**: T5.2 + +### T5.6 — Implement thread-safe ChannelState (3h) +- **Modify**: `src/platform/webrtc_native.zig` +- `state: std.atomic.Value(Transport.State)` — lock-free state reads +- `recv_queue` — mutex-protected FIFO (SPSC: libdatachannel thread writes, update loop reads) +- `local_sdp`, `local_candidates`, `gathering_complete` — atomic or mutex-protected +- Concurrent read/write test from two threads +- **Depends on**: T5.5 + +### T5.7 — Implement createOffer() (4h) +- **Modify**: `src/platform/webrtc_native.zig` +- Build rtcConfiguration with ICE servers +- rtcCreatePeerConnection → allocate ChannelState → wire callbacks via rtcSetUserPointer +- rtcCreateDataChannelEx (reliable, ordered, protocol "zig-p2p") +- Wire DataChannel callbacks (open, closed, message) +- Return {channel_id, state}. Caller polls state.local_sdp for generated offer. +- Test: createOffer(), wait for local_sdp != null, verify SDP contains "v=0" +- **Depends on**: T5.6 + +### T5.8 — Implement acceptOffer() (3h) +- **Modify**: `src/platform/webrtc_native.zig` +- Create PeerConnection, set remote description (triggers answer generation) +- Wire DataChannel callback for incoming channel from remote +- Test: createOffer on A → pass SDP to acceptOffer on B → verify answer SDP +- **Depends on**: T5.7 + +### T5.9 — Implement send/receive/close (3h) +- **Modify**: `src/platform/webrtc_native.zig` +- send() → rtcSendMessage(dc_id, data.ptr, data.len) +- receive() → read from ChannelState.recv_queue +- close() → rtcClose, rtcDeleteDataChannel, rtcDeletePeerConnection +- canSend() → check rtcGetBufferedAmount < threshold +- canReceive() → check recv_queue non-empty +- **Depends on**: T5.7, T5.8 + +### T5.10 — Implement ICE candidate exchange (2h) +- **Modify**: `src/platform/webrtc_native.zig` +- addRemoteCandidate(channel_id, candidate) → rtcAddRemoteCandidate(pc_id, cand, "0") +- drainLocalCandidates(channel_id) → return accumulated local candidates, clear list +- getLocalSdp(channel_id) → return SDP +- Test: two NativeWebRTCTransport exchanging SDP/ICE in-memory +- **Depends on**: T5.9 + +### T5.11 — Loopback integration test: two native WebRTC peers (4h) +- **Create**: `tests/integration/test_webrtc_loopback.zig` +- Two NativeWebRTCTransport instances +- A creates offer, B accepts, exchange ICE in-memory +- Wait for DataChannel open +- Send "hello world" A→B, verify. Send response B→A, verify. +- Test reliable and unreliable channel configs +- **Depends on**: T5.10 +- **Risk**: ICE may fail in loopback. Use 127.0.0.1 bind, may need STUN disabled. + +### T5.12 — Conform to Transport vtable (3h) +- **Modify**: `src/platform/webrtc_native.zig` +- Create `WebRTCChannelTransport` wrapper: holds ref to NativeWebRTCTransport + channel_id +- Implements Transport vtable (send → self.manager.send(self.channel_id, data), etc.) +- Interchangeable with PosixStreamTransport in PeerConnection +- **Depends on**: T5.9, T1.1 + +### T5.13 — Implement SignalingMessage serialization (3h) +- **Create**: `src/platform/webrtc_signaling.zig` +- SignalingMessage: msg_type (offer/answer/ice_candidate), from_pubkey, sdp/candidate, timestamp, Ed25519 signature +- serialize/deserialize +- computeSignalingKey() — SHA-256(sorted pubkeys), same as MWP meeting point +- Roundtrip + signature verification tests +- **Depends on**: none (uses existing Ed25519) + +### T5.14 — Implement DHT-based signaling (4h) +- **Create**: `src/platform/webrtc_dht_signaling.zig` +- Use dhtStore/dhtFindValue to exchange WebRTC signaling messages +- Flow: compute meeting key → store offer → poll for answer → exchange ICE +- Reuse MWP meeting point derivation +- Timeout with retry +- Test: two P2P instances on localhost, one stores offer in DHT, other finds it +- **Depends on**: T5.13, T1.15 + +### T5.15 — Implement ICE candidate trickle via DHT (3h) +- **Modify**: `src/platform/webrtc_dht_signaling.zig` +- Periodically store batched candidates in DHT +- Other peer polls for new candidates +- Versioned keys or growing value +- Test: ICE candidates propagate, connection succeeds with delayed candidates +- **Depends on**: T5.14 + +### T5.16 — WebSocket signaling fallback (3h) +- **Create**: `src/platform/webrtc_ws_signaling.zig` +- For bootstrap: when DHT unavailable (first browser peer with no native bootstrap) +- Use libdatachannel's WebSocket client (rtcCreateWebSocket — free with the library) +- Lower priority — DHT signaling (T5.14) is primary path +- **Depends on**: T5.10, T3.4 + +### T5.17 — Integrate WebRTC transport into P2P connection flow (4h) +- **Modify**: `src/p2p/connection.zig`, `src/p2p/config.zig` +- Add `webrtc: bool = false` to P2PConfig.transports +- When enabled + peer is browser: WebRTC connection path +- Flow: compute signaling key → create/wait offer → exchange SDP/ICE via DHT → DataChannel opens → create PeerConnection with WebRTCChannelTransport → Noise handshake +- When connecting to native peer: prefer UDP +- **Depends on**: T5.12, T5.14, T1.12 + +### T5.18 — Noise handshake over WebRTC DataChannel (3h) +- Verify Noise XX works over WebRTC DataChannel transport +- SecureConnection uses Transport interface (T1.9), WebRTCChannelTransport implements it (T5.12) +- Should work without code changes — create integration test +- Test: two peers connect via WebRTC, Noise handshake, exchange encrypted messages, verify wire envelope nonce auth +- **Depends on**: T5.12, T1.9 + +### T5.19 — Native-to-browser connection test (4h) ⚠️ HIGH RISK +- **Create**: `tests/integration/test_native_browser.js` (Playwright + native) +- Launch native peer with WebRTC enabled +- Launch browser page with WASM peer +- Exchange signaling via WebSocket signaling server +- Verify DataChannel established +- Send native→browser, verify. Send browser→native, verify. +- **Depends on**: T5.17, T3.7 +- **Risk**: DTLS negotiation, SDP format, ICE candidates must be compatible + +### T5.20 — File transfer over WebRTC DataChannel (3h) +- Test piece-based file transfer through WebRTC transport +- Key: WebRTC DataChannel max message size (default 256KB) must be >= piece size +- Configure rtcConfiguration.maxMessageSize if needed +- Test: 1MB file from native to browser, all pieces verified +- **Depends on**: T5.19 + +### T5.21 — Cleanup and resource management (3h) +- **Modify**: `src/platform/webrtc_native.zig` +- Proper deinit(): close DataChannels, delete PeerConnections, rtcCleanup() +- Edge cases: disconnect during handshake, ICE failure, DataChannel close +- Leak test: 100 connections created+closed, verify zero leaked allocations +- **Depends on**: T5.11 + +### T5.22 — CI build integration (2h) +- Add CI step: `zig build -Denable-webrtc=true` +- Document install steps per platform +- Non-WebRTC builds unaffected +- **Depends on**: T5.3 + +### T5.23 — Phase 5 comprehensive test (4h) +- Full suite with WebRTC enabled +- Matrix: native↔native via UDP (no regression), native↔native via WebRTC, native↔browser via WebRTC +- Verify Noise + wire envelope on all paths +- **Depends on**: T5.17 through T5.21 +- **Gate**: MUST pass before Phase 6 + +--- + +## Phase 6: Integration and Polish (9 tasks, ~30h) + +### T6.1 — Auto-transport negotiation (4h) +- **Modify**: `src/p2p/connection.zig`, `src/p2p/config.zig` +- Native-to-native: prefer UDP. Native-to-browser: use WebRTC. +- Store transport capabilities in DHT peer metadata +- Auto-select on connection +- **Depends on**: T5.17 + +### T6.2 — Connection upgrade: WebRTC → UDP (3h) +- **Modify**: `src/p2p/connection.zig` +- If two native peers connected via WebRTC, attempt upgrade to UDP +- Exchange UDP addresses, attempt direct connection, migrate transport +- **Depends on**: T6.1 + +### T6.3 — Error handling and timeouts (3h) +- **Modify**: `src/platform/webrtc_native.zig`, `src/platform/webrtc_dht_signaling.zig` +- 30s timeout for WebRTC connection establishment +- Handle ICE failure, DTLS failure, DataChannel not opening +- Propagate errors for retry/fallback +- **Depends on**: T5.17 + +### T6.4 — TURN server support (2h) +- **Modify**: `src/platform/webrtc_native.zig` +- Add TURN server URLs to rtcConfiguration +- Config: `ice_servers: ["stun:stun.l.google.com:19302", "turn:user:pass@turn.example.com:3478"]` +- **Depends on**: T5.7 + +### T6.5 — End-to-end browser + DHT test (4h) +- **Create**: `tests/e2e/test_full_stack.js` +- 3 native peers forming DHT + 1 browser peer +- Browser discovers native peers via DHT, connects via WebRTC +- Exchange messages, store/retrieve DHT values across transport boundaries +- **Depends on**: T5.19, T5.14 + +### T6.6 — Cross-browser testing (3h) +- Run browser tests on Chrome, Firefox, Safari +- Fix browser-specific WebRTC quirks +- Document minimum browser versions +- **Depends on**: T3.8 + +### T6.7 — Performance profiling (3h) +- Measure: WebRTC connection setup time, DataChannel throughput, latency vs UDP, WASM memory, CPU +- Compare against design doc targets (setup <500ms, throughput >10MB/s) +- Document results +- **Depends on**: T5.23 + +### T6.8 — Documentation (4h) +- **Create/Modify**: `docs/WEBRTC_BUILD.md`, `docs/WASM_QUICKSTART.md`, README.md +- Build instructions, deployment guide, API reference, architecture diagrams +- New developer can follow docs to run native-to-browser demo +- **Depends on**: T6.5 + +### T6.9 — Final regression and cleanup (4h) +- Full suite: native + WASM + WebRTC +- No Thread.sleep in WASM paths, no direct posix.* in platform-agnostic code +- Remove temporary workarounds +- **Depends on**: all above + +--- + +## Critical Path + +``` +T0.2 → T1.1 → T1.3 → T1.7 → T1.8 → T1.9 → T2.5 → T2.6 → T2.13 + ↓ +T5.1 → T5.2 → T5.3 → T5.5 → T5.6 → T5.7 → T5.9 → T5.12 → T5.17 → T5.19 +``` + +## Summary + +| Phase | Tasks | Hours | +|-------|-------|-------| +| 0: Audit | 4 | 7 | +| 1: Transport Abstraction | 16 | 48 | +| 2: Event-Driven I/O | 13 | 37 | +| 3: WASM Browser | 8 | 24 | +| 4: FileSystem | 7 | 17 | +| 5: Native WebRTC (libdatachannel) | 23 | 71 | +| 6: Integration | 9 | 30 | +| **Total** | **80** | **~234** | + +Phase 3 and Phase 4 can run in parallel after Phase 2 completes.