### Complete Tenancy Setup Example Source: https://docs.muonroi.com/docs/reference/packages/tenancy This example demonstrates a comprehensive setup for multi-site and multi-tenant applications using the tenancy services. It includes registration for core tenancy, site profiles, per-site DbContext and Dapper infrastructure, quota tracking, gRPC, and middleware. ```csharp var builder = WebApplication.CreateBuilder(args); // ===== Core Tenancy (HttpContext extraction + AsyncLocal storage) ===== builder.Services.AddTenancy(builder.Configuration); // ===== Site Profile Infrastructure ===== builder.Services.AddMultiSiteProfiles( builder.Configuration, siteCodeAccessor: sp => { var httpContext = sp.GetRequiredService()?.HttpContext; return httpContext?.Request.Headers["X-Site-Code"].FirstOrDefault() ?? "default"; }, assemblies: typeof(Program).Assembly); // ===== Per-Site DbContext ===== builder.Services.AddSiteDbInfrastructure(o => { o.TenantId = sp => sp.GetRequiredService() .Get().TenantId; o.ConnectionString = sp => { var factory = sp.GetRequiredService(); var tenantId = sp.GetRequiredService().TenantId; return factory.GetConnectionString(tenantId); }; o.ConnectionStringTransform = cs => Cryptography.Decrypt(_secretKey, cs); o.ConfigureDbContext = (b, cs) => b.UseSqlServer(cs); }); builder.Services.AddSiteDbContext(); builder.Services.AddSiteDbContext(); builder.Services.AddSiteMigrationRunner(); // ===== Per-Site Dapper ===== builder.Services.AddSiteDapperInfrastructure(o => { o.WriteConnectionString = sp => { var factory = sp.GetRequiredService(); var tenantId = sp.GetRequiredService().TenantId; return factory.GetConnectionString(tenantId); }; o.ReadConnectionString = sp => { // Optional: separate read replica return sp.GetRequiredService() .GetReadConnectionString(); }; }); builder.Services.AddSiteResolvedService(); builder.Services.AddSiteResolvedService(); builder.Services.AddSiteSqlBuilder(); // ===== Quota Tracking ===== builder.Services.AddTenantQuota(); // ===== gRPC ===== builder.Services.AddSiteGrpc(); // ===== Site Profiles (source-generated or manual) ===== builder.Services.AddGeneratedSiteProfiles(builder.Configuration); var app = builder.Build(); // ===== Middleware ===== app.UseMiddleware(); app.UseMiddleware(); app.Run(); ``` -------------------------------- ### Run Quickstart Decision Table Sample Source: https://docs.muonroi.com/docs/getting-started/quickstart-decision-table Navigate to the quickstart API project directory and run the .NET application to start evaluating loan applications. ```bash cd muonroi-building-block/samples/Quickstart.DecisionTable/src/Quickstart.DecisionTable.Api dotnet run ``` -------------------------------- ### muonroi-cli Quick Start Commands Source: https://docs.muonroi.com/docs/cli/overview Examples of common muonroi-cli commands for interactive TUI, starting prompts, headless mode, listing models, and health checks. ```bash muonroi-cli # interactive TUI ``` ```bash muonroi-cli "fix the flaky test in auth.test.ts" # with starting prompt ``` ```bash muonroi-cli --prompt "run tests" --format json # headless / CI mode ``` ```bash muonroi-cli models # list models with pricing ``` ```bash muonroi-cli doctor # health check ``` -------------------------------- ### Complete Integration Example for .NET Web Application Source: https://docs.muonroi.com/docs/reference/packages/observability-diagnostics This snippet shows the full setup for a .NET web application, including adding Muonroi logging, diagnostics, and observability services. It also includes an example endpoint demonstrating structured logging and trace session usage. ```csharp using Muonroi.Logging; using Muonroi.Diagnostics; using Muonroi.Observability; using Muonroi.Logging.Abstractions; using Muonroi.Core.Abstractions.Diagnostics; var builder = WebApplicationBuilder.CreateBuilder(args); // 1. Add structured logging builder.Logging.AddMuonroiLogging(); // 2. Add diagnostics (trace sessions) builder.Services.AddMuonroiDiagnostics(); // or AddMuonroiDiagnosticsRedis() // 3. Add observability (OpenTelemetry, metrics, exporters) builder.Services.AddObservability(builder.Configuration); var app = builder.Build(); app.MapPost("/api/orders", ProcessOrderEndpoint); app.Run(); // Endpoint async Task ProcessOrderEndpoint( HttpContext httpContext, IMLog log, IMTraceContext traceContext, OrderService orderService) { var correlationId = httpContext.TraceIdentifier; var tenantId = httpContext.User.FindFirst("tenant_id")?.Value ?? "unknown"; // Begin trace session for full execution tracing using var traceScope = traceContext.Begin( sessionId: Guid.NewGuid().ToString(), tenantId: tenantId, userId: httpContext.User.Identity?.Name, lineTraceEnabled: false ); // Log with automatic context enrichment using (log.BeginProperty(LogPropertyConventions.CorrelationId, correlationId)) using (log.BeginProperty(LogPropertyConventions.TenantId, tenantId)) { log.Info("Processing order", new { CorrelationId = correlationId }); try { var result = await orderService.ProcessAsync("ORD-001", 5000m); log.Info("Order processed successfully", new { OrderId = "ORD-001", Status = result.Status }); // Export trace session var session = traceContext.Current; if (session != null) { var traceRecord = session.Export(); // Store in database for audit trail } return Results.Ok(result); } catch (Exception ex) { log.Error(ex, "Order processing failed"); var session = traceContext.Current; if (session != null) { var traceRecord = session.Export(); // Log exception with full trace context } return Results.BadRequest(new { Error = ex.Message }); } } } public class OrderService(IMLog log, IMTraceContext traceContext) { public async Task ProcessAsync(string orderId, decimal amount) { using (log.BeginProperty("order.id", orderId)) using (log.BeginProperty("order.amount", amount)) { var session = traceContext.Current; using (session?.BeginNode("ValidateOrder", MTraceNodeType.Rule)) { log.Info("Validating order"); if (amount <= 0) { session?.MarkFailed("Invalid amount"); throw new InvalidOperationException("Amount must be positive"); } } using (session?.BeginNode("ApproveOrder", MTraceNodeType.Rule)) { log.Info("Approving order"); await Task.Delay(100); } log.Info("Order processing complete"); return new OrderResult { Status = "approved" }; } } } public record OrderResult { public string Status { get; set; } = string.Empty; } ``` -------------------------------- ### Example Claims Population Source: https://docs.muonroi.com/docs/guides/identity-access/auth-module-guide Demonstrates how claims for username, user GUID, and tenant ID are created and populated into the authentication context. ```csharp new Claim(nameof(MAuthenticateInfoContext.CurrentUsername), verifyToken.CurrentUsername), new Claim(nameof(MAuthenticateInfoContext.CurrentUserGuid), verifyToken.CurrentUserGuid), new Claim(ClaimConstants.TenantId, resolvedContext.TenantId) ``` -------------------------------- ### Multi-Provider Setup Configuration Source: https://docs.muonroi.com/docs/cli/overview Example JSON configuration for `~/.muonroi-cli/user-settings.json` to set up multiple API keys and define role models for advanced routing. ```json { "apiKey": "sk-ant-your-key", "providers": { "anthropic": { "apiKey": "sk-ant-..." }, "deepseek": { "apiKey": "sk-..." } }, "roleModels": { "leader": "claude-sonnet-4-6", "implement": "deepseek-v4-flash", "verify": "claude-sonnet-4-6", "research": "deepseek-v4-flash" } } ``` -------------------------------- ### Tenancy Configuration Example Source: https://docs.muonroi.com/docs/reference/appsettings-guide Example of how to configure tenancy settings, including isolation mode and default tenant ID. ```json "TenancyConfigs": { "IsolationMode": "SharedSchema", "DefaultTenantId": "system", "EnableQuotaEnforcement": true, "QuotaCacheExpiryMinutes": 5 } ``` -------------------------------- ### Install and Ingest Documents Source: https://docs.muonroi.com/docs/mcp/mcp-bb-docs Installs dependencies and runs the initial document ingestion process. This is typically done once for a new project. ```bash cd D:/sources/Core/muonroi-docs/mcp npm install npm run ingest ``` -------------------------------- ### Quick Install Experience Engine Source: https://docs.muonroi.com/docs/experience-engine/getting-started Use this command for a quick, automated installation on any OS. It detects and configures your local or remote brain. ```bash npx @muonroi/experience-engine init ``` -------------------------------- ### Install Bun (macOS/Linux) Source: https://docs.muonroi.com/docs/cli/quickstart Installs Bun on macOS or Linux using curl to download and execute the installation script from bun.sh. ```bash # macOS / Linux curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Install Bun (Windows PowerShell) Source: https://docs.muonroi.com/docs/cli/quickstart Installs Bun on Windows using PowerShell by executing a script from bun.sh. ```powershell # Windows (PowerShell) powershell -c "irm bun.sh/install.ps1 | iex" ``` -------------------------------- ### Install UI Engine Rule Components and Core Packages Source: https://docs.muonroi.com/docs/guides/ui-engine/rule-flow-designer Install the core runtime helpers and the web components for the rule flow designer. ```bash npm install @muonroi/ui-engine-core @muonroi/ui-engine-rule-components ``` -------------------------------- ### Install npm Packages Source: https://docs.muonroi.com/docs/reference/package-reference Installs core and commercial UI engine packages from the npm registry. ```bash npm install @muonroi/ui-engine-core npm install @muonroi/ui-engine-rule-components # Commercial ``` -------------------------------- ### Install muonroi-cli (Windows PowerShell) Source: https://docs.muonroi.com/docs/cli/reference/mcp-tools-mcp Installs the `muonroi-cli` using a PowerShell command for Windows. This method also provides a prebuilt binary. ```powershell # Windows PowerShell irm https://raw.githubusercontent.com/muonroi/muonroi-cli/master/install.ps1 | iex ``` -------------------------------- ### Run Multi Tenant SaaS Sample Source: https://docs.muonroi.com/docs/resources/samples/multi-tenant-saas Navigate to the sample directory, restore dependencies, and run the API project. ```bash cd \muonroi-building-block\samples\MultiTenantSaaS\src\MultiTenant.Api dotnet restore dotnet run ``` -------------------------------- ### Get Decision Table Response Example Source: https://docs.muonroi.com/docs/reference/decision-table-api Example of a successful response when retrieving a specific decision table's full definition, including its structure and rules. ```json { "id": "discount-table-001", "name": "Customer Discount Rules", "description": "Discount rates by customer type and region", "inputColumns": [ { "name": "customerType", "type": "string", "required": true }, { "name": "amount", "type": "number", "required": true }, { "name": "region", "type": "string", "required": false } ], "outputColumns": [ { "name": "discountRate", "type": "number" }, { "name": "freeShipping", "type": "boolean" } ], "hitPolicy": "First", "rows": [ { "id": "row-1", "priority": 1, "inputConditions": { "customerType": "\"premium\"", "amount": ">= 5000", "region": "-" }, "outputs": { "discountRate": 0.20, "freeShipping": true } } ], "version": 5, "createdAt": "2026-02-15T08:00:00Z", "modifiedAt": "2026-03-20T10:30:00Z" } ``` -------------------------------- ### Create License File Source: https://docs.muonroi.com/docs/getting-started/quickstart Create a `licenses` directory and add your license key file to it. This file is required at startup. ```json { "LicenseKey": "MRR-xxxxxxxxxxxxxxxxxxxxx" } ``` -------------------------------- ### Quick Start: Experience Engine Python SDK Usage Source: https://docs.muonroi.com/docs/experience-engine/python-sdk Initialize the client, query for warnings, extract lessons from a transcript, trigger an evolution cycle, and view the knowledge evolution timeline. ```python from muonroi_experience import Client # Initialize client client = Client("http://localhost:8082") # Query for warnings before a tool call result = client.intercept("Write", {"file_path": "app.py"}) if result["hasSuggestions"]: print(result["suggestions"]) # Extract lessons from a session transcript client.extract("Agent tried singleton for DbContext, caused state corruption...") # Trigger evolution cycle evolution = client.evolve() print(f"Promoted: {evolution['promoted']}, Abstracted: {evolution['abstracted']}") # View knowledge evolution timeline timeline = client.timeline("dependency injection") for entry in timeline["timeline"]: status = '[superseded]' if entry['superseded'] else '' print(f" {status} {entry['solution']}") ``` -------------------------------- ### Usage Example: Fetching Data with Standard Resilience Pipeline Source: https://docs.muonroi.com/docs/reference/packages/infrastructure Use the injected ResiliencePipelineProvider to get and execute a resilience pipeline for HTTP requests. This example demonstrates fetching data from an external API with built-in resilience. ```csharp public class ExternalApiService(ResiliencePipelineProvider pipelineProvider) { private readonly HttpClient _httpClient = new(); public async Task FetchDataAsync(string endpoint) { var pipeline = pipelineProvider.GetPipeline("muonroi-standard"); var outcome = await pipeline.ExecuteAsync( async (ct) => { var response = await _httpClient.GetAsync(endpoint, ct); return response; }, CancellationToken.None); return await outcome.Result.Content.ReadAsStringAsync(); } } ``` -------------------------------- ### Basic Rule Engine Setup with DI Source: https://docs.muonroi.com/docs/guides/rule-engine/rule-engine-guide Configure the Rule Engine with PostgreSQL storage and optional features like hot reload and FEEL support during application startup. ```csharp var builder = WebApplicationBuilder.CreateBuilder(args); // Rule engine with PostgreSQL storage (for runtime rulesets) builder.Services.AddMRuleEngineWithPostgres( connectionString: configuration.GetConnectionString("Default"), options => { options.RequireApproval = true; options.NotifyOnStateChange = true; options.ExecutionMode = ExecutionMode.BestEffort; }); // Optional: Enable Redis-backed hot reload builder.Services.AddMRuleEngineWithRedisHotReload( configuration.GetConnectionString("Redis")); // Optional: FEEL expression support builder.Services.AddFeelWeb(); ``` -------------------------------- ### Register Observability and Logging Services Source: https://docs.muonroi.com/docs/reference/packages/observability-diagnostics Quick start example for registering Muonroi logging and observability services in an ASP.NET Core application. ```csharp var builder = WebApplicationBuilder.CreateBuilder(args); builder.Services.AddMuonroiLogging(); builder.Services.AddObservability(builder.Configuration); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Program.cs Example for Sample Project Source: https://docs.muonroi.com/docs/operations/migration-scripts A minimal Program.cs file for a generated sample project, demonstrating how to import and reference a Muonroi package. ```csharp using Muonroi.Core; Console.WriteLine("Muonroi.Core.Sample running..."); Console.WriteLine("Reference loaded: Muonroi.Core"); ``` -------------------------------- ### MRepository Example for Tenant Filtering Source: https://docs.muonroi.com/docs/concepts/ef-filters Inherit from MRepository to automatically get tenant filtering. The query automatically includes a WHERE clause for the current tenant. ```csharp public class OrderRepository : MRepository { public OrderRepository(MyDbContext context) : base(context) { } // Tenant filtering is automatic via MDbContext public async Task> GetOrdersAsync(int page = 1, int pageSize = 10) { // This query automatically includes: WHERE TenantId = {CurrentTenantId} return await GetPagedAsync( query => query.OrderByDescending(o => o.CreatedAt), page, pageSize ); } } ``` -------------------------------- ### Example Activation Request Source: https://docs.muonroi.com/docs/guides/license-governance/license-activation Send a POST request to the activation endpoint with your license key and machine fingerprint. ```bash curl -X POST https://license.truyentm.xyz/api/v1/activate \ -H "Content-Type: application/json" \ -d '{ "licenseKey": "MRR-YWJjZGVmZ2hpamtsbW5vcA==", "machineFingerprint": "abc123def456ghi789" }' ``` -------------------------------- ### Get Table Audit Trail Example Source: https://docs.muonroi.com/docs/reference/decision-table-api Retrieves the audit log for a specific decision table. Use this to track changes made to an individual table. ```json [ { "timestamp": "2026-03-20T10:30:00Z", "action": "Update", "actor": "john.doe@example.com", "version": 5, "comment": "Increased premium discount from 15% to 20%", "changesSummary": "Modified 1 row, added 0 rows, removed 0 rows" }, { "timestamp": "2026-03-15T14:22:00Z", "action": "Create", "actor": "system", "version": 1, "comment": null, "changesSummary": "Initial version" } ] ``` -------------------------------- ### Run Loan Approval Sample Source: https://docs.muonroi.com/docs/resources/samples/loan-approval Navigate to the sample's API directory, restore dependencies, and run the application. ```bash cd \muonroi-building-block\samples\LoanApproval\src\LoanApproval.Api dotnet restore dotnet run ``` -------------------------------- ### Get Specific Version using curl Source: https://docs.muonroi.com/docs/reference/decision-table-api Example curl command to fetch the definition of a particular decision table version. Replace the version number as required. ```curl curl -X GET "https://cp.truyentm.xyz/api/v1/decision-tables/discount-table-001/versions/4" \ -H "Authorization: Bearer YOUR_TOKEN" ``` -------------------------------- ### Site Profile Implementation Example Source: https://docs.muonroi.com/docs/reference/packages/tenancy This example shows how to implement a specific site profile for a tenant. It registers tenant-specific services like DbContext, repositories, Dapper implementations, column mappings, gRPC clients, and custom behaviors. ```csharp [GenerateSiteProfile(SiteIds.BRAVO, typeof(BravoOrderContext))] public class BravoSiteProfile : ISiteProfile { public string SiteId => SiteIds.BRAVO; public void RegisterServices(IServiceCollection services, IConfiguration configuration) { // DbContext (already registered globally, but can customize here) services.AddSiteDbContext(); // Repositories services.AddKeyedScoped(SiteId); // Services services.AddKeyedScoped(SiteId); // Dapper services.AddKeyedScoped(SiteId); services.AddKeyedScoped(SiteId); // Column mappings services.AddKeyedSingleton(SiteId); // gRPC services services.AddKeyedScoped(SiteId); // Custom behavior services.AddKeyedScoped(SiteId); } } ``` -------------------------------- ### Canary Rollout Response Source: https://docs.muonroi.com/docs/operations/canary-shadow Example of a successful response when starting a canary rollout. It includes details about the rollout ID, workflow, version, status, and targeting parameters. ```json { "rolloutId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "workflowName": "OrderApproval", "version": 3, "status": "Active", "createdAt": "2026-03-20T10:15:00Z", "targetPercentage": 25, "targetTenantIds": null } ``` -------------------------------- ### Core Foundation Service Implementation Example Source: https://docs.muonroi.com/docs/reference/packages/core-foundation This example demonstrates how to define entity and DTO classes, create a mapper, and implement a site-specific service using MServiceBase. It includes custom validation and default value application. ```csharp // Define your entity and DTO public class Product : IEntityBase { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class ProductDto { public string Name { get; set; } public decimal Price { get; set; } } // Define your mapper public class ProductMapper : IEntityMapper { public ProductDto ToDto(Product entity) => new() { Name = entity.Name, Price = entity.Price }; public Product ToEntity(ProductDto dto) => new() { Name = dto.Name, Price = dto.Price }; public void ApplyUpdate(Product entity, ProductDto dto) { entity.Name = dto.Name; entity.Price = dto.Price; } } // Create site service public class ProductService : MServiceBase { public ProductService(DbContext context, IEntityMapper mapper) : base(context, mapper) { } protected override async Task ValidateAsync(Product entity, CancellationToken ct) { if (entity.Price <= 0) throw new ArgumentException("Price must be positive"); } protected override void ApplyDefaultValues(Product entity) { entity.CreatedAt = DateTime.UtcNow; } protected override async Task AfterCreate(Product entity, CancellationToken ct) { // Publish event, send notification, etc. await Task.CompletedTask; } } // Usage var service = new ProductService(context, mapper); var dto = new ProductDto { Name = "Widget", Price = 9.99m }; var created = await service.CreateAsync(dto); var retrieved = await service.GetByIdAsync(created.Id); ``` -------------------------------- ### Submit Feedback (Raw Curl - Not Recommended) Source: https://docs.muonroi.com/docs/experience-engine/api-reference Reports a verdict on a suggestion using a raw curl request. This method is not recommended for thin-client setups or remote installations. ```bash curl -X POST http://localhost:8082/api/feedback \ -H "Content-Type: application/json" \ -d '{ "pointId": "a1b2c3d4", "collection": "experience-behavioral", "verdict": "followed" }' ``` -------------------------------- ### SignalR Canary Event Notifications Source: https://docs.muonroi.com/docs/guides/control-plane/canary-rollout-guide These are example JSON payloads for SignalR notifications indicating canary state changes. They include events for starting, promoting, and rolling back canaries. ```json { event: "CanaryStarted", workflowName: "loan-approval", rolloutId: "f47ac10b-...", ``` ```json version: 3, targetPercentage: 10, timestamp: "2026-03-20T10:30:00Z" } ``` ```json { event: "CanaryPromoted", workflowName: "loan-approval", newActiveVersion: 3, previousActiveVersion: 2, timestamp: "2026-03-20T10:45:00Z" } ``` ```json { event: "CanaryRolledBack", workflowName: "loan-approval", rolloutId: "f47ac10b-...", ``` ```json reason: "Error rate increased 5x", timestamp: "2026-03-20T10:42:00Z" } ``` -------------------------------- ### Site Project File Structure Example Source: https://docs.muonroi.com/docs/guides/site-profile/adding-a-new-site Recommended file structure for a new site project to maintain isolated dependencies. This includes DI entry points, site-specific contexts, entities, services, and gRPC implementations. ```plaintext MyProject.Sites.Bravo/ ├── BravoSiteProfile.cs # DI entry point with [GenerateSiteProfile] ├── BravoSiteProfile.Additional.cs # Partial method for custom DI registrations ├── BravoOrderContext.cs # Site-specific DbContext ├── Entities/ │ └── OrderDetailBravo.cs # Site-specific entity (inherits base) │ └── OrderDetailBravoConfig.cs # EF Core configuration overrides ├── Services/ │ └── BravoOrderService.cs # Business logic overrides (optional) ├── Hooks/ │ └── BravoValidationHook.cs # Pipeline hooks (optional) ├── Grpc/ │ └── BravoGrpcService.cs # [SiteGrpcService] implementation ├── Protos/ │ └── service.bravo.proto # Site-specific proto file └── BravoColumnMap.cs # Column name overrides for Dapper (optional) ``` -------------------------------- ### Example .env File Configuration Source: https://docs.muonroi.com/docs/cli/reference/providers-reference Configure primary and multi-provider API keys, and optionally override the default model. ```dotenv # Primary provider MUONROI_API_KEY=sk-ant-... # Multi-provider routing OPENAI_API_KEY=sk-proj-... DEEPSEEK_API_KEY=sk-... GOOGLE_API_KEY=AIza... # Override (use sparingly) MUONROI_MODEL=claude-opus-4-7 ``` -------------------------------- ### Verify Experience Engine Setup Source: https://docs.muonroi.com/docs/experience-engine/getting-started After starting the Docker services, use curl to check the health status of the Experience Engine API and its dependencies. This confirms that all services are running correctly. ```bash curl http://localhost:8082/health ``` -------------------------------- ### Node Authoring Contract Response Example Source: https://docs.muonroi.com/docs/reference/rule-flow-contract-api This snippet illustrates the response shape for the GET /api/v1/control-plane/rule-flow/{flowCode}/nodes/{nodeId}/authoring-contract endpoint, showing request scope and response delta. ```json { "flowCode": "FCD-CreateV2-Rules", "nodeId": "condition-2", "ruleCode": "FCD_V2_TAX_VALID", "requestScope": { "contractName": "FCD_V2_TAX_VALID_request_scope", "fields": [ { "path": "request.orderId", "dataType": "string" }, { "path": "liners.code", "dataType": "string" } ] }, "responseDelta": { "contractName": "FCD_V2_TAX_VALID_response_delta", "fields": [ { "path": "bookingContainers", "dataType": "array" } ] } } ``` -------------------------------- ### Service Discovery Startup and Locator Implementation Source: https://docs.muonroi.com/docs/reference/packages/infrastructure Implement IHostedService for service discovery startup logic and a ServiceLocator class to query Consul for service endpoints. Demonstrates how to integrate service discovery into the application lifecycle and resolve services. ```csharp public class ServiceDiscoveryStartup : IHostedService { private readonly ConsulConfigs _consulConfigs; private readonly IConsulClient? _consulClient; private readonly IMLog _log; public ServiceDiscoveryStartup( IOptions consulOptions, IConsulClient? consulClient, IMLog log) { _consulConfigs = consulOptions.Value; _consulClient = consulClient; _log = log; } public async Task StartAsync(CancellationToken cancellationToken) { if (!_consulConfigs.Enable || _consulClient == null) { _log.Info("Service discovery is disabled"); return; } // Service registration occurs in UseServiceDiscovery middleware _log.Info($"Service {_consulConfigs.ServiceName} registered with Consul"); await Task.CompletedTask; } public async Task StopAsync(CancellationToken cancellationToken) { // Deregistration handled automatically by ConsulHandler on app shutdown await Task.CompletedTask; } } // Query services from Consul (in client application) public class ServiceLocator(IConsulClient? consulClient) { public async Task LocateServiceAsync(string serviceName) { if (consulClient == null) { return null; } var services = await consulClient.Health.Service(serviceName, null, true); var service = services.Response.FirstOrDefault(); if (service != null) { return $"http://{service.Service.Address}:{service.Service.Port}"; } return null; } } ``` -------------------------------- ### Test Tenant-Starter Pricing API Source: https://docs.muonroi.com/docs/resources/samples/multi-tenant-saas Send a POST request to the tenant-starter pricing endpoint with JSON payload. ```bash curl -X POST http://localhost:5000/api/pricing/tenant-starter -H "Content-Type: application/json" -d '{"basePrice":20,"seatCount":30,"annualCommitment":false}' ``` -------------------------------- ### Incorrect Abstraction Reference to Infrastructure Source: https://docs.muonroi.com/docs/guides/ecosystem-coding-rules An example of an abstraction package incorrectly referencing infrastructure concerns (e.g., EntityFrameworkCore), violating MBB005. This creates circular dependencies and forces unnecessary package installations. ```csharp // ❌ Incorrect — triggers MBB005 // File: Muonroi.Orders.Abstractions.csproj (references EntityFrameworkCore) namespace Muonroi.Orders.Abstractions { public interface IOrderRepository { Task GetByIdAsync(int id, DbContext context); } } ``` -------------------------------- ### Register Experience Store (Qdrant or File) Source: https://docs.muonroi.com/docs/reference/packages/governance-experience Configures the experience store, specifying the type (Qdrant or File), Qdrant URL, vector size, and budget. Use this to set up persistence and semantic search capabilities. ```csharp services.AddExperienceStore(opts => { opts.StoreType = ExperienceStoreType.Qdrant; opts.QdrantUrl = "http://localhost:6334"; opts.VectorSize = 1536; // OpenAI embeddings dimension opts.Budget = new ExperienceBudgetConfig { }; }); ``` -------------------------------- ### Docker Compose for License Server and PostgreSQL Source: https://docs.muonroi.com/docs/operations/license-server-admin An example Docker Compose setup for deploying the license server alongside a PostgreSQL database. It configures environment variables for both services, including database connection details and license server settings. ```yaml services: postgres: image: postgres:16 environment: POSTGRES_DB: muonroi_licenses POSTGRES_USER: admin POSTGRES_PASSWORD: admin ports: - "5433:5432" volumes: - license-db:/var/lib/postgresql/data license-server: image: ghcr.io/muonroi/muonroi-license-server:develop depends_on: - postgres environment: ASPNETCORE_ENVIRONMENT: Production ASPNETCORE_URLS: http://+:8080 ConnectionStrings__LicenseDb: Host=postgres;Port=5432;Database=muonroi_licenses;Username=admin;Password=admin LicenseServer__AdminApiKey: replace-me LicenseServer__KeyRotationDays: "30" LicenseServer__RevocationRefreshMinutes: "15" LicenseServer__LicenseServerUrl: https://license.muonroi.internal LicenseServer__RevocationGraceHours: "24" ports: - "5010:8080" volumes: license-db: ``` -------------------------------- ### C# Rule Engine Core Usage Examples Source: https://docs.muonroi.com/docs/reference/packages/rule-engine-core Demonstrates minimal validation, dependent, and compensatable rules using the Rule Engine Core library. Includes setup for OrderContext, FactBag, and various rule implementations like IRule and ICompensatableRule. ```csharp using Muonroi.RuleEngine.Abstractions; // Minimal validation rule public class OrderAmountRule : IRule { public string Code => "order-amount"; public Task EvaluateAsync(OrderContext ctx, FactBag facts, CancellationToken ct) { if (ctx.Amount <= 0) return Task.FromResult(RuleResult.Failure("Amount must be positive")); facts.Set("order.amount.valid", true); return Task.FromResult(RuleResult.Passed()); } } // Rule depending on upstream result public class PersistOrderRule : IRule { private readonly IOrderRepository _repo; public PersistOrderRule(IOrderRepository repo) => _repo = repo; public string Code => "persist-order"; public IReadOnlyList DependsOn => ["order-amount"]; public RuleType Type => RuleType.Business; public Task EvaluateAsync(OrderContext ctx, FactBag facts, CancellationToken ct) { if (!facts.TryGet("order.amount.valid", out var valid) || !valid) return Task.FromResult(RuleResult.Failure("Order not valid")); return Task.FromResult(RuleResult.Passed()); } public Task ExecuteAsync(OrderContext context, CancellationToken ct) => _repo.SaveAsync(context.Order, ct); } // Compensatable rule (used with ExecutionMode.CompensateOnFailure) public class NotifyRule : ICompensatableRule { private readonly INotificationService _ns; public NotifyRule(INotificationService ns) => _ns = ns; public string Code => "notify"; public IReadOnlyList DependsOn => ["persist-order"]; public Task EvaluateAsync(OrderContext ctx, FactBag facts, CancellationToken ct) => Task.FromResult(RuleResult.Passed()); public Task ExecuteAsync(OrderContext ctx, CancellationToken ct) => _ns.SendConfirmationAsync(ctx.Order.Id, ct); // Called in reverse order if a later rule fails public Task CompensateAsync(OrderContext ctx, FactBag facts, CancellationToken ct) => _ns.SendCancellationAsync(ctx.Order.Id, ct); } ``` -------------------------------- ### Usage Example: Process Payment with Contextual Logging Source: https://docs.muonroi.com/docs/reference/packages/observability-diagnostics Demonstrates how to use IMLog for logging payment processing steps. Includes automatic context enrichment and manual property scoping for detailed logging. ```csharp using Muonroi.Logging.Abstractions; using Muonroi.Core.Abstractions.Context; public class PaymentService( IMLog log, ISystemExecutionContextAccessor contextAccessor) { public async Task ProcessPaymentAsync(string orderId, decimal amount) { // Automatic context enrichment (tenant, user, correlation ID) log.Info("Starting payment processing", new { OrderId = orderId, Amount = amount }); try { // Manual property scope using (log.BeginProperty("payment.order_id", orderId)) using (log.BeginProperty("payment.amount", amount)) { var result = await CallPaymentGatewayAsync(orderId, amount); log.Info("Payment successful", new { TransactionId = result.TransactionId, Status = result.Status }); return result; } } catch (Exception ex) { log.Error(ex, "Payment processing failed"); throw; } } } ``` -------------------------------- ### Install external-secrets-operator Helm Chart Source: https://docs.muonroi.com/docs/operations/secret-management Installs the external-secrets-operator using Helm. Ensure you have Helm installed and configured. ```bash helm repo add external-secrets https://charts.external-secrets.io helm install external-secrets external-secrets/external-secrets \ --namespace external-secrets-system \ --create-namespace ``` -------------------------------- ### Initialize Thin Client with npx Source: https://docs.muonroi.com/docs/experience-engine/getting-started Use this command to connect your workstation as a thin client to a shared Experience Engine instance running on a VPS. It saves configuration to ~/.experience/config.json. ```bash npx @muonroi/experience-engine init \ --server http://your-vps:8082 \ --token YOUR_TOKEN --yes ``` -------------------------------- ### Install muonroi-cli Globally via Bun Source: https://docs.muonroi.com/docs/cli/overview Install the CLI globally using Bun. Ensure Bun version 1.3 or later is installed. ```bash bun add -g muonroi-cli ``` -------------------------------- ### Install muonroi-cli Globally via NPM Source: https://docs.muonroi.com/docs/cli/overview Install the CLI globally using NPM. Ensure Node.js version 20 or later is installed. ```bash npm install -g muonroi-cli ``` -------------------------------- ### Database Configuration Example Source: https://docs.muonroi.com/docs/reference/packages/data-layer Configure database connection details, including the database type, connection string, and tenant-specific connection strings, within the application's configuration. ```json { "DatabaseConfigs": { "DbType": "SqlServer", "ConnectionString": "Server=localhost;Database=myapp;...", "IsFromSecret": false }, "TenantConnectionStrings": { "tenant1": "Server=localhost;Database=tenant1;...", "tenant2": "Server=localhost;Database=tenant2;..." }, "MultiTenant": { "Enabled": true, "DefaultTenantId": "default" } } ``` -------------------------------- ### Install Local Template Package Source: https://docs.muonroi.com/docs/getting-started/template-quickstart Installs a specific version of a local template package into the .NET environment. Use --force to overwrite existing installations. ```powershell dotnet new install "$workspace\LocalNuget\Muonroi.BaseTemplate..nupkg" --force ``` -------------------------------- ### Example Feature Flags Configuration Source: https://docs.muonroi.com/docs/resources/feature-flags This snippet shows a typical configuration for enabling or disabling various optional subsystems in the application. ```json "FeatureFlags": { "UseGrpc": true, "UseServiceDiscovery": true, "UseMessageBus": false, "UseBackgroundJobs": false, "UseEnsureCreatedFallback": true } ``` -------------------------------- ### Usage Example for Order Service Source: https://docs.muonroi.com/docs/reference/packages/data-layer Demonstrates how to use the IOrderRepository within a service to retrieve active orders. ```csharp public class OrderService(IOrderRepository orderRepo) { public async Task> GetActiveOrdersAsync() { return await orderRepo.GetActiveOrdersAsync(CancellationToken.None); } } ``` -------------------------------- ### Install RuleGen Source: https://docs.muonroi.com/docs/guides/rule-engine/rulegen-guide Installs RuleGen as a global .NET tool. ```bash dotnet tool install -g Muonroi.RuleGen ``` -------------------------------- ### Get Current Date Source: https://docs.muonroi.com/docs/guides/rule-engine/feel-reference Use the `today()` function to get the current date. ```FEEL today() ``` -------------------------------- ### Start Canary Rollout Source: https://docs.muonroi.com/docs/operations/control-plane-operator Starts a canary rollout for a specific workflow version. ```APIDOC ## POST /api/v1/control-plane/canary/{workflow}/{version}/start ### Description Starts a canary rollout for a specific workflow version. ### Method POST ### Endpoint /api/v1/control-plane/canary/{workflow}/{version}/start ### Parameters #### Path Parameters - **workflow** (string) - Required - The identifier of the workflow. - **version** (string) - Required - The version of the workflow to start canary for. ``` -------------------------------- ### Agent Harness Query and Command Example Source: https://docs.muonroi.com/docs/cli/guides/agent-harness This example demonstrates how an external agent can query the semantic tree for a specific dialog and then issue a command to press Enter. This is a core interaction pattern for driving TUI applications with the Agent Harness. ```text External agent (Claude, Codex, Gemini) │ driver.query("role=dialog name~='Recovery'") │ driver.press("Enter") ▼ WebSocket / fd 3-4 / Named pipe transport ▼ Semantic registry ── 30-60 Hz snapshot, hash-dedup ▼ TUI / React web app / Angular web app ``` -------------------------------- ### Get Current Date and Time Source: https://docs.muonroi.com/docs/guides/rule-engine/feel-reference Use the `now()` function to get the current date and time. ```FEEL now() ``` -------------------------------- ### License Server Deployment Topology Source: https://docs.muonroi.com/docs/operations/license-server-admin Illustrates the basic deployment topology for the license server, showing the flow from client activation to the license server and its PostgreSQL database. ```text client activation -> license server -> PostgreSQL ``` -------------------------------- ### Complete Program.cs Example for gRPC Multi-Site Source: https://docs.muonroi.com/docs/guides/site-profile/grpc-multi-site-patterns This example shows the complete registration order for a gRPC multi-site application, including site infrastructure, gRPC services, handlers, and dispatchers. ```csharp using MyProject.Core; using MyProject.Sites.Default; using MyProject.Sites.Bravo; var builder = WebApplication.CreateBuilder(args); // 1. Site infrastructure (must come first — discovers all site profiles) builder.Services.AddSiteInfrastructure(builder.Configuration, options => { options.SiteCodeAccessor = sp => sp.GetRequiredService().WorkContext?.SiteCode; options.SiteAssemblies = [ typeof(DefaultSiteProfile).Assembly, typeof(BravoSiteProfile).Assembly, ]; }); // 2. gRPC site services (interceptor + dispatch infrastructure) builder.Services.AddSiteGrpcServices(options => { options.MetadataKey = "x-site-code"; options.HttpHeaderFallbackKey = "x-site-code"; options.Required = true; }); // 3. Register site-specific gRPC handlers (keyed by site ID) builder.Services.AddSiteGrpcHandler("default"); builder.Services.AddSiteGrpcHandler(SiteIds.BRAVO); // 4. Register dispatcher infrastructure builder.Services.AddSiteGrpcDispatcher(); // 5. Per-request resolved services builder.Services.AddSiteResolvedService(); builder.Services.AddSiteResolvedService(); builder.Services.AddGrpc(); var app = builder.Build(); // 6. Map the shared-proto dispatcher app.MapGrpcService(); // 7. Map per-site proto services (auto-discovers [SiteGrpcService] types) app.MapSiteGrpcServices(typeof(BravoSiteProfile).Assembly); app.Run(); ``` -------------------------------- ### Start Canary Rollout Source: https://docs.muonroi.com/docs/operations/ruleset-governance-ops Initiates a canary rollout for a ruleset, starting with a specified percentage of tenants. ```APIDOC ## POST /api/v1/rule-engine/rulesets/order-approval/canary-start ### Description Starts a canary rollout for the 'order-approval' ruleset, targeting a specific percentage of tenants. ### Method POST ### Endpoint https://cp.truyentm.xyz/api/v1/rule-engine/rulesets/order-approval/canary-start ### Parameters #### Request Body - **version** (integer) - Required - The version of the ruleset to roll out. - **targetPercentage** (integer) - Required - The percentage of tenants to include in the canary rollout. - **actor** (string) - Required - The identifier of the actor initiating the rollout. ### Request Example { "version": 6, "targetPercentage": 10, "actor": "ops-team" } ### Response #### Success Response (200) - **rolloutId** (string) - The unique identifier for the rollout. - **version** (integer) - The ruleset version being rolled out. - **progress** (object) - Information about the rollout progress. - **percentage** (integer) - The current percentage of tenants affected. - **tenantsAffected** (integer) - The number of tenants affected. - **totalTenants** (integer) - The total number of tenants. - **status** (string) - The current status of the rollout (e.g., 'active'). - **startedAt** (string) - The timestamp when the rollout started (ISO 8601 format). #### Response Example { "rolloutId": "rollout-uuid-1234", "version": 6, "progress": { "percentage": 10, "tenantsAffected": 150, "totalTenants": 1500 }, "status": "active", "startedAt": "2026-03-20T15:00:00Z" } ``` -------------------------------- ### Domain Event Example Source: https://docs.muonroi.com/docs/reference/packages/messaging-integration An example of a concrete domain event inheriting from the base DomainEvent class. ```csharp public class OrderCreatedDomainEvent : DomainEvent { public string OrderId { get; init; } public string CustomerId { get; init; } } ``` -------------------------------- ### Mapping Configuration Example Source: https://docs.muonroi.com/docs/operations/migration-scripts Illustrates the hardcoded mapping array within the migration script, defining source to target transformations for packages, directories, and namespace bases. ```powershell @{ Package = "Muonroi.Core" Source = "External/Common/Constants" Target = "Constants" NamespaceBase = "Muonroi.Core.Constants" } ``` -------------------------------- ### Install cert-manager Source: https://docs.muonroi.com/docs/operations/kubernetes-deployment-guide Apply the cert-manager manifest to install it in your Kubernetes cluster. Ensure you are using a compatible version. ```bash kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml ``` -------------------------------- ### Quartz.NET Configuration Example Source: https://docs.muonroi.com/docs/operations/background-jobs-guide A full example of the Quartz.NET configuration in appsettings.json, detailing settings for data sources, job stores, thread pools, retry policies, dead-letter queues, and persistence. ```json { "QuartzConfigs": { "Datasource": { "ConnectionString": "${QUARTZ_CONNECTION_STRING}", "Provider": "SqlServer" }, "JobStore": { "Type": "JobStoreTX", "UseProperties": false, "MisfireThreshold": 60000, "DriverDelegateType": "Quartz.Impl.AdoJobStore.SqlServerDelegate" }, "ThreadPool": { "Type": "Quartz.Simpl.SimpleThreadPool", "ThreadCount": 10, "ThreadPriority": "Normal", "MakeThreadsDaemons": true }, "RetryPolicy": { "MaxRetries": 3, "RetryDelaySeconds": 30, "BackoffMultiplier": 2.0 }, "DeadLetterQueue": { "Enabled": true, "TableName": "qrtz_job_failures" }, "Persistence": { "SqlCommandTimeoutSeconds": 30, "ClusterCheckinIntervalMilliseconds": 7500 } } } ``` -------------------------------- ### UI Engine Runtime Initialization Source: https://docs.muonroi.com/docs/concepts/architecture-overview Illustrates the steps involved in initializing the UI engine runtime, including manifest parsing, map building, caching, and readiness for rendering. ```text MUiEngineRuntime.Create(manifest) ├─ Parse manifest schema (v1 or v2) ├─ Build 4 indexed maps (O(1) lookup): │ ├─ ComponentMap │ ├─ ExpressionEngineMap │ ├─ DataBindingMap │ └─ ValidationRuleMap ├─ TTL cache (60s) + ETag HTTP caching ├─ SignalR schema watcher for invalidation └─ Ready for rendering ``` -------------------------------- ### Install UI Engine Rule Components Source: https://docs.muonroi.com/docs/guides/ui-engine/impact-list-widget Install the necessary package for UI engine rule components. ```bash npm install @muonroi/ui-engine-rule-components ``` -------------------------------- ### Startup Verification Stages Source: https://docs.muonroi.com/docs/concepts/architecture-overview Illustrates the multi-stage verification process during application startup, including code integrity checks, anti-tampering detection, and license activation. ```text 1. CodeIntegrityVerifier ├─ SHA256 hash of loaded assemblies ├─ Compare against recorded hashes └─ Fail if tampering detected ↓ 2. AntiTamperDetector ├─ Detect debugger attachment ├─ Detect code profilers ├─ Detect runtime hooks / breakpoints └─ Degrade to Free tier on detection ↓ 3. LicenseActivator ├─ Read license key (file or env var) ├─ POST to LicenseServer /api/v1/activate ├─ Receive signed ActivationProof └─ Save proof to local file ```