Skip to content

Latest commit

 

History

History
347 lines (279 loc) · 14.7 KB

AGENTS.md

File metadata and controls

347 lines (279 loc) · 14.7 KB

AGENTS.md - LLM Contribution Guide for Nostrino

Project Overview

Nostrino is a Nostr SDK for Kotlin, providing a multiplatform implementation of the Nostr protocol. The project implements various NIPs (Nostr Implementation Possibilities) and is used by Block/CashApp for Nostr-based features. Nostrino supports JVM, iOS, and Linux platforms.

Using Nostrino from Another Project

Read this when a service or app needs Nostr or Buzz, not only when working on Nostrino itself.

  • On the JVM or in Kotlin, use Nostrino for all Nostr work: keys, event ids and signatures, NIP-98 HTTP auth, NIP-44 encryption and relays. Use nostr-sdk-buzz (BuzzClient) to post to Buzz.
  • Do not hand-roll NIP-01 id hashing, Schnorr event signing or Authorization: Nostr headers. The id preimage must match the relay's serialization byte for byte, and default Moshi and Jackson settings get it wrong for some content (for example U+2028 and U+2029).
  • If Nostrino lacks something a caller needs, add it to Nostrino rather than working around it in the caller. Standard NIPs go in lib, and Buzz-specific behaviour goes in buzz.
  • See README.md for usage examples.

Technology Stack

  • Language: Kotlin (Multiplatform)
  • Build System: Gradle with Kotlin DSL
  • Java Version: JVM 11
  • Test Framework: JUnit 5 (Jupiter) + Kotest
  • Platforms: JVM, iOS (x64, ARM64, Simulator ARM64), Linux x64
  • Key Dependencies:
    • OkHttp (HTTP client for JVM)
    • Moshi (JSON)
    • acinq secp256k1 (Cryptographic curves)
    • Kotlinx Coroutines (Asynchronous programming)
    • OkIO (I/O operations)
    • Kotest (Testing and assertions)
    • Turbine (Flow testing)

Build & Development Commands

Prerequisites

This project uses Hermit for consistent tooling. Activate it with:

. ./bin/activate-hermit

Essential Commands

IMPORTANT: This project uses Hermit. Always use bin/gradle instead of gradlew or gradle.

# Build the entire project (includes tests)
bin/gradle build

# Run tests only
bin/gradle test

# Clean build
bin/gradle clean build

# Check for API breaking changes (binary compatibility)
bin/gradle apiCheck

# Generate new API dumps after API changes
bin/gradle apiDump

# Check for dependency updates
bin/gradle dependencyUpdates -Drevision=release

# Update version catalog
bin/gradle versionCatalogUpdate

# Generate API documentation
bin/gradle dokkaHtml

Project Structure

nostrino/
├── lib/                    # Main SDK library (multiplatform)
│   └── src/
│       ├── commonMain/kotlin/   # Platform-agnostic code
│       └── jvmMain/kotlin/      # JVM-specific code
├── lib-test/              # Testing utilities and integration tests
│   └── src/
│       ├── main/kotlin/        # Test helpers and Arb generators
│       └── test/kotlin/        # Integration tests
├── buzz/                  # Buzz-specific client (JVM)
│   └── src/
│       ├── main/kotlin/        # BuzzClient and BuzzChannel
│       └── test/kotlin/        # Tests against the Buzz relay in Docker
├── buildSrc/              # Build configuration
└── gradle/                # Gradle wrapper and version catalog
    └── libs.versions.toml # Dependency versions

Code Conventions

General Style

  • Indentation: 2 spaces (NOT tabs)
  • Line Length: Maximum 120 characters
  • Line Endings: LF (Unix-style)
  • Charset: UTF-8
  • Final Newline: Always insert
  • Copyright Headers: Required for all new files. Always use the current year (2025) in the copyright year field, not the project start year (2023)

Kotlin-Specific

  • Imports: No wildcard imports (use explicit imports)
    • ij_kotlin_name_count_to_use_star_import = 2147483647
    • ij_kotlin_name_count_to_use_star_import_for_members = 2147483647
  • Naming: Follow standard Kotlin conventions
  • Null Safety: Leverage Kotlin's null safety features
  • Function Syntax: Prefer expression syntax over block body. Avoid early returns when possible
    • ✅ fun add(a: Int, b: Int): Int = a + b
    • ✅ fun isValid(x: Int): Boolean = x > 0
    • ❌ fun add(a: Int, b: Int): Int { return a + b }
  • Parameters: Wrap on every item with proper formatting
    • Method parameters: new line after (, right paren on new line
    • Call parameters: new line after (, right paren on new line
  • Code Style: Follow Kotlin official code style

Testing

Testing Philosophy: Sociable Unit Testing

Nostrino follows the Sociable Unit Testing approach for comprehensive, resilient test coverage.

Core Principle: Write unit tests for all classes, but let them connect through to real dependencies until hitting the system boundary.

  • ✅ Real object graphs: Classes use their actual dependencies (services, stores, validators)
  • ✅ Fake external services: Only external APIs and services are faked at system boundaries
  • ✅ Fast execution: Still runs quickly despite using real components
  • ✅ Less brittle: No need to update mocks when internal implementations change

System Boundaries (what gets faked or containerised):

  • External relay servers: use FakeRelay for unit tests, and the Docker relays for integration tests
  • Nostr relay connections
  • HTTP relay APIs (such as Buzz's /events): always the real Buzz relay in Docker, never a mock server

Benefits over traditional mock-based testing:

  • Tests behavior, not implementation details
  • Resilient to refactoring
  • Real integration confidence
  • Simpler test setup

Test Framework & Conventions

  • Framework: JUnit 5 (Jupiter) + Kotest - configured in root build.gradle.kts
  • Test Style: ALWAYS use Kotest StringSpec (test names in strings)
  • Assertions: Use Kotest matchers (shouldBe, shouldBeEqual, shouldContainExactly, etc.) - NOT JUnit assertions
  • Test Naming: Test class suffix is Test (e.g., RelaySetTest.kt)
  • Test Names: Use string literals for readable test names (StringSpec style)
  • Integration Tests: Use the Docker relays that start before the tests that need them:
    • nostr-rs-relay at ws://localhost:7707, started by lib-test, for NIP-01 websocket traffic
    • a second nostr-rs-relay with NIP-42 auth enabled at ws://localhost:7710, also started by lib-test, which sends an AUTH challenge on connect
    • the Buzz relay (ghcr.io/block/buzz, with Postgres and Redis, from buzz/buzz-relay.compose.yml), started by buzz, at http://localhost:7708, for Buzz's HTTP API
    • a second Buzz relay from the same file, with closed membership, at http://localhost:7709, owned by the key whose secret is 1, for NIP-OA owner attestation
  • Never use MockWebServer: Do not use MockWebServer, or any other mock HTTP server, in tests. Test HTTP clients against the real relay in Docker, so the tests prove what the relay accepts. Keep Docker image tags pinned to a released version, and update them when the relay releases
  • Mocking: Use fake implementations (e.g., FakeRelay) for external system boundaries, not internal dependencies
  • Test Data Generation: Prefer Arb<T> generators over hard-coded values. Compose existing Arb generators for new types
    • Located in lib-test/src/main/kotlin (e.g., ArbEvent.kt, ArbPubKey.kt)
    • Use Arb.next() to generate single values
    • Use checkAll() for property-based testing
  • Flow Testing: Use Turbine for testing Kotlin Flows
  • Assertion Style: Use Kotest matchers for clean, expressive assertions

Test Example

// Simple unit test with Kotest StringSpec
class RelaySetTest : StringSpec({
  "delegates start" {
    val set = RelaySet(
      setOf(FakeRelay(), FakeRelay(), FakeRelay())
    )
    set.start()
    set.relays.map { it as FakeRelay }.map { it.started } shouldBe listOf(true, true, true)
  }

  "merge distinct events into a single flow" {
    val events = Arb.list(arbEvent, 20..20).next().distinct().take(6)
    val set = RelaySet(
      setOf(
        FakeRelay(events.take(2).toMutableList()),
        FakeRelay(events.drop(2).take(2).toMutableList()),
        FakeRelay(events.drop(4).take(2).toMutableList())
      )
    )
    set.subscribe(Filter.globalFeedNotes)

    set.allEvents.toList() shouldContainExactly events
  }
})

// Fake implementation for testing (defined in same file as tests)
class FakeRelay(val sent: MutableList<Event> = mutableListOf()) : Relay() {
  var started = false
  override fun start() {
    started = true
  }

  var stopped = false
  override fun stop() {
    stopped = true
  }

  override fun send(event: Event) {
    sent.add(event)
  }

  val subscriptions = mutableMapOf<Subscription, Set<Filter>>()
  override fun subscribe(filters: Set<Filter>, subscription: Subscription): Subscription =
    subscription.also {
      subscriptions[subscription] = filters
    }

  val unsubscriptions = mutableSetOf<Subscription>()
  override fun unsubscribe(subscription: Subscription) {
    unsubscriptions.add(subscription)
  }

  override val relayMessages: Flow<RelayMessage> =
    sent.asSequence()
      .zip(arbSubscriptionId.samples())
      .map { (event, id) -> EventMessage(id.value, event) }
      .asFlow()

  override val allEvents: Flow<Event> = sent.asFlow()
}

Testing Best Practices

  1. Use real dependencies - Let controllers use real stores, validators, etc.
  2. Fake at boundaries - Only fake external relay servers, and never with a mock HTTP server
  3. Test both paths - Write tests for success and failure cases
  4. Use property-based testing - Leverage Kotest's Arb generators and checkAll() for comprehensive coverage
  5. Avoid redundant comments - Let test names be descriptive. Never add AAA (Arrange/Act/Assert) comments
  6. Prefer brevity - Keep tests concise and to the point
  7. Independent tests - Each test creates its own test data
  8. Property-based test data - Use Kotest's Arb generators where applicable
  9. Add relay integration tests - When implementing new NIPs or message exchanges, add integration tests in RelayClientTest.kt that connect to the real Docker relay at ws://localhost:7707 to verify end-to-end functionality

Multiplatform Considerations

Nostrino is a Kotlin Multiplatform project. When making changes:

  • Platform-specific code: Place in appropriate source sets (jvmMain, commonMain, etc.)
  • Common code first: Prefer platform-agnostic implementations in commonMain
  • Platform implementations: Use expect/actual pattern when platform-specific implementations are required
  • Dependencies: Check platform compatibility of dependencies
  • Testing: Focus integration tests in lib-test (JVM-only), unit tests can be in lib

Binary Compatibility

The project uses the Kotlin Binary Compatibility Validator to prevent unintentional API changes.

  • API changes: Run bin/gradle apiDump after making intentional API changes
  • Before committing: Always run bin/gradle apiCheck to verify no unintentional breaking changes
  • API files: Commit .api files alongside code changes
  • Breaking changes: Avoid removals and additions in the same change to prevent downstream compatibility issues

Module Responsibilities

lib/

Main SDK library implementing Nostr protocol functionality. Contains multiplatform code for:

  • Event creation and validation
  • Cryptographic operations (signing, encryption)
  • Relay communication
  • Message encoding/decoding
  • Filter construction

lib-test/

Testing utilities and integration tests. Contains:

  • Arb generators for test data (ArbEvent, ArbPubKey, etc.)
  • Fake implementations (FakeRelay)
  • Integration tests against real relay server
  • Docker-based relay setup for testing (nostr-rs-relay)

buzz/

Client for Buzz, published as nostr-sdk-buzz. Contains:

  • BuzzClient and BuzzChannel, for Buzz's HTTP API
  • Tests against the Buzz relay stack in Docker
  • Buzz-specific behaviour belongs here, not in lib. Standard NIPs that Buzz uses (such as NIP-29 and NIP-98) stay in lib

Publishing

The project is published to Maven Central:

Contributing Guidelines

  1. Code Style: Follow the .editorconfig settings (automatically enforced by IntelliJ IDEA)
  2. Testing: All new features must include comprehensive tests
  3. Binary Compatibility: Run bin/gradle apiCheck before committing; use bin/gradle apiDump for intentional API changes
  4. No Warnings: Compiler is configured with allWarningsAsErrors = true
  5. Multiplatform: Ensure changes work across all target platforms when possible
  6. Documentation: Update module documentation and KDoc comments for public APIs
  7. Build Verification: Always run bin/gradle build before committing to ensure tests pass
  8. Dependencies: Check existing dependencies before adding new ones
  9. Licensing: New runtime dependencies must be licensed with Apache 2.0, MIT, BSD, ISC, or Creative Commons Attribution (test & build dependencies can be more flexible)

Important Notes for LLMs

  • Never add wildcard imports - use explicit imports for all Kotlin files
  • Use Kotest for assertions, not JUnit assertions
  • Use StringSpec style for test classes with string-based test names
  • Use Arb generators for test data instead of hard-coded values
  • Check .editorconfig before making formatting decisions
  • All tests use JUnit 5 (Jupiter) with Kotest - configured in root build.gradle.kts
  • Binary compatibility matters - always run bin/gradle apiCheck before committing
  • Multiplatform project - be mindful of platform-specific vs common code placement
  • No compiler warnings allowed - allWarningsAsErrors = true is set

@ai-rules/issue-tracking.md

Landing the Plane (Session Completion)

When ending a work session, you MUST complete ALL steps below. Work is NOT complete until git push succeeds.

MANDATORY WORKFLOW:

  1. File issues for remaining work - Create issues for anything that needs follow-up
  2. Run quality gates (if code changed) - Tests, linters, builds
  3. Update issue status - Close finished work, update in-progress items
  4. PUSH TO REMOTE - This is MANDATORY:
    git pull --rebase
    bd sync
    git push
    git status  # MUST show "up to date with origin"
  5. Clean up - Clear stashes, prune remote branches
  6. Verify - All changes committed AND pushed
  7. Hand off - Provide context for next session

CRITICAL RULES:

  • Work is NOT complete until git push succeeds
  • NEVER stop before pushing - that leaves work stranded locally
  • NEVER say "ready to push when you are" - YOU must push
  • If push fails, resolve and retry until it succeeds