Bundle: redb-tsak / src/redb.Tsak.CLI (src.redb.Tsak.CLI.txt), 18 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Index: https://redbase.app/src/dev-2026-12-06/redb-tsak/_index.txt ==== Path: redb-tsak/src/redb.Tsak.CLI/CliInvocation.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/CliInvocation.cs ---- using System.CommandLine; namespace redb.Tsak.CLI; /// /// One run of a command's action: the parse result it reads its options from, the token Ctrl+C cancels, and the exit /// code it sets (0 unless it sets another). Created by . /// internal sealed class CliInvocation(ParseResult parseResult, CancellationToken cancellationToken) { /// The parsed command line. public ParseResult ParseResult { get; } = parseResult; /// Cancelled by Ctrl+C. public CancellationToken CancellationToken { get; } = cancellationToken; /// The process exit code the command returns. public int ExitCode { get; set; } } Path: redb-tsak/src/redb.Tsak.CLI/Commands/DiagnosticsCommands.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Commands/DiagnosticsCommands.cs ---- using System.CommandLine; using redb.Tsak.CLI.Rendering; namespace redb.Tsak.CLI.Commands; /// /// CLI commands for diagnostics: lifecycle events, system dump, route dump, dashboard. /// public static class DiagnosticsCommands { public static Command Create() { var cmd = new Command("diagnostics", "Diagnostics, lifecycle events, and dashboard"); cmd.Add(BuildLifecycleCommand()); cmd.Add(BuildDumpCommand()); cmd.Add(BuildRouteDumpCommand()); cmd.Add(BuildDashboardCommand()); return cmd; } // tsak diagnostics lifecycle [--context X] [--route Y] [--type Z] [--since DT] [--limit N] [--watch] private static Command BuildLifecycleCommand() { var contextOpt = new Option("--context") { Description = "Filter by context name" }; var routeOpt = new Option("--route") { Description = "Filter by route identifier" }; var typeOpt = new Option("--type") { Description = "Filter by event type" }; var sinceOpt = new Option("--since") { Description = "Events since this timestamp (ISO 8601)" }; var limitOpt = new Option("--limit") { Description = "Maximum number of events to return" }; var lifecycleCmd = new Command("lifecycle", "Browse lifecycle audit events") { contextOpt, routeOpt, typeOpt, sinceOpt, limitOpt }; Program.Handle(lifecycleCmd, async ctx => { var context = ctx.ParseResult.GetValue(contextOpt); var route = ctx.ParseResult.GetValue(routeOpt); var type = ctx.ParseResult.GetValue(typeOpt); var since = ctx.ParseResult.GetValue(sinceOpt); var limit = ctx.ParseResult.GetValue(limitOpt); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await Program.RunOrWatch(ctx, async ct => { var events = await client.GetLifecycleEventsAsync(context, route, type, since, limit, ct); r.RenderTable(events, ("Timestamp", e => e.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")), ("Context", e => e.ContextName), ("Route", e => e.RouteId ?? "—"), ("Event", e => e.EventType.ToString()), ("Details", e => e.Details ?? "—")); }); }); return lifecycleCmd; } // tsak diagnostics dump private static Command BuildDumpCommand() { var dumpCmd = new Command("dump", "Full system diagnostic dump"); Program.Handle(dumpCmd, async ctx => { using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); var dump = await client.GetDiagnosticDumpAsync(ctx.CancellationToken); r.RenderDetail( ("Timestamp", dump.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")), ("Inflight", dump.InflightExchanges.Count.ToString()), ("Contexts", dump.Contexts.Count.ToString()), ("ActiveAlerts", dump.ActiveAlerts.Count.ToString()), ("RecentEvents", dump.RecentEvents.Count.ToString()), ("ThreadPool.Pending", dump.ThreadPool.PendingWorkItems.ToString()), ("ThreadPool.Workers", $"{dump.ThreadPool.WorkerThreadsAvailable}/{dump.ThreadPool.WorkerThreadsMax}"), ("ThreadPool.IO", $"{dump.ThreadPool.IoThreadsAvailable}/{dump.ThreadPool.IoThreadsMax}"), ("GC.Gen0", dump.GarbageCollector.Gen0Collections.ToString()), ("GC.Gen1", dump.GarbageCollector.Gen1Collections.ToString()), ("GC.Gen2", dump.GarbageCollector.Gen2Collections.ToString()), ("GC.Memory(MB)", dump.GarbageCollector.TotalMemoryMB.ToString("F1"))); if (dump.SystemMetrics is { } sm) RenderSystemMetrics(r, sm); if (dump.Contexts.Count > 0) { r.RenderTable(dump.Contexts, ("Context", c => c.ContextName), ("Started", c => c.IsStarted ? "Yes" : "No"), ("Routes", c => c.RouteCount.ToString()), ("Endpoints", c => c.EndpointCount.ToString()), ("Inflight", c => c.InflightCount.ToString())); } }); return dumpCmd; } // tsak diagnostics route private static Command BuildRouteDumpCommand() { var ctxArg = new Argument("context") { Description = "Context name" }; var routeArg = new Argument("routeId") { Description = "Route identifier" }; var routeCmd = new Command("route", "Diagnostic dump for a specific route") { ctxArg, routeArg }; Program.Handle(routeCmd, async ctx => { var name = ctx.ParseResult.GetValue(ctxArg); var routeId = ctx.ParseResult.GetValue(routeArg); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); var dump = await client.GetRouteDiagnosticsAsync(name, routeId, ctx.CancellationToken); r.RenderDetail( ("RouteId", dump.RouteId), ("FromUri", dump.FromUri), ("Status", dump.Status), ("AutoStart", dump.AutoStart ? "Yes" : "No"), ("Inflight", dump.InflightExchanges.Count.ToString()), ("RecentErrors", dump.RecentErrors.Count.ToString()), ("LifecycleEvents", dump.LifecycleHistory.Count.ToString())); if (dump.Metrics is { } m) { r.RenderDetail( ("Messages", m.MessagesProcessed.ToString()), ("Errors", m.Errors.ToString()), ("Rejected", m.Rejected.ToString()), ("Refused", m.Refused.ToString()), ("LastRefusal", m.LastRefusal ?? "—"), ("AvgProcessing(ms)", m.AvgProcessingMs.ToString("F1")), ("Throughput(/s)", m.ThroughputPerSecond.ToString("F2")), ("LastActivity", m.LastActivity?.ToString("HH:mm:ss") ?? "—")); } if (dump.InflightExchanges.Count > 0) { r.RenderTable(dump.InflightExchanges, ("ExchangeId", e => e.ExchangeId), ("RouteId", e => e.RouteId), ("Elapsed(ms)", e => e.ElapsedMs.ToString("F0")), ("Thread", e => e.ThreadId.ToString())); } }); return routeCmd; } // tsak diagnostics dashboard [--watch] private static Command BuildDashboardCommand() { var dashCmd = new Command("dashboard", "Live dashboard summary"); Program.Handle(dashCmd, async ctx => { using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await Program.RunOrWatch(ctx, async ct => { var snap = await client.GetDashboardAsync(ct); r.RenderDetail( ("Timestamp", snap.Timestamp.ToString("HH:mm:ss")), ("Contexts", $"{snap.RunningContexts}/{snap.TotalContexts}"), ("Inflight", snap.TotalInflight.ToString()), ("Alerts", snap.ActiveAlerts.Count.ToString())); if (snap.SystemMetrics is { } sm) RenderSystemMetrics(r, sm); if (snap.BusiestRoutes.Count > 0) { r.RenderTable(snap.BusiestRoutes, ("RouteId", rt => rt.RouteId), ("Status", rt => rt.Status), ("Msgs", rt => rt.MessagesProcessed.ToString()), ("Throughput", rt => rt.ThroughputPerSecond.ToString("F1")), ("Inflight", rt => rt.InflightCount.ToString()), ("Rejected", rt => rt.Rejected.ToString())); } if (snap.ErrorProneRoutes.Count > 0) { r.RenderTable(snap.ErrorProneRoutes, ("RouteId", rt => rt.RouteId), ("Errors", rt => rt.Errors.ToString()), ("LastError", rt => rt.LastError ?? "—"), ("LastErrorTime", rt => rt.LastErrorTime?.ToString("HH:mm:ss") ?? "—")); } // Shedding is not an error condition — a separate table, mirroring the web panel. if (snap.SheddingRoutes.Count > 0) { r.RenderTable(snap.SheddingRoutes, ("RouteId", rt => rt.RouteId), ("Rejected", rt => rt.Rejected.ToString()), ("Throughput", rt => rt.ThroughputPerSecond.ToString("F1")), ("Inflight", rt => rt.InflightCount.ToString())); } // Refusals are the callers' fault, neither errors nor shedding — their own table, as on the web panel. if (snap.RefusingRoutes.Count > 0) { r.RenderTable(snap.RefusingRoutes, ("RouteId", rt => rt.RouteId), ("Refused", rt => rt.Refused.ToString()), ("LastRefusal", rt => rt.LastRefusal ?? "—"), ("LastRefusalTime", rt => rt.LastRefusalTime?.ToString("HH:mm:ss") ?? "—")); } }); }); return dashCmd; } /// The system metrics of a dump or a dashboard, with the module contexts in memory and what to do about them. private static void RenderSystemMetrics(IOutputRenderer r, redb.Tsak.Contracts.SystemMetricsSnapshot sm) { r.RenderDetail( ("CPU(%)", sm.CpuPercent.ToString("F1")), ("Memory(MB)", sm.MemoryMB.ToString("F1")), ("Threads", sm.ThreadCount.ToString()), ("ModuleContexts", sm.ModuleContextsAlive.ToString()), ("OrphanedContexts", sm.OrphanedModuleContexts.ToString()), ("Notice", sm.ModuleContextsNotice ?? "—")); } } Path: redb-tsak/src/redb.Tsak.CLI/Commands/RouteCommands.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Commands/RouteCommands.cs ---- using System.CommandLine; using redb.Tsak.CLI.Rendering; namespace redb.Tsak.CLI.Commands; /// /// CLI commands for route management: list, get, start, stop, inflight, force-stop. /// public static class RouteCommands { public static Command Create() { var cmd = new Command("route", "Manage individual routes within contexts"); var ctxArg = new Argument("context") { Description = "Context name" }; // tsak route list var listCtxArg = new Argument("context") { Description = "Context name" }; var listCmd = new Command("list", "List routes in a context") { listCtxArg }; Program.Handle(listCmd, async ctx => { var name = ctx.ParseResult.GetValue(listCtxArg); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await Program.RunOrWatch(ctx, async ct => { var routes = await client.ListRoutesAsync(name, ct); r.RenderTable(routes, ("RouteId", rt => rt.RouteId), ("FromUri", rt => rt.FromUri), ("Status", rt => rt.Status), ("Inflight", rt => rt.InflightCount.ToString()), ("AutoStart", rt => rt.AutoStart ? "Yes" : "No")); }); }); // tsak route get var getCtxArg = new Argument("context") { Description = "Context name" }; var getRouteArg = new Argument("routeId") { Description = "Route identifier" }; var getCmd = new Command("get", "Get route details") { getCtxArg, getRouteArg }; Program.Handle(getCmd, async ctx => { var name = ctx.ParseResult.GetValue(getCtxArg); var routeId = ctx.ParseResult.GetValue(getRouteArg); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); var detail = await client.GetRouteAsync(name, routeId, ctx.CancellationToken); r.RenderDetail( ("RouteId", detail.RouteId), ("FromUri", detail.FromUri), ("Status", detail.Status), ("AutoStart", detail.AutoStart ? "Yes" : "No"), ("Inflight", detail.InflightCount.ToString()), ("Endpoints", detail.Endpoints.Length.ToString())); }); // tsak route start var startCtxArg = new Argument("context") { Description = "Context name" }; var startRouteArg = new Argument("routeId") { Description = "Route identifier" }; var startCmd = new Command("start", "Start a route") { startCtxArg, startRouteArg }; Program.Handle(startCmd, async ctx => { var name = ctx.ParseResult.GetValue(startCtxArg); var routeId = ctx.ParseResult.GetValue(startRouteArg); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); var result = await client.StartRouteAsync(name, routeId, ctx.CancellationToken); r.Success($"Route '{result.RouteId}' → {result.Status}"); }); // tsak route stop [--timeout N] var stopCtxArg = new Argument("context") { Description = "Context name" }; var stopRouteArg = new Argument("routeId") { Description = "Route identifier" }; var timeoutOpt = new Option("--timeout") { Description = "Drain timeout in seconds" }; var stopCmd = new Command("stop", "Stop a route with graceful drain") { stopCtxArg, stopRouteArg, timeoutOpt }; Program.Handle(stopCmd, async ctx => { var name = ctx.ParseResult.GetValue(stopCtxArg); var routeId = ctx.ParseResult.GetValue(stopRouteArg); var timeout = ctx.ParseResult.GetValue(timeoutOpt); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); var result = await client.StopRouteAsync(name, routeId, timeout, ctx.CancellationToken); r.Success($"Route '{result.RouteId}' → {result.Status}"); }); // tsak route inflight [routeId] var inflightCtxArg = new Argument("context") { Description = "Context name" }; var inflightRouteArg = new Argument("routeId") { Arity = ArgumentArity.ZeroOrOne, DefaultValueFactory = _ => null, Description = "Route identifier (optional, all routes if omitted)", }; var inflightCmd = new Command("inflight", "Browse in-flight exchanges") { inflightCtxArg, inflightRouteArg }; Program.Handle(inflightCmd, async ctx => { var name = ctx.ParseResult.GetValue(inflightCtxArg); var routeId = ctx.ParseResult.GetValue(inflightRouteArg); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await Program.RunOrWatch(ctx, async ct => { var exchanges = routeId is not null ? await client.GetRouteInflightAsync(name, routeId, ct) : await client.GetContextInflightAsync(name, ct); r.RenderTable(exchanges, ("ExchangeId", e => e.ExchangeId), ("RouteId", e => e.RouteId), ("Elapsed(ms)", e => e.ElapsedMs.ToString("F0")), ("Thread", e => e.ThreadId.ToString()), ("From", e => e.FromEndpoint ?? "—")); }); }); // tsak route force-stop [--yes] var forceCtxArg = new Argument("context") { Description = "Context name" }; var forceRouteArg = new Argument("routeId") { Description = "Route identifier" }; var forceCmd = new Command("force-stop", "Force-stop a route (no drain)") { forceCtxArg, forceRouteArg }; Program.Handle(forceCmd, async ctx => { var name = ctx.ParseResult.GetValue(forceCtxArg); var routeId = ctx.ParseResult.GetValue(forceRouteArg); Program.ConfirmOrAbort(ctx, $"Force-stop route '{routeId}' in context '{name}'?"); using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); var result = await client.ForceStopRouteAsync(name, routeId, ctx.CancellationToken); r.Success($"Route '{result.RouteId}' → {result.Status} (force-stopped)"); }); cmd.Add(listCmd); cmd.Add(getCmd); cmd.Add(startCmd); cmd.Add(stopCmd); cmd.Add(inflightCmd); cmd.Add(forceCmd); return cmd; } } Path: redb-tsak/src/redb.Tsak.CLI/Commands/WatchdogCommands.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Commands/WatchdogCommands.cs ---- using System.CommandLine; using redb.Tsak.CLI.Rendering; namespace redb.Tsak.CLI.Commands; /// /// CLI commands for watchdog management: status, alerts, enable, disable. /// public static class WatchdogCommands { public static Command Create() { var cmd = new Command("watchdog", "Manage route watchdog service"); // tsak watchdog status [--watch] var statusCmd = new Command("status", "Show watchdog status"); Program.Handle(statusCmd, async ctx => { using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await Program.RunOrWatch(ctx, async ct => { var state = await client.GetWatchdogStatusAsync(ct); r.RenderDetail( ("Enabled", state.Enabled ? "Yes" : "No"), ("LastCheck", state.LastCheckAt.ToString("yyyy-MM-dd HH:mm:ss")), ("SuspectedExchanges", state.SuspectedExchanges.ToString()), ("HungExchanges", state.HungExchanges.ToString()), ("AutoRestarts", state.AutoRestartsPerformed.ToString()), ("ActiveAlerts", state.ActiveAlerts.Count.ToString())); }); }); // tsak watchdog alerts [--watch] var alertsCmd = new Command("alerts", "List active watchdog alerts"); Program.Handle(alertsCmd, async ctx => { using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await Program.RunOrWatch(ctx, async ct => { var alerts = await client.GetWatchdogAlertsAsync(ct); r.RenderTable(alerts, ("ExchangeId", a => a.ExchangeId), ("RouteId", a => a.RouteId), ("Context", a => a.ContextName), ("Level", a => a.Level), ("DetectedAt", a => a.DetectedAt.ToString("HH:mm:ss")), ("Elapsed(s)", a => a.ElapsedSeconds.ToString("F1"))); }); }); // tsak watchdog enable var enableCmd = new Command("enable", "Enable the watchdog service"); Program.Handle(enableCmd, async ctx => { using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await client.EnableWatchdogAsync(ctx.CancellationToken); r.Success("Watchdog enabled."); }); // tsak watchdog disable var disableCmd = new Command("disable", "Disable the watchdog service"); Program.Handle(disableCmd, async ctx => { using var client = Program.CreateClient(ctx); var r = Program.CreateRenderer(ctx); await client.DisableWatchdogAsync(ctx.CancellationToken); r.Success("Watchdog disabled."); }); cmd.Add(statusCmd); cmd.Add(alertsCmd); cmd.Add(enableCmd); cmd.Add(disableCmd); return cmd; } } Path: redb-tsak/src/redb.Tsak.CLI/Config/ConnectionProfile.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Config/ConnectionProfile.cs ---- namespace redb.Tsak.CLI.Config; /// /// A named connection profile for a Tsak runtime instance. /// public sealed class ConnectionProfile { /// Profile name (used as file name without extension). public required string Name { get; set; } /// Base URL of the Tsak runtime API. public required string Url { get; set; } /// API key for authentication. public string? ApiKey { get; set; } } Path: redb-tsak/src/redb.Tsak.CLI/Config/ProfileManager.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Config/ProfileManager.cs ---- using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; namespace redb.Tsak.CLI.Config; /// /// Manages connection profiles stored as YAML files in ~/.tsak/profiles/. /// public sealed class ProfileManager { private static readonly string DefaultBaseDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".tsak"); private readonly string _profileDir; private readonly string _activeFilePath; /// /// Initializes the profile manager with the default base directory (~/.tsak/). /// public ProfileManager() : this(DefaultBaseDir) { } /// /// Initializes the profile manager with a custom base directory (for testing). /// /// Base directory containing profiles/ and active marker. public ProfileManager(string baseDir) { _profileDir = Path.Combine(baseDir, "profiles"); _activeFilePath = Path.Combine(baseDir, "active"); } private static readonly IDeserializer YamlReader = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .IgnoreUnmatchedProperties() .Build(); private static readonly ISerializer YamlWriter = new SerializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); /// /// Resolves the effective connection settings. /// Priority: explicit flags > environment variables > active profile. /// /// Profile name from --profile flag. /// URL from --url flag. /// API key from --key flag. /// Resolved profile, or null if nothing is configured. public ConnectionProfile? Resolve(string? profileName, string? url, string? apiKey) { // Start from the named or active profile ConnectionProfile? profile = null; if (profileName is not null) profile = Load(profileName); else profile = LoadActive(); // Environment variables override profile var envUrl = Environment.GetEnvironmentVariable("TSAK_URL"); var envKey = Environment.GetEnvironmentVariable("TSAK_API_KEY"); var resolvedUrl = url ?? envUrl ?? profile?.Url; var resolvedKey = apiKey ?? envKey ?? profile?.ApiKey; if (resolvedUrl is null) return null; return new ConnectionProfile { Name = profile?.Name ?? "inline", Url = resolvedUrl, ApiKey = resolvedKey }; } /// /// Lists all saved profiles. /// public IReadOnlyList List() { if (!Directory.Exists(_profileDir)) return []; var files = Directory.GetFiles(_profileDir, "*.yml"); var profiles = new List(files.Length); foreach (var file in files) { var name = Path.GetFileNameWithoutExtension(file); var loaded = Load(name); if (loaded is not null) profiles.Add(loaded); } return profiles; } /// /// Loads a profile by name. /// public ConnectionProfile? Load(string name) { var path = GetProfilePath(name); if (!File.Exists(path)) return null; var yaml = File.ReadAllText(path); var data = YamlReader.Deserialize(yaml); return new ConnectionProfile { Name = name, Url = data.Url, ApiKey = data.ApiKey }; } /// /// Saves a profile to disk. /// public void Save(ConnectionProfile profile) { Directory.CreateDirectory(_profileDir); var data = new ProfileData { Url = profile.Url, ApiKey = profile.ApiKey }; var yaml = YamlWriter.Serialize(data); File.WriteAllText(GetProfilePath(profile.Name), yaml); } /// /// Deletes a profile. /// public bool Delete(string name) { var path = GetProfilePath(name); if (!File.Exists(path)) return false; File.Delete(path); // If it was the active profile, remove the active marker if (GetActiveName() == name) DeleteActiveMarker(); return true; } /// /// Sets the active profile. /// public void SetActive(string name) { if (!File.Exists(GetProfilePath(name))) throw new FileNotFoundException($"Profile '{name}' does not exist."); Directory.CreateDirectory(Path.GetDirectoryName(_activeFilePath)!); File.WriteAllText(_activeFilePath, name); } /// /// Gets the name of the active profile. /// public string? GetActiveName() { return File.Exists(_activeFilePath) ? File.ReadAllText(_activeFilePath).Trim() : null; } private ConnectionProfile? LoadActive() { var name = GetActiveName(); return name is not null ? Load(name) : null; } private void DeleteActiveMarker() { if (File.Exists(_activeFilePath)) File.Delete(_activeFilePath); } private string GetProfilePath(string name) => Path.Combine(_profileDir, $"{name}.yml"); /// /// Internal YAML shape for profile files. /// private sealed class ProfileData { public string Url { get; set; } = string.Empty; public string? ApiKey { get; set; } } } Path: redb-tsak/src/redb.Tsak.CLI/MissingArguments.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/MissingArguments.cs ---- using System.CommandLine; using System.CommandLine.Help; using System.CommandLine.Parsing; namespace redb.Tsak.CLI; /// /// The parse errors of a command line whose only problem is required arguments left out. System.CommandLine reports /// one error per missing argument, but its text names the command and not the argument ("Required argument missing for /// command: 'get'."), so a command with two arguments printed the same line twice /// (https://github.com/dotnet/command-line-api/pull/1993 would name the argument; not merged in 2.0). These errors are /// reported here, one line per argument with its name, followed by the help of the command as the library does. Any /// other parse error (an unknown command, a bad value, a missing required option) goes to the library's own /// , which keeps its "Did you mean" suggestions. /// internal static class MissingArguments { /// /// The arguments left out, when every parse error of is a missing required argument; /// empty otherwise (no error, or another kind of error among them). /// public static IReadOnlyList Of(ParseResult parseResult) { if (parseResult.Errors.Count == 0) return []; var missing = new List(); foreach (var error in parseResult.Errors) { if (error.SymbolResult is not ArgumentResult argument || argument.Tokens.Count >= argument.Argument.Arity.MinimumNumberOfValues) return []; missing.Add(argument); } return missing; } /// /// Writes one line per missing argument to the error output, then the help of the command, and returns the exit /// code of a parse error (1). /// public static int Report(ParseResult parseResult, IReadOnlyList missing) { var error = parseResult.InvocationConfiguration.Error; foreach (var argument in missing) error.WriteLine($"Required argument '<{argument.Argument.Name}>' is missing for command '{CommandPath(argument)}'."); error.WriteLine(); new HelpAction().Invoke(parseResult); return 1; } /// The command the argument belongs to, as typed: route get, without the root command. private static string CommandPath(ArgumentResult argument) { var names = new Stack(); for (var result = argument.Parent as CommandResult; result is { Parent: not null }; result = result.Parent as CommandResult) names.Push(result.Command.Name); return string.Join(" ", names); } } Path: redb-tsak/src/redb.Tsak.CLI/Program.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Program.cs ---- using System.CommandLine; using System.Globalization; using redb.Tsak.Client; using redb.Tsak.Contracts; using redb.Tsak.CLI.Config; using redb.Tsak.CLI.Rendering; namespace redb.Tsak.CLI; /// /// Entry point for the tsak CLI tool. /// Noun-verb style: tsak context list, tsak scheduler status, etc. /// public static class Program { // ── Global options ────────────────────────────────────────────── // Recursive: every subcommand takes them, as global options did before System.CommandLine 2.0. private static readonly Option ProfileOption = new("--profile", "-p") { Description = "Connection profile name", Recursive = true, }; private static readonly Option UrlOption = new("--url", "-u") { Description = "Tsak runtime URL (overrides profile)", Recursive = true, }; private static readonly Option KeyOption = new("--key", "-k") { Description = "API key (overrides profile)", Recursive = true, }; private static readonly Option OutputOption = new("--output", "-o") { DefaultValueFactory = _ => OutputFormat.Table, Description = "Output format: table | json | quiet", Recursive = true, }; private static readonly Option NoColorOption = new("--no-color") { Description = "Disable colored output", Recursive = true, }; private static readonly Option YesOption = new("--yes", "-y") { Description = "Skip confirmation prompts", Recursive = true, }; private static readonly Option WatchOption = new("--watch") { Description = "Poll repeatedly (Ctrl+C to stop)", Recursive = true, }; private static readonly Option IntervalOption = new("--interval") { DefaultValueFactory = _ => 5, Description = "Polling interval in seconds (used with --watch)", Recursive = true, }; private static readonly Option TimeoutOption = new("--timeout") { Description = "HTTP request timeout in seconds (default: 5). Useful for slow operations like diagnostics dump, force-stop, module install.", Recursive = true, }; public static async Task Main(string[] args) { // System.CommandLine ships localized resources and picks them by the OS UI language; the CLI // speaks English everywhere, so help, usage and parse errors match the rest of its output. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; var root = new RootCommand("tsak — CLI for redb.Tsak runtime management"); root.Add(ProfileOption); root.Add(UrlOption); root.Add(KeyOption); root.Add(OutputOption); root.Add(NoColorOption); root.Add(YesOption); root.Add(WatchOption); root.Add(IntervalOption); root.Add(TimeoutOption); // ── Register command groups ───────────────────────────────── root.Add(BuildSystemCommand()); root.Add(BuildContextCommand()); root.Add(BuildModuleCommand()); root.Add(BuildSchedulerCommand()); root.Add(BuildClusterCommand()); root.Add(BuildLogCommand()); root.Add(BuildAuditCommand()); root.Add(BuildDlqCommand()); root.Add(BuildAuthCommand()); root.Add(BuildProfileCommand()); root.Add(Commands.RouteCommands.Create()); root.Add(Commands.WatchdogCommands.Create()); root.Add(Commands.DiagnosticsCommands.Create()); // Help, version, parse errors and Ctrl+C are the library's defaults; a command's exception is handled by // Handle, which sets the exit code the way the CLI always has. Required arguments left out are reported by // name (MissingArguments): the library's text names only the command. var parseResult = root.Parse(args); if (MissingArguments.Of(parseResult) is { Count: > 0 } missing) return MissingArguments.Report(parseResult, missing); return await parseResult.InvokeAsync(); } // ── Helpers ───────────────────────────────────────────────────── /// /// Sets the action of : runs with the parse result and the /// Ctrl+C token, turns an exception into a message and an exit code (), and returns /// the exit code the action set. /// internal static void Handle(Command command, Func action) { command.SetAction(async (parseResult, cancellationToken) => { var invocation = new CliInvocation(parseResult, cancellationToken); try { await action(invocation); } catch (Exception ex) { HandleException(ex, invocation); } return invocation.ExitCode; }); } /// A synchronous action, otherwise as . internal static void Handle(Command command, Action action) => Handle(command, invocation => { action(invocation); return Task.CompletedTask; }); /// /// Resolves connection settings and creates an API client from the invocation context. /// internal static TsakApiClient CreateClient(CliInvocation ctx) { var profile = new ProfileManager().Resolve( ctx.ParseResult.GetValue(ProfileOption), ctx.ParseResult.GetValue(UrlOption), ctx.ParseResult.GetValue(KeyOption)); if (profile is null) { Console.Error.WriteLine("No connection configured. Use --url, set TSAK_URL, or create a profile."); ctx.ExitCode = 1; throw new OperationCanceledException(); } var timeoutSeconds = ctx.ParseResult.GetValue(TimeoutOption); var timeout = timeoutSeconds is > 0 ? TimeSpan.FromSeconds(timeoutSeconds.Value) : (TimeSpan?)null; return new TsakApiClient(profile.Url, profile.ApiKey, timeout); } /// /// Creates the appropriate output renderer from the invocation context. /// internal static IOutputRenderer CreateRenderer(CliInvocation ctx) { var format = ctx.ParseResult.GetValue(OutputOption); var noColor = ctx.ParseResult.GetValue(NoColorOption); return RendererFactory.Create(format, noColor); } /// /// Asks for confirmation before a destructive action. Aborts if declined. /// Skipped when --yes is set or output format is not Table (scripts). /// internal static void ConfirmOrAbort(CliInvocation ctx, string prompt) { var yes = ctx.ParseResult.GetValue(YesOption); var format = ctx.ParseResult.GetValue(OutputOption); if (yes || format != OutputFormat.Table) return; Console.Write($"{prompt} [y/N]: "); var answer = Console.ReadLine()?.Trim(); if (!string.Equals(answer, "y", StringComparison.OrdinalIgnoreCase) && !string.Equals(answer, "yes", StringComparison.OrdinalIgnoreCase)) { Console.Error.WriteLine("Aborted."); throw new OperationCanceledException(); } } /// /// Runs an async action once or in a polling loop if --watch is set. /// internal static async Task RunOrWatch(CliInvocation ctx, Func action) { var watch = ctx.ParseResult.GetValue(WatchOption); var interval = ctx.ParseResult.GetValue(IntervalOption); var ct = ctx.CancellationToken; if (!watch) { await action(ct); return; } Console.WriteLine($"Every {interval}s — Ctrl+C to stop"); Console.WriteLine(); while (!ct.IsCancellationRequested) { try { Console.Write($"\x1b[2K[{DateTime.Now:HH:mm:ss}] "); await action(ct); Console.WriteLine(); await Task.Delay(TimeSpan.FromSeconds(interval), ct); } catch (OperationCanceledException) { break; } } } /// /// Global exception handler for the CLI. /// /// /// Writes a PEM key. fails rather than replace a file that appeared after the /// check for existing keys; replaces it (--force). /// private static void WriteKey(string path, string pem, FileMode mode) { using var stream = new FileStream(path, mode, FileAccess.Write); using var writer = new StreamWriter(stream); writer.Write(pem); } private static void HandleException(Exception ex, CliInvocation ctx) { if (ex is OperationCanceledException) return; var renderer = CreateRenderer(ctx); if (ex is ApiException apiEx) { renderer.Error($"[{apiEx.StatusCode}] {apiEx.Message}"); ctx.ExitCode = 1; } else { renderer.Error(ex.Message); ctx.ExitCode = 2; } } // ═══════════════════════════════════════════════════════════════ // SYSTEM // ═══════════════════════════════════════════════════════════════ /// The exit code of tsak system deploy-advice for a cold deploy; 1 and 2 are errors. public const int ColdDeployExitCode = 3; private static Command BuildSystemCommand() { var cmd = new Command("system", "System health, metrics, and info"); // tsak system health [--watch] [--interval N] var healthCmd = new Command("health", "Show system health status"); Handle(healthCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); await RunOrWatch(ctx, async ct => { var health = await client.GetHealthAsync(ct); r.RenderDetail( ("Status", health.Status.ToString()), ("Description", health.Description), ("Timestamp", health.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"))); if (health.Checks is { Count: > 0 }) { r.RenderTable(health.Checks, ("Check", kv => kv.Key), ("Status", kv => kv.Value.ToString()), ("Detail", kv => health.Details.GetValueOrDefault(kv.Key) ?? "")); } }); }); // tsak system metrics [--watch] [--interval N] var metricsCmd = new Command("metrics", "Show system metrics"); Handle(metricsCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); await RunOrWatch(ctx, async ct => { var m = await client.GetMetricsAsync(ct); if (!m.Available || m.Latest is null) { r.Error("Metrics not available."); return; } r.RenderDetail( ("CPU Process", $"{m.Latest.Cpu.ProcessUsage:F1}%"), ("CPU System", $"{m.Latest.Cpu.SystemUsage:F1}%"), ("Memory (MB)", $"{m.Latest.Memory.WorkingSetMB:F1}"), ("Active Threads", m.Latest.Threading.ActiveThreads.ToString()), ("GC Gen0/1/2", $"{m.Latest.GarbageCollector.Gen0Collections}/{m.Latest.GarbageCollector.Gen1Collections}/{m.Latest.GarbageCollector.Gen2Collections}"), ("GC Total (MB)", $"{m.Latest.GarbageCollector.TotalMemoryMB:F1}"), ("Stored Points", m.StoredPoints?.ToString() ?? ""), ("Timestamp", m.Latest.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"))); }); }); // tsak system info var infoCmd = new Command("info", "Show system information"); Handle(infoCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var info = await client.GetInfoAsync(ctx.CancellationToken); r.RenderDetail( ("Version", info.Version), ("Started", info.StartedAt.ToString("yyyy-MM-dd HH:mm:ss")), ("Uptime", info.Uptime), ("Contexts", info.ContextCount.ToString()), ("Modules", info.ModuleCount.ToString()), ("Machine", info.MachineName), ("CPUs", info.ProcessorCount.ToString()), ("Memory (MB)", $"{info.WorkingSetMb:F1}"), ("Module contexts", info.ModuleContextsAlive.ToString()), ("Orphaned contexts", $"{info.OrphanedModuleContexts} (limit {info.MaxOrphanedModuleContexts})"), ("Notice", info.ModuleContextsNotice ?? "—")); }); var configCmd = new Command("config", "Show effective (merged, redacted) configuration"); Handle(configCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var cfg = await client.GetConfigAsync(ctx.CancellationToken); if (!cfg.Available) { r.Error("Configuration is not available."); ctx.ExitCode = 1; return; } r.RenderTable(cfg.Values, ("Key", kv => kv.Key), ("Value", kv => kv.Value ?? "—")); }); // tsak system deploy-advice [--cluster]: exit code 0 hot-swap, 3 cold-deploy (1 and 2 stay errors) var clusterOpt = new Option("--cluster") { Description = "Ask every alive node of the cluster through this one" }; var deployCmd = new Command("deploy-advice", $"Hot swap a new package or deploy it cold? Exit code 0: {DeployVerdicts.HotSwap}, {ColdDeployExitCode}: {DeployVerdicts.ColdDeploy}") { clusterOpt }; Handle(deployCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); IReadOnlyList nodes; string verdict; if (ctx.ParseResult.GetValue(clusterOpt)) { var cluster = await client.GetClusterDeployAdviceAsync(ctx.CancellationToken); (nodes, verdict) = (cluster.Nodes, cluster.Verdict); } else { var advice = await client.GetDeployAdviceAsync(ctx.CancellationToken); (nodes, verdict) = ([advice], advice.Verdict); } r.RenderTable(nodes, ("Node", n => n.NodeId), ("Verdict", n => n.Verdict), ("Reasons", n => n.Reasons.Count == 0 ? "—" : string.Join(", ", n.Reasons)), ("Orphaned", n => $"{n.OrphanedModuleContexts}/{n.MaxOrphanedModuleContexts}"), ("Contexts", n => n.ModuleContextsAlive.ToString()), ("WorkingSet(MB)", n => n.MaxWorkingSetMb is { } max ? $"{n.WorkingSetMb:F0}/{max:F0}" : $"{n.WorkingSetMb:F0}"), ("Collectible", n => n.Collectible ? "Yes" : "No")); ctx.ExitCode = verdict == DeployVerdicts.HotSwap ? 0 : ColdDeployExitCode; }); cmd.Add(healthCmd); cmd.Add(metricsCmd); cmd.Add(infoCmd); cmd.Add(configCmd); cmd.Add(deployCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // CONTEXT // ═══════════════════════════════════════════════════════════════ private static Command BuildContextCommand() { var cmd = new Command("context", "Manage route contexts"); // tsak context list var listCmd = new Command("list", "List all contexts"); Handle(listCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var contexts = await client.ListContextsAsync(ctx.CancellationToken); r.RenderTable(contexts, ("Name", c => c.Name), ("Status", c => c.Status), ("Endpoints", c => c.EndpointCount.ToString())); }); // tsak context get var nameArg = new Argument("name") { Description = "Context name" }; var getCmd = new Command("get", "Get context details") { nameArg }; Handle(getCmd, async (ctx) => { var name = ctx.ParseResult.GetValue(nameArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var detail = await client.GetContextAsync(name, ctx.CancellationToken); r.RenderDetail( ("Name", detail.Name), ("Status", detail.Status), ("Endpoints", detail.EndpointCount.ToString()), ("AutoStart", detail.AutoStart ? "Yes" : "No")); }); // tsak context start var startArg = new Argument("name") { Description = "Context name" }; var startCmd = new Command("start", "Start a context") { startArg }; Handle(startCmd, async ctx => { var name = ctx.ParseResult.GetValue(startArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.StartContextAsync(name, ctx.CancellationToken); r.Success($"Context '{result.Name}' → {result.Status}"); }); // tsak context stop var stopArg = new Argument("name") { Description = "Context name" }; var stopCmd = new Command("stop", "Stop a context") { stopArg }; Handle(stopCmd, async ctx => { var name = ctx.ParseResult.GetValue(stopArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.StopContextAsync(name, ctx.CancellationToken); r.Success($"Context '{result.Name}' → {result.Status}"); }); // tsak context restart var restartArg = new Argument("name") { Description = "Context name" }; var restartCmd = new Command("restart", "Restart a context") { restartArg }; Handle(restartCmd, async ctx => { var name = ctx.ParseResult.GetValue(restartArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.RestartContextAsync(name, ctx.CancellationToken); r.Success($"Context '{result.Name}' → {result.Status}"); }); // tsak context remove [--yes] var removeArg = new Argument("name") { Description = "Context name" }; var removeCmd = new Command("remove", "Remove a context") { removeArg }; Handle(removeCmd, async ctx => { var name = ctx.ParseResult.GetValue(removeArg); ConfirmOrAbort(ctx, $"Remove context '{name}'?"); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.RemoveContextAsync(name, ctx.CancellationToken); r.Success($"Context '{result.Name}' removed."); }); cmd.Add(listCmd); cmd.Add(getCmd); cmd.Add(startCmd); cmd.Add(stopCmd); cmd.Add(restartCmd); cmd.Add(removeCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // MODULE // ═══════════════════════════════════════════════════════════════ private static Command BuildModuleCommand() { var cmd = new Command("module", "Manage runtime modules"); // tsak module list var listCmd = new Command("list", "List all modules"); Handle(listCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var modules = await client.ListModulesAsync(ctx.CancellationToken); r.RenderTable(modules, ("Name", m => m.ModuleName), ("Version", m => m.Version ?? "—"), ("Status", m => m.Status), ("Dependencies", m => m.Dependencies.Length > 0 ? string.Join(", ", m.Dependencies) : "—")); }); // tsak module get var nameArg = new Argument("name") { Description = "Module name" }; var getCmd = new Command("get", "Get module details") { nameArg }; Handle(getCmd, async ctx => { var name = ctx.ParseResult.GetValue(nameArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var mod = await client.GetModuleAsync(name, ctx.CancellationToken); r.RenderDetail( ("Name", mod.ModuleName), ("Version", mod.Version ?? "—"), ("Description", mod.Description ?? "—"), ("Status", mod.Status), ("Can Initialize", mod.CanInitialize ? "Yes" : "No"), ("Dependencies", mod.Dependencies.Length > 0 ? string.Join(", ", mod.Dependencies) : "—")); }); // tsak module remove [--yes] var removeArg = new Argument("name") { Description = "Module name" }; var removeCmd = new Command("remove", "Remove a module") { removeArg }; Handle(removeCmd, async ctx => { var name = ctx.ParseResult.GetValue(removeArg); ConfirmOrAbort(ctx, $"Remove module '{name}'?"); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.RemoveModuleAsync(name, ctx.CancellationToken); r.Success($"Module '{result.ModuleName}' removed."); }); // tsak module keygen --out [--force] → writes .key (private) + .pub (public) // The command creates a secret, so where it goes is always the caller's choice (no default prefix), and an // existing key is never replaced unless asked to: losing a signing key strands every package signed with it. var keygenOut = new Option("--out") { Description = "Output file prefix: writes .key (private) and .pub (public)", Required = true, }; var keygenForce = new Option("--force") { Description = "Overwrite an existing key pair with that prefix" }; var keygenCmd = new Command("keygen", "Generate an ECDSA signing key pair for module packages") { keygenOut, keygenForce }; Handle(keygenCmd, ctx => { var prefix = ctx.ParseResult.GetValue(keygenOut)!; var force = ctx.ParseResult.GetValue(keygenForce); var r = CreateRenderer(ctx); var keyPath = Path.GetFullPath(prefix + ".key"); var pubPath = Path.GetFullPath(prefix + ".pub"); var existing = new[] { keyPath, pubPath }.Where(File.Exists).ToList(); if (existing.Count > 0 && !force) { r.Error($"Not overwriting {string.Join(" and ", existing)}. Choose another --out, or pass --force to " + "replace the key pair (packages signed with the old key then no longer verify)."); ctx.ExitCode = 1; return; } using var ecdsa = System.Security.Cryptography.ECDsa.Create( System.Security.Cryptography.ECCurve.NamedCurves.nistP256); var mode = force ? FileMode.Create : FileMode.CreateNew; WriteKey(keyPath, ecdsa.ExportPkcs8PrivateKeyPem(), mode); WriteKey(pubPath, ecdsa.ExportSubjectPublicKeyInfoPem(), mode); r.Success($"Wrote {keyPath} (PRIVATE: keep secret, use to sign) and {pubPath} " + $"(public: configure on the node as Tsak:Modules:Signature:PublicKeyPath)."); }); // tsak module sign --key → writes (base64) var signFileArg = new Argument("file") { Description = "Path to the .tpkg to sign" }; var signKey = new Option("--key") { Description = "Path to the PEM private key", Required = true }; var signCmd = new Command("sign", "Sign a .tpkg with a private key (produces .tpkg.sig)") { signFileArg, signKey }; Handle(signCmd, ctx => { var file = ctx.ParseResult.GetValue(signFileArg); var keyPath = ctx.ParseResult.GetValue(signKey)!; var r = CreateRenderer(ctx); var data = File.ReadAllBytes(file); var pem = File.ReadAllText(keyPath); byte[] sig; try { using var ecdsa = System.Security.Cryptography.ECDsa.Create(); ecdsa.ImportFromPem(pem); sig = ecdsa.SignData(data, System.Security.Cryptography.HashAlgorithmName.SHA256); } catch { using var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportFromPem(pem); sig = rsa.SignData(data, System.Security.Cryptography.HashAlgorithmName.SHA256, System.Security.Cryptography.RSASignaturePadding.Pkcs1); } var sigPath = file + ".sig"; File.WriteAllText(sigPath, Convert.ToBase64String(sig)); r.Success($"Wrote {sigPath}. Deploy the .tpkg and .tpkg.sig together."); }); // tsak module deploy [--sig ] → upload to the node var deployFileArg = new Argument("file") { Description = "Path to the .tpkg to deploy" }; var deploySig = new Option("--sig") { Description = "Path to the .tpkg.sig (defaults to .sig if present)" }; var deployCmd = new Command("deploy", "Upload a .tpkg to the node for hot-deploy") { deployFileArg, deploySig }; Handle(deployCmd, async ctx => { var file = ctx.ParseResult.GetValue(deployFileArg); var sigPath = ctx.ParseResult.GetValue(deploySig) ?? (File.Exists(file + ".sig") ? file + ".sig" : null); var r = CreateRenderer(ctx); var bytes = await File.ReadAllBytesAsync(file, ctx.CancellationToken); string? sigB64 = null; if (sigPath is not null) { var raw = await File.ReadAllTextAsync(sigPath, ctx.CancellationToken); sigB64 = raw.Trim(); } using var client = CreateClient(ctx); var result = await client.UploadModuleAsync(bytes, sigB64, ctx.CancellationToken); if (result.Success) r.Success($"{result.Message} (module: {result.ModuleName ?? "?"}, v{result.Version ?? "?"})"); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak module validate [--sig ] → dry-run, installs nothing var validateFileArg = new Argument("file") { Description = "Path to the .tpkg to validate" }; var validateSig = new Option("--sig") { Description = "Path to the .tpkg.sig (defaults to .sig if present)" }; var validateCmd = new Command("validate", "Validate a .tpkg without installing it") { validateFileArg, validateSig }; Handle(validateCmd, async ctx => { var file = ctx.ParseResult.GetValue(validateFileArg); var sigPath = ctx.ParseResult.GetValue(validateSig) ?? (File.Exists(file + ".sig") ? file + ".sig" : null); var r = CreateRenderer(ctx); var bytes = await File.ReadAllBytesAsync(file, ctx.CancellationToken); string? sigB64 = sigPath is not null ? (await File.ReadAllTextAsync(sigPath, ctx.CancellationToken)).Trim() : null; using var client = CreateClient(ctx); var result = await client.ValidateModuleAsync(bytes, sigB64, ctx.CancellationToken); if (result.Success) r.Success($"{result.Message} (module: {result.ModuleName ?? "?"}, v{result.Version ?? "?"})"); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak module rollback var rollbackArg = new Argument("name") { Description = "Module name to roll back" }; var rollbackCmd = new Command("rollback", "Roll a module back to its previous version") { rollbackArg }; Handle(rollbackCmd, async ctx => { var name = ctx.ParseResult.GetValue(rollbackArg); ConfirmOrAbort(ctx, $"Roll module '{name}' back to the previous version?"); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.RollbackModuleAsync(name, ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); cmd.Add(listCmd); cmd.Add(getCmd); cmd.Add(removeCmd); cmd.Add(keygenCmd); cmd.Add(signCmd); cmd.Add(deployCmd); cmd.Add(validateCmd); cmd.Add(rollbackCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // SCHEDULER // ═══════════════════════════════════════════════════════════════ private static Command BuildSchedulerCommand() { var cmd = new Command("scheduler", "Manage Quartz scheduler"); // tsak scheduler status [--watch] [--interval N] var statusCmd = new Command("status", "Show scheduler status"); Handle(statusCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); await RunOrWatch(ctx, async ct => { var s = await client.GetSchedulerStatusAsync(ct); r.RenderDetail( ("Status", s.Status), ("Name", s.SchedulerName), ("Instance", s.SchedulerInstanceId), ("Started", s.IsStarted ? "Yes" : "No"), ("Standby", s.InStandbyMode ? "Yes" : "No"), ("Shutdown", s.IsShutdown ? "Yes" : "No"), ("Total Jobs", s.TotalJobs.ToString()), ("Running Jobs", s.RunningJobs.ToString()), ("Contexts", s.Schedulers.Length == 0 ? "—" : string.Join(", ", s.Schedulers.Select(c => $"{c.Context} ({c.Status}, {c.TotalJobs} jobs)")))); }); }); // tsak scheduler jobs var jobsCmd = new Command("jobs", "List scheduled jobs"); Handle(jobsCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.ListScheduledJobsAsync(ctx.CancellationToken); r.RenderTable(result.Jobs, ("Context", j => j.Context ?? "—"), ("Job", j => j.JobName), ("Group", j => j.JobGroup), ("Trigger", j => j.TriggerState), ("Cron", j => j.CronExpression ?? "—"), ("Next Fire", j => j.NextFireTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "—")); }); // tsak scheduler running [--watch] [--interval N] var runningCmd = new Command("running", "List currently running jobs"); Handle(runningCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); await RunOrWatch(ctx, async ct => { var result = await client.ListRunningJobsAsync(ct); r.RenderTable(result.Jobs, ("Context", j => j.Context ?? "—"), ("Job", j => j.JobName), ("Group", j => j.JobGroup), ("Fire Time", j => j.FireTime.ToString("yyyy-MM-dd HH:mm:ss")), ("Runtime (ms)", j => j.RunTimeMs.ToString())); }); }); // Every route context owns its Quartz scheduler. Without --context a command addresses all of them; // a job key that two contexts share has to be qualified. const string jobContextHelp = "Route context whose scheduler holds the job (required when the key is in several)"; // tsak scheduler start [--context NAME] var startContextOpt = new Option("--context") { Description = "Start only the scheduler of this route context" }; var startCmd = new Command("start", "Start the scheduler") { startContextOpt }; Handle(startCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.StartSchedulerAsync( ctx.ParseResult.GetValue(startContextOpt), ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak scheduler standby [--context NAME] var standbyContextOpt = new Option("--context") { Description = "Put only the scheduler of this route context in standby" }; var standbyCmd = new Command("standby", "Put scheduler in standby mode") { standbyContextOpt }; Handle(standbyCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.StandbySchedulerAsync( ctx.ParseResult.GetValue(standbyContextOpt), ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak scheduler pause [--context NAME] var pauseKeyArg = new Argument("key") { Description = "Job key (group.name)" }; var pauseContextOpt = new Option("--context") { Description = jobContextHelp }; var pauseCmd = new Command("pause", "Pause a specific job") { pauseKeyArg, pauseContextOpt }; Handle(pauseCmd, async ctx => { var key = ctx.ParseResult.GetValue(pauseKeyArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.PauseJobAsync( key, ctx.ParseResult.GetValue(pauseContextOpt), ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak scheduler resume [--context NAME] var resumeKeyArg = new Argument("key") { Description = "Job key (group.name)" }; var resumeContextOpt = new Option("--context") { Description = jobContextHelp }; var resumeCmd = new Command("resume", "Resume a specific job") { resumeKeyArg, resumeContextOpt }; Handle(resumeCmd, async ctx => { var key = ctx.ParseResult.GetValue(resumeKeyArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.ResumeJobAsync( key, ctx.ParseResult.GetValue(resumeContextOpt), ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak scheduler fire [--context NAME] var fireKeyArg = new Argument("key") { Description = "Job key (group.name)" }; var fireContextOpt = new Option("--context") { Description = jobContextHelp }; var fireCmd = new Command("fire", "Fire a job immediately (out of schedule)") { fireKeyArg, fireContextOpt }; Handle(fireCmd, async ctx => { var key = ctx.ParseResult.GetValue(fireKeyArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.FireJobAsync( key, ctx.ParseResult.GetValue(fireContextOpt), ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); cmd.Add(statusCmd); cmd.Add(jobsCmd); cmd.Add(runningCmd); cmd.Add(startCmd); cmd.Add(standbyCmd); cmd.Add(pauseCmd); cmd.Add(resumeCmd); cmd.Add(fireCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // CLUSTER // ═══════════════════════════════════════════════════════════════ private static Command BuildClusterCommand() { var cmd = new Command("cluster", "Manage cluster topology"); // tsak cluster status var statusCmd = new Command("status", "Show cluster status"); Handle(statusCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var s = await client.GetClusterStatusAsync(ctx.CancellationToken); r.RenderDetail( ("Enabled", s.Enabled ? "Yes" : "No"), ("Node ID", s.NodeId ?? "—"), ("Leader", s.IsLeader.HasValue ? (s.IsLeader.Value ? "Yes" : "No") : "—"), ("Epoch", s.CurrentEpoch?.ToString() ?? "—")); }); // tsak cluster nodes var nodesCmd = new Command("nodes", "List cluster nodes"); Handle(nodesCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.ListClusterNodesAsync(ctx.CancellationToken); if (!result.Enabled) { r.Error("Clustering is not enabled."); ctx.ExitCode = 1; return; } r.RenderTable(result.Nodes, ("Node ID", n => n.NodeId), ("Hostname", n => n.Hostname), ("Status", n => n.Status.ToString()), ("Cordoned", n => n.Cordoned ? "yes" : "no"), ("Started", n => n.StartedAt.ToString("yyyy-MM-dd HH:mm:ss")), ("Heartbeat", n => n.LastHeartbeat.ToString("yyyy-MM-dd HH:mm:ss"))); }); // tsak cluster rebalance [--yes] var rebalanceCmd = new Command("rebalance", "Trigger cluster rebalance"); Handle(rebalanceCmd, async ctx => { ConfirmOrAbort(ctx, "Trigger cluster rebalance?"); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.RebalanceClusterAsync(ctx.CancellationToken); r.Success($"Rebalanced. Epoch: {result.CurrentEpoch}"); }); // tsak cluster cordon var cordonArg = new Argument("nodeId") { Description = "Node id" }; var cordonCmd = new Command("cordon", "Cordon a node (no new work; drain to peers)") { cordonArg }; Handle(cordonCmd, async ctx => { var id = ctx.ParseResult.GetValue(cordonArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.CordonNodeAsync(id, ctx.CancellationToken); r.Success($"Node '{result.NodeId}' cordoned — it will drain and take no new work."); }); // tsak cluster uncordon var uncordonArg = new Argument("nodeId") { Description = "Node id" }; var uncordonCmd = new Command("uncordon", "Uncordon a node (resume taking work)") { uncordonArg }; Handle(uncordonCmd, async ctx => { var id = ctx.ParseResult.GetValue(uncordonArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.UncordonNodeAsync(id, ctx.CancellationToken); r.Success($"Node '{result.NodeId}' uncordoned."); }); cmd.Add(statusCmd); cmd.Add(nodesCmd); cmd.Add(rebalanceCmd); cmd.Add(cordonCmd); cmd.Add(uncordonCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // LOG // ═══════════════════════════════════════════════════════════════ private static Command BuildLogCommand() { var cmd = new Command("log", "View runtime logs"); var limitOption = new Option("--limit") { Description = "Maximum number of entries" }; var levelOption = new Option("--level") { Description = "Minimum log level (Trace, Debug, Information, Warning, Error, Critical)" }; // tsak log get [--limit N] [--level LEVEL] var getCmd = new Command("get", "Get buffered log entries") { limitOption, levelOption }; Handle(getCmd, async ctx => { var limit = ctx.ParseResult.GetValue(limitOption); var level = ctx.ParseResult.GetValue(levelOption); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var logs = await client.GetLogsAsync(limit: limit, level: level, ct: ctx.CancellationToken); if (!logs.Available) { r.Error("Log buffering is not available."); ctx.ExitCode = 1; return; } r.RenderTable(logs.Entries ?? [], ("Time", e => e.Timestamp.ToString("HH:mm:ss.fff")), ("Level", e => e.Level), ("Source", e => e.Source ?? "—"), ("Message", e => e.Message)); }); cmd.Add(getCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // DLQ (dead-letter queue) // ═══════════════════════════════════════════════════════════════ private static Command BuildDlqCommand() { var cmd = new Command("dlq", "Dead-letter queue: browse, replay, discard failed exchanges"); // tsak dlq list [--context] [--route] [--status] [--limit] [--offset] var ctxOpt = new Option("--context") { Description = "Filter by context" }; var routeOpt = new Option("--route") { Description = "Filter by route id" }; var statusOpt = new Option("--status") { Description = "Filter by status (pending/replayed/discarded)" }; var limitOpt = new Option("--limit") { DefaultValueFactory = _ => 50, Description = "Page size (1..1000)" }; var offsetOpt = new Option("--offset") { DefaultValueFactory = _ => 0, Description = "Rows to skip" }; var listCmd = new Command("list", "List dead-lettered exchanges") { ctxOpt, routeOpt, statusOpt, limitOpt, offsetOpt }; Handle(listCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.GetFailedExchangesAsync( context: ctx.ParseResult.GetValue(ctxOpt), route: ctx.ParseResult.GetValue(routeOpt), status: ctx.ParseResult.GetValue(statusOpt), limit: ctx.ParseResult.GetValue(limitOpt), offset: ctx.ParseResult.GetValue(offsetOpt), ct: ctx.CancellationToken); if (!result.Available) { r.Error(result.Error ?? "DLQ not available (no database on this node)."); ctx.ExitCode = 1; return; } r.RenderTable(result.Entries, ("Id", e => e.EntryId.Length > 8 ? e.EntryId[..8] : e.EntryId), ("Time", e => e.OccurredAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")), ("Route", e => e.RouteId), ("Marker", e => e.MarkerName), ("Status", e => e.Status), ("Error", e => e.ExceptionType ?? "—"), ("Replayable", e => e.Replayable ? "yes" : "no")); }); // tsak dlq replay var replayArg = new Argument("id") { Description = "Entry id (full)" }; var replayCmd = new Command("replay", "Replay a dead-lettered exchange") { replayArg }; Handle(replayCmd, async ctx => { var id = ctx.ParseResult.GetValue(replayArg); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.ReplayExchangeAsync(id, ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); // tsak dlq discard var discardArg = new Argument("id") { Description = "Entry id (full)" }; var discardCmd = new Command("discard", "Discard a dead-lettered exchange") { discardArg }; Handle(discardCmd, async ctx => { var id = ctx.ParseResult.GetValue(discardArg); ConfirmOrAbort(ctx, $"Discard DLQ entry '{id}'?"); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.DiscardExchangeAsync(id, ctx.CancellationToken); if (result.Success) r.Success(result.Message); else { r.Error(result.Message); ctx.ExitCode = 1; } }); cmd.Add(listCmd); cmd.Add(replayCmd); cmd.Add(discardCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // AUDIT // ═══════════════════════════════════════════════════════════════ private static Command BuildAuditCommand() { var cmd = new Command("audit", "Query the persistent admin-action audit trail"); var actorOption = new Option("--actor") { Description = "Filter by actor (API key id or principal)" }; var actionOption = new Option("--action") { Description = "Filter by action name (e.g. RemoveContext)" }; var targetOption = new Option("--target") { Description = "Filter by target resource" }; var sinceOption = new Option("--since") { Description = "Only entries at or after this UTC time" }; var untilOption = new Option("--until") { Description = "Only entries at or before this UTC time" }; var limitOption = new Option("--limit") { DefaultValueFactory = _ => 50, Description = "Page size (1..1000)" }; var offsetOption = new Option("--offset") { DefaultValueFactory = _ => 0, Description = "Rows to skip (pagination)" }; // tsak audit [--actor] [--action] [--target] [--since] [--until] [--limit] [--offset] cmd.Add(actorOption); cmd.Add(actionOption); cmd.Add(targetOption); cmd.Add(sinceOption); cmd.Add(untilOption); cmd.Add(limitOption); cmd.Add(offsetOption); Handle(cmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var since = ctx.ParseResult.GetValue(sinceOption); var until = ctx.ParseResult.GetValue(untilOption); var result = await client.GetAuditAsync( actor: ctx.ParseResult.GetValue(actorOption), action: ctx.ParseResult.GetValue(actionOption), target: ctx.ParseResult.GetValue(targetOption), since: since is { } s ? new DateTimeOffset(s.ToUniversalTime(), TimeSpan.Zero) : null, until: until is { } u ? new DateTimeOffset(u.ToUniversalTime(), TimeSpan.Zero) : null, limit: ctx.ParseResult.GetValue(limitOption), offset: ctx.ParseResult.GetValue(offsetOption), ct: ctx.CancellationToken); if (!result.Available) { r.Error(result.Error ?? "Audit trail is not available (no database configured on this node)."); ctx.ExitCode = 1; return; } r.RenderTable(result.Entries, ("Time", e => e.Timestamp.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")), ("Actor", e => e.ActorPrincipal ?? e.ActorKeyId ?? "—"), ("Action", e => e.Action), ("Target", e => e.TargetResource ?? "—"), ("Status", e => e.StatusCode.ToString()), ("IP", e => e.RemoteIp ?? "—")); var offset = ctx.ParseResult.GetValue(offsetOption) ?? 0; var shown = result.Count ?? result.Entries.Length; if (shown == (result.Limit ?? 0)) r.Success($"Showing {shown} entries from offset {offset}. Use --offset {offset + shown} for the next page."); }); return cmd; } // ═══════════════════════════════════════════════════════════════ // AUTH // ═══════════════════════════════════════════════════════════════ private static Command BuildAuthCommand() { var cmd = new Command("auth", "Manage API keys"); // tsak auth list var listCmd = new Command("list", "List all API keys"); Handle(listCmd, async ctx => { using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var keys = await client.ListApiKeysAsync(ctx.CancellationToken); r.RenderTable(keys, ("ID", k => k.Id.ToString()), ("Name", k => k.Name), ("Roles", k => string.Join(", ", k.Roles)), ("Valid", k => k.IsValid ? "Yes" : "No"), ("Created", k => k.CreatedAt.ToString("yyyy-MM-dd"))); }); // tsak auth create --name [--roles r1,r2] [--user-id id] [--expires-at dt] var createNameOption = new Option("--name") { Description = "Key name", Required = true }; var createRolesOption = new Option("--roles") { Description = "Comma-separated roles" }; var createUserIdOption = new Option("--user-id") { Description = "Associated user ID" }; var createExpiresOption = new Option("--expires-at") { Description = "Expiration date/time" }; var createCmd = new Command("create", "Create a new API key") { createNameOption, createRolesOption, createUserIdOption, createExpiresOption }; Handle(createCmd, async ctx => { var name = ctx.ParseResult.GetValue(createNameOption)!; var roles = ctx.ParseResult.GetValue(createRolesOption); var userId = ctx.ParseResult.GetValue(createUserIdOption); var expiresAt = ctx.ParseResult.GetValue(createExpiresOption); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.CreateApiKeyAsync(name, roles, userId, expiresAt, ctx.CancellationToken); r.RenderDetail( ("ID", result.Id.ToString()), ("Key", result.Key), ("Name", result.Name), ("Roles", string.Join(", ", result.Roles)), ("Created", result.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss"))); r.Success(result.Message ?? "API key created. Save the key — it won't be shown again."); }); // tsak auth revoke [--yes] var revokeArg = new Argument("id") { Description = "API key ID" }; var revokeCmd = new Command("revoke", "Revoke an API key") { revokeArg }; Handle(revokeCmd, async ctx => { var id = ctx.ParseResult.GetValue(revokeArg); ConfirmOrAbort(ctx, $"Revoke API key '{id}'?"); using var client = CreateClient(ctx); var r = CreateRenderer(ctx); var result = await client.RevokeApiKeyAsync(id, ctx.CancellationToken); r.Success($"Key {result.Id} revoked."); }); cmd.Add(listCmd); cmd.Add(createCmd); cmd.Add(revokeCmd); return cmd; } // ═══════════════════════════════════════════════════════════════ // PROFILE (local — no API calls) // ═══════════════════════════════════════════════════════════════ private static Command BuildProfileCommand() { var pm = new ProfileManager(); var cmd = new Command("profile", "Manage connection profiles"); // tsak profile list var listCmd = new Command("list", "List saved profiles"); Handle(listCmd, ctx => { var r = CreateRenderer(ctx); var profiles = pm.List(); var activeName = pm.GetActiveName(); r.RenderTable(profiles, ("Name", p => p.Name + (p.Name == activeName ? " *" : "")), ("URL", p => p.Url), ("Key", p => p.ApiKey is not null ? "••••" : "—")); }); // tsak profile add --name --url [--key ] var addNameOpt = new Option("--name") { Description = "Profile name", Required = true }; var addUrlOpt = new Option("--url") { Description = "Runtime URL", Required = true }; var addKeyOpt = new Option("--key") { Description = "API key" }; var addCmd = new Command("add", "Add a new profile") { addNameOpt, addUrlOpt, addKeyOpt }; Handle(addCmd, ctx => { var r = CreateRenderer(ctx); var name = ctx.ParseResult.GetValue(addNameOpt)!; var url = ctx.ParseResult.GetValue(addUrlOpt)!; var key = ctx.ParseResult.GetValue(addKeyOpt); pm.Save(new ConnectionProfile { Name = name, Url = url, ApiKey = key }); r.Success($"Profile '{name}' saved."); }); // tsak profile remove var removeArg = new Argument("name") { Description = "Profile name" }; var removeCmd = new Command("remove", "Remove a profile") { removeArg }; Handle(removeCmd, ctx => { var r = CreateRenderer(ctx); var name = ctx.ParseResult.GetValue(removeArg); if (pm.Delete(name)) r.Success($"Profile '{name}' removed."); else r.Error($"Profile '{name}' not found."); }); // tsak profile use var useArg = new Argument("name") { Description = "Profile name to activate" }; var useCmd = new Command("use", "Set the active profile") { useArg }; Handle(useCmd, ctx => { var r = CreateRenderer(ctx); var name = ctx.ParseResult.GetValue(useArg); try { pm.SetActive(name); r.Success($"Active profile: {name}"); } catch (FileNotFoundException) { r.Error($"Profile '{name}' not found."); ctx.ExitCode = 1; } }); cmd.Add(listCmd); cmd.Add(addCmd); cmd.Add(removeCmd); cmd.Add(useCmd); return cmd; } } Path: redb-tsak/src/redb.Tsak.CLI/README.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/README.md ---- # redb.Tsak.CLI — `tsak` > Documentation and articles: Command-line tool for managing a running redb.Tsak runtime. Connects to any Tsak node over HTTP, exposes every REST API operation as a composable noun-verb command, and is scriptable via JSON output and quiet mode. ## Install ```bash # Global .NET tool dotnet tool install -g redb.Tsak.CLI # Verify tsak --version ``` ## Connect Connection settings are resolved in priority order: | Priority | Source | Description | |---|---|---| | 1 (highest) | `--url` / `--key` flags | Explicit per-invocation | | 2 | `TSAK_URL` / `TSAK_API_KEY` env vars | CI/CD pipelines, containers | | 3 (lowest) | Active profile (`~/.tsak/`) | Developer workstation | ### Connection profiles ```bash # Add a named profile tsak profile add --name prod --url https://tsak.prod.example.com --key sk-... # Add a local dev profile tsak profile add --name dev --url http://localhost:5100 # Switch active profile tsak profile use prod # List profiles (* = active) tsak profile list # Remove a profile tsak profile remove dev ``` Profiles are stored as YAML files under `~/.tsak/profiles/`. The active profile name is written to `~/.tsak/active`. ## Global options These flags apply to every command: | Flag | Short | Default | Description | |---|---|---|---| | `--profile` | `-p` | active | Connection profile name | | `--url` | `-u` | — | Tsak runtime URL (overrides profile) | | `--key` | `-k` | — | API key (overrides profile) | | `--output` | `-o` | `table` | Output format: `table` \| `json` \| `quiet` | | `--no-color` | | `false` | Disable ANSI color codes | | `--yes` | `-y` | `false` | Skip confirmation prompts (for destructive ops) | | `--watch` | | `false` | Poll the command repeatedly (Ctrl+C to stop) | | `--interval` | | `5` | Polling interval in seconds (with `--watch`) | | `--timeout` | | `5` | HTTP request timeout in seconds | ## Command reference ### `system` — Health, metrics, info ```bash tsak system health # Health check (live status) tsak system health --watch --interval 2 # Poll every 2 s tsak system metrics # Current CPU, memory, GC snapshot tsak system metrics --watch # Live metrics dashboard tsak system info # Version, uptime, context/module counts, module contexts in memory tsak system deploy-advice # Hot swap or cold deploy? Exit code 0: hot-swap, 3: cold-deploy tsak system deploy-advice --cluster -o json # Every alive node through this one; JSON only on stdout ``` ### `context` — Route context lifecycle A context groups one or more modules into a shared lifecycle and property bag. ```bash tsak context list # All contexts (name, status, endpoint count) tsak context get # Detailed view of one context tsak context start # Start a stopped context tsak context stop # Graceful stop (drains in-flight exchanges) tsak context restart # Stop + start tsak context remove # Remove context (prompts unless --yes) ``` ### `module` — Hot-loadable modules ```bash tsak module list # All loaded modules (name, version, status) tsak module get # Module details + dependencies tsak module remove # Unload and remove a module (--yes to skip prompt) ``` ### `route` — Individual routes within a context ```bash tsak route list # Routes in a context tsak route get # Route detail (endpoints, inflight count) tsak route start # Start a stopped route tsak route stop [--timeout N] # Graceful stop tsak route force-stop # Immediate stop (no drain) tsak route inflight # In-flight exchanges for a route tsak route inflight # All in-flight exchanges in a context ``` ### `watchdog` — Hung-exchange monitoring ```bash tsak watchdog status # Watchdog state, last check, alert count tsak watchdog alerts # Active watchdog alerts tsak watchdog enable # Enable watchdog tsak watchdog disable # Disable watchdog ``` ### `scheduler` — Quartz job scheduler ```bash tsak scheduler status # Scheduler status + job counts tsak scheduler jobs # All scheduled jobs (cron, next fire time) tsak scheduler running # Currently executing jobs tsak scheduler start # Start the scheduler tsak scheduler standby # Put scheduler in standby mode tsak scheduler pause # Pause a specific job tsak scheduler resume # Resume a paused job ``` ### `cluster` — Multi-node topology ```bash tsak cluster status # Cluster enabled?, node ID, leader flag, epoch tsak cluster nodes # All nodes (hostname, status, heartbeat) tsak cluster rebalance # Trigger leader election / rebalance ``` ### `log` — In-process log ring buffer ```bash tsak log get # Recent buffered log entries tsak log get --limit 100 # Last N entries tsak log get --level Warning # Filter by minimum level ``` ### `auth` — API key management ```bash tsak auth list # All API keys tsak auth create --name ci-bot --roles operator # New key (prints raw key once) tsak auth revoke # Revoke by ID ``` ### `diagnostics` — Deep inspection ```bash tsak diagnostics dump # Full system dump (contexts, inflight, alerts, events) tsak diagnostics route # Detailed dump for one route tsak diagnostics lifecycle # Lifecycle audit event log tsak diagnostics lifecycle --context orders --route in-0 --limit 50 tsak diagnostics dashboard # Aggregated snapshot (metrics + context states) ``` ## Output formats | Format | Use case | |---|---| | `table` (default) | Human-readable; Spectre.Console-rendered | | `json` | Scripting, piping to `jq` | | `quiet` | CI pipelines; only success/error messages | ```bash # Example: get context list as JSON tsak context list -o json | jq '.[].name' # Example: watch metrics without prompts (CI) tsak system metrics --watch --interval 10 -o json ``` ## Scripting example ```bash #!/usr/bin/env bash # Restart all contexts on a remote node export TSAK_URL=http://tsak-prod:5100 export TSAK_API_KEY=sk-prod-... for ctx in $(tsak context list -o json | jq -r '.[].name'); do echo "Restarting $ctx..." tsak context restart "$ctx" -y done ``` ## Environment variables | Variable | Description | |---|---| | `TSAK_URL` | Runtime base URL (`http://host:port`) | | `TSAK_API_KEY` | API key for authentication | ## Architecture ``` tsak (System.CommandLine) ├── Global options parser (ProfileManager → TsakApiClient) ├── Rendering layer (IOutputRenderer) │ ├── TableRenderer (Spectre.Console) │ ├── JsonRenderer (System.Text.Json) │ └── QuietRenderer (success/error only) ├── Commands/ │ ├── RouteCommands (route list/get/start/stop/inflight/force-stop) │ ├── WatchdogCommands (watchdog status/alerts/enable/disable) │ └── DiagnosticsCommands (diagnostics dump/route/lifecycle/dashboard) └── Config/ └── ProfileManager (~/.tsak/profiles/*.yaml) ``` ## Dependencies | Package | Purpose | |---|---| | `System.CommandLine` | Argument parsing, help generation | | `Spectre.Console` | Rich table rendering, colors | | `YamlDotNet` | Profile serialization | | `redb.Tsak.Client` | Typed HTTP client | | `redb.Tsak.Contracts` | Shared DTO models | ## Related projects | Project | Role | |---|---| | [redb.Tsak.Client](../redb.Tsak.Client/README.md) | HTTP client used by the CLI | | [redb.Tsak.Contracts](../redb.Tsak.Contracts/README.md) | DTO models for all API responses | | [redb.Tsak.Worker](../redb.Tsak.Worker/) | Runtime the CLI connects to | | [redb.Tsak](../../README.md) | Full project overview | Path: redb-tsak/src/redb.Tsak.CLI/Rendering/IOutputRenderer.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Rendering/IOutputRenderer.cs ---- namespace redb.Tsak.CLI.Rendering; /// /// Contract for CLI output renderers. /// public interface IOutputRenderer { /// Render a single object. void Render(T data); /// Render a collection as a table with named columns. void RenderTable(IEnumerable items, params (string Header, Func Value)[] columns); /// Render a key-value detail view. void RenderDetail(params (string Label, string Value)[] rows); /// Render a success message. void Success(string message); /// Render an error message. void Error(string message); } Path: redb-tsak/src/redb.Tsak.CLI/Rendering/JsonRenderer.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Rendering/JsonRenderer.cs ---- using System.Text.Json; namespace redb.Tsak.CLI.Rendering; /// /// Renders output as indented JSON (for piping and scripting). /// public sealed class JsonRenderer : IOutputRenderer { private static readonly JsonSerializerOptions Options = new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; /// public void Render(T data) { Console.WriteLine(JsonSerializer.Serialize(data, Options)); } /// public void RenderTable(IEnumerable items, params (string Header, Func Value)[] columns) { // For JSON mode, just serialize the raw items Console.WriteLine(JsonSerializer.Serialize(items, Options)); } /// public void RenderDetail(params (string Label, string Value)[] rows) { var dict = rows.ToDictionary(r => r.Label, r => r.Value); Console.WriteLine(JsonSerializer.Serialize(dict, Options)); } /// public void Success(string message) { Console.WriteLine(JsonSerializer.Serialize(new { status = "ok", message }, Options)); } /// public void Error(string message) { Console.Error.WriteLine(JsonSerializer.Serialize(new { status = "error", message }, Options)); } } Path: redb-tsak/src/redb.Tsak.CLI/Rendering/OutputFormat.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Rendering/OutputFormat.cs ---- namespace redb.Tsak.CLI.Rendering; /// /// Output format for CLI rendering. /// public enum OutputFormat { /// Human-readable table/colored output. Table, /// Machine-readable JSON output. Json, /// Minimal output (IDs, names, status codes only). Quiet } Path: redb-tsak/src/redb.Tsak.CLI/Rendering/QuietRenderer.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Rendering/QuietRenderer.cs ---- namespace redb.Tsak.CLI.Rendering; /// /// Minimal output renderer — prints only essential identifiers and statuses. /// public sealed class QuietRenderer : IOutputRenderer { /// public void Render(T data) { if (data is not null) Console.WriteLine(data); } /// public void RenderTable(IEnumerable items, params (string Header, Func Value)[] columns) { // Print only the first column value per row foreach (var item in items) { if (columns.Length > 0) Console.WriteLine(columns[0].Value(item)); } } /// public void RenderDetail(params (string Label, string Value)[] rows) { foreach (var (_, value) in rows) Console.WriteLine(value); } /// public void Success(string message) { // Quiet — no output on success } /// public void Error(string message) { Console.Error.WriteLine(message); } } Path: redb-tsak/src/redb.Tsak.CLI/Rendering/RendererFactory.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Rendering/RendererFactory.cs ---- namespace redb.Tsak.CLI.Rendering; /// /// Factory for creating the appropriate renderer based on the output format. /// public static class RendererFactory { /// /// Creates a renderer for the specified output format. /// /// Desired output format. /// Disable color in table output. public static IOutputRenderer Create(OutputFormat format, bool noColor = false) => format switch { OutputFormat.Json => new JsonRenderer(), OutputFormat.Quiet => new QuietRenderer(), _ => new TableRenderer(noColor) }; } Path: redb-tsak/src/redb.Tsak.CLI/Rendering/TableRenderer.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/Rendering/TableRenderer.cs ---- using Spectre.Console; namespace redb.Tsak.CLI.Rendering; /// /// Renders output as colored Spectre.Console tables. /// public sealed class TableRenderer : IOutputRenderer { private readonly bool _noColor; /// /// Initializes the table renderer. /// /// Disable color output. public TableRenderer(bool noColor = false) { _noColor = noColor; } /// public void Render(T data) { if (data is null) return; var props = typeof(T).GetProperties(); var table = new Table(); if (_noColor) table.Border = TableBorder.Ascii; table.AddColumn("Property"); table.AddColumn("Value"); foreach (var prop in props) { var value = prop.GetValue(data); table.AddRow( Markup.Escape(prop.Name), Markup.Escape(FormatValue(value))); } AnsiConsole.Write(table); } /// public void RenderTable(IEnumerable items, params (string Header, Func Value)[] columns) { var table = new Table(); if (_noColor) table.Border = TableBorder.Ascii; foreach (var col in columns) table.AddColumn(col.Header); foreach (var item in items) { var values = columns.Select(c => Markup.Escape(c.Value(item))).ToArray(); table.AddRow(values); } AnsiConsole.Write(table); } /// public void RenderDetail(params (string Label, string Value)[] rows) { var table = new Table().HideHeaders(); if (_noColor) table.Border = TableBorder.Ascii; table.AddColumn("Label"); table.AddColumn("Value"); foreach (var (label, value) in rows) table.AddRow($"[bold]{Markup.Escape(label)}[/]", Markup.Escape(value)); AnsiConsole.Write(table); } /// public void Success(string message) { AnsiConsole.MarkupLine(_noColor ? Markup.Escape($"OK: {message}") : $"[green]✓[/] {Markup.Escape(message)}"); } /// public void Error(string message) { AnsiConsole.MarkupLine(_noColor ? Markup.Escape($"ERROR: {message}") : $"[red]✗[/] {Markup.Escape(message)}"); } private static string FormatValue(object? value) => value switch { null => "—", bool b => b ? "Yes" : "No", DateTime dt => dt.ToString("yyyy-MM-dd HH:mm:ss"), string[] arr => string.Join(", ", arr), _ => value.ToString() ?? "—" }; } Path: redb-tsak/src/redb.Tsak.CLI/doc/API_REFERENCE.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/doc/API_REFERENCE.md ---- # API Reference Complete list of REST API endpoints used by the `tsak` CLI. All endpoints are served by the Tsak runtime on the configured host/port (default `http://localhost:5100`). ## Authentication When API key authentication is enabled, include the key in the `X-API-Key` header: ``` X-API-Key: sk-1234567890abcdef ``` The CLI handles this automatically via `--key`, profile, or `TSAK_API_KEY` environment variable. ## Endpoints ### System | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/system/health` | `tsak system health` | Health check with per-component statuses | | `GET` | `/api/system/metrics` | `tsak system metrics` | CPU, memory, GC, threading snapshot | | `GET` | `/api/system/info` | `tsak system info` | Version, uptime, machine info | ### Contexts | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/contexts` | `tsak context list` | List all route contexts | | `GET` | `/api/contexts/{name}` | `tsak context get ` | Get context details | | `POST` | `/api/contexts/{name}/start` | `tsak context start ` | Start a context | | `POST` | `/api/contexts/{name}/stop` | `tsak context stop ` | Stop a context | | `POST` | `/api/contexts/{name}/restart` | `tsak context restart ` | Restart a context | | `DELETE` | `/api/contexts/{name}` | `tsak context remove ` | Remove a context | ### Modules | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/modules` | `tsak module list` | List all modules | | `GET` | `/api/modules/{name}` | `tsak module get ` | Get module details | | `DELETE` | `/api/modules/{name}` | `tsak module remove ` | Remove a module | ### Scheduler | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/scheduler` | `tsak scheduler status` | Scheduler state | | `GET` | `/api/scheduler/jobs` | `tsak scheduler jobs` | List scheduled jobs | | `GET` | `/api/scheduler/running` | `tsak scheduler running` | Currently executing jobs | | `POST` | `/api/scheduler/start` | `tsak scheduler start` | Start scheduler | | `POST` | `/api/scheduler/standby` | `tsak scheduler standby` | Set standby mode | | `POST` | `/api/scheduler/jobs/{group}/{name}/pause` | `tsak scheduler pause ` | Pause a job | | `POST` | `/api/scheduler/jobs/{group}/{name}/resume` | `tsak scheduler resume ` | Resume a job | ### Cluster | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/cluster` | `tsak cluster status` | Cluster state and topology | | `GET` | `/api/cluster/nodes` | `tsak cluster nodes` | List cluster nodes | | `POST` | `/api/cluster/rebalance` | `tsak cluster rebalance` | Trigger rebalance | ### Logs | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/logs?limit={n}&level={level}` | `tsak log get` | Get buffered log entries | ### Auth (API Keys) | Method | Path | CLI Command | Description | |--------|------|-------------|-------------| | `GET` | `/api/auth/keys` | `tsak auth list` | List API keys | | `POST` | `/api/auth/keys` | `tsak auth create` | Create a new API key | | `DELETE` | `/api/auth/keys/{id}` | `tsak auth revoke ` | Revoke an API key | ## Error Responses All API errors return a JSON body: ```json { "message": "Context 'foo' not found", "statusCode": 404 } ``` The CLI maps these to `ApiException` with the HTTP status code as the exit code. Path: redb-tsak/src/redb.Tsak.CLI/doc/README.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/doc/README.md ---- # tsak CLI Command-line interface for managing [redb.Tsak](../../../README.md) runtime instances. ## Installation ```bash dotnet tool install -g redb.Tsak.CLI ``` After installation the `tsak` command is available globally. ## Quick Start ```bash # Configure a connection profile tsak profile add --name local --url http://localhost:5100 # Set it as the active profile tsak profile use local # Check system health tsak system health # List route contexts tsak context list # View recent logs tsak log get --limit 20 --level Warning ``` ## Global Options Every command accepts these options: | Option | Alias | Description | |--------|-------|-------------| | `--profile` | `-p` | Connection profile name | | `--url` | `-u` | Override runtime URL | | `--key` | `-k` | Override API key | | `--output` | `-o` | Output format: `Table` (default), `Json`, `Quiet` | | `--no-color` | — | Disable colored output | | `--yes` | `-y` | Skip confirmation prompts on destructive operations | | `--watch` | — | Poll repeatedly (Ctrl+C to stop) | | `--interval` | — | Polling interval in seconds (default: 5, used with `--watch`) | ### Connection Resolution The CLI resolves the target URL and API key in this order: 1. Explicit flags (`--url`, `--key`) 2. Environment variables (`TSAK_URL`, `TSAK_API_KEY`) 3. Active profile (`~/.tsak/active`) 4. Named profile (`--profile `) ## Commands ### system — System Health, Metrics, Info ```bash tsak system health # Health check with individual check statuses tsak system health --watch # Live health monitoring (every 5s) tsak system metrics # CPU, memory, GC, thread stats tsak system metrics --watch --interval 10 # Metrics every 10s tsak system info # Version, uptime, machine info ``` ### context — Route Contexts ```bash tsak context list # List all contexts (name, status, endpoints) tsak context get # Detailed context info tsak context start # Start a stopped context tsak context stop # Stop a running context tsak context restart # Restart a context tsak context remove # Remove (asks confirmation) tsak context remove -y # Remove without confirmation ``` ### module — Runtime Modules ```bash tsak module list # List modules (name, version, status) tsak module get # Module details and dependencies tsak module remove # Remove (asks confirmation) tsak module remove -y # Remove without confirmation ``` ### scheduler — Quartz Scheduler ```bash tsak scheduler status # Scheduler state overview tsak scheduler status --watch # Live scheduler monitoring tsak scheduler jobs # Scheduled jobs with cron and next fire time tsak scheduler running # Currently executing jobs tsak scheduler running --watch # Live running jobs view tsak scheduler start # Start the scheduler tsak scheduler standby # Put scheduler in standby tsak scheduler pause # Pause a specific job tsak scheduler resume # Resume a paused job ``` ### cluster — Cluster Topology ```bash tsak cluster status # Cluster state, node ID, leader, epoch tsak cluster nodes # All nodes with heartbeat info tsak cluster rebalance # Trigger rebalance (asks confirmation) tsak cluster rebalance -y # Rebalance without confirmation ``` ### log — Runtime Logs ```bash tsak log get # Recent log entries (default limit) tsak log get --limit 50 # Last 50 entries tsak log get --level Error # Only errors and above tsak log get --limit 100 --level Warning ``` Valid log levels: `Trace`, `Debug`, `Information`, `Warning`, `Error`, `Critical`. ### auth — API Key Management ```bash tsak auth list # List all API keys tsak auth create --name "deploy-key" --roles admin,reviewer tsak auth create --name "temp" --expires-at "2026-12-31T23:59:59" tsak auth revoke # Revoke (asks confirmation) tsak auth revoke -y # Revoke without confirmation ``` The generated key value is displayed **only on creation** — store it securely. ### profile — Connection Profiles Profiles are stored locally in `~/.tsak/profiles/` as YAML files. No API calls are made. ```bash tsak profile list # List profiles (* = active) tsak profile add --name prod --url https://tsak.example.com --key sk-xxx tsak profile remove prod tsak profile use prod # Set active profile ``` ## Output Formats ### Table (default) Human-readable tables with aligned columns. Use `--no-color` for plain text. ```bash tsak context list ``` ### JSON Machine-readable output for scripting and piping: ```bash tsak context list --output json | jq '.[] | .name' ``` ### Quiet Minimal output — only success/error messages, suitable for scripts: ```bash tsak context start my-ctx --output quiet && echo "Started" ``` ## Profiles ### File Structure Profiles live in `~/.tsak/profiles/.yml`: ```yaml url: https://tsak.example.com apiKey: sk-1234567890abcdef ``` The active profile name is stored in `~/.tsak/active`. ### Environment Variables | Variable | Description | |----------|-------------| | `TSAK_URL` | Runtime base URL | | `TSAK_API_KEY` | API key for authentication | Environment variables override profile values but are overridden by explicit `--url`/`--key` flags. ## Exit Codes | Code | Meaning | |------|---------| | `0` | Success | | `1` | Runtime/application error | | `≥2` | HTTP error from API (status code mapped) | ## Examples ### Monitor in a script ```bash #!/bin/bash export TSAK_URL=http://localhost:5100 # Check health STATUS=$(tsak system health --output json | jq -r '.status') if [ "$STATUS" != "Healthy" ]; then echo "ALERT: Tsak is $STATUS" fi # Count running jobs RUNNING=$(tsak scheduler running --output json | jq '.jobs | length') echo "Running jobs: $RUNNING" ``` ### Manage multiple environments ```bash # Setup profiles tsak profile add --name dev --url http://localhost:5100 tsak profile add --name staging --url https://staging.example.com --key sk-stg tsak profile add --name prod --url https://prod.example.com --key sk-prod # Compare contexts across environments tsak --profile dev context list tsak --profile staging context list tsak --profile prod context list ``` ### Scheduler operations ```bash # View scheduled jobs tsak scheduler jobs # Pause a job, do maintenance, resume tsak scheduler pause DEFAULT cleanup-job # ... maintenance ... tsak scheduler resume DEFAULT cleanup-job ``` ## Confirmation Prompts Destructive commands ask for confirmation before executing: ``` $ tsak context remove payment-gateway Remove context 'payment-gateway'? [y/N]: y Context 'payment-gateway' removed. ``` Commands with confirmation: `context remove`, `module remove`, `cluster rebalance`, `auth revoke`. Skip with `--yes` / `-y`: ```bash tsak context remove old-context --yes ``` Confirmation is also skipped automatically when output format is `Json` or `Quiet` (implies scripting). ## Watch Mode Add `--watch` to monitoring commands for continuous polling: ```bash tsak system health --watch # Poll every 5 seconds tsak system metrics --watch --interval 10 # Poll every 10 seconds tsak scheduler status --watch tsak scheduler running --watch ``` Press `Ctrl+C` to stop. Default interval is 5 seconds. ## Shell Auto-Complete The CLI supports tab completion via `dotnet-suggest` (built into System.CommandLine): ```bash # Install dotnet-suggest globally dotnet tool install -g dotnet-suggest ``` ### Bash / Zsh Add to `~/.bashrc` or `~/.zshrc`: ```bash eval "$(dotnet-suggest register)" ``` ### PowerShell Add to `$PROFILE`: ```powershell Register-ArgumentCompleter -Native -CommandName tsak -ScriptBlock { param($wordToComplete, $commandAst, $cursorPosition) dotnet-suggest get -e "tsak" -- "$commandAst" | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } } ``` ### Fish ```fish dotnet-suggest register --shell fish | source ``` After setup, tab completion works for all commands, subcommands, options, and enum values: ``` tsak sch → tsak scheduler tsak scheduler → status jobs running start standby pause resume tsak --output → Table Json Quiet ``` Path: redb-tsak/src/redb.Tsak.CLI/redb.Tsak.CLI.csproj Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.CLI/redb.Tsak.CLI.csproj ---- Exe tsak redb.Tsak.CLI true tsak redb.Tsak.CLI CLI tool for redb.Tsak runtime management: contexts, modules, cluster, scheduler, monitoring. redb;tsak;cli;runtime;management README.md