diff --git a/OrchestratorIDE.Daemon/HiveService.cs b/OrchestratorIDE.Daemon/HiveService.cs index dd13dc79..0927df47 100644 --- a/OrchestratorIDE.Daemon/HiveService.cs +++ b/OrchestratorIDE.Daemon/HiveService.cs @@ -118,7 +118,23 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) // Wire election/heartbeat logs after Start (services auto-created inside Start). if (_nodeServer.ElectionService is { } election) + { election.OnLog += msg => _log.LogInformation("[Election] {Msg}", msg); + + // Discovered live (2026-07-29) verifying the new /hive/roles/degrade and + // /hive/tasks/cancel endpoints: HiveElectionService.WarchiefNodeId is ONLY ever set + // via live election-protocol messages (SetWarchief's own doc comment: "Must be + // called by the app when a HIVE session starts... we've received a session context + // identifying who is"). Nothing here ever called it for a statically-configured + // worker, even though _cfg.WarchiefNodeId is already known from config -- so every + // Warchief-only mutation gate (this one, /hive/roles/degrade, /hive/tasks/cancel, and + // the PRE-EXISTING /hive/update/deploy) rejected the fleet's real, correctly-signed + // Warchief with a 403 on every one of them, on every worker in this deployment shape. + // A worker that already knows its Warchief via config doesn't need to wait for + // election traffic to learn what it was already told. + if (!string.IsNullOrWhiteSpace(_cfg.WarchiefNodeId)) + election.SetWarchief(_cfg.WarchiefNodeId); + } if (_nodeServer.MeshHeartbeat is { } hb) hb.OnLog += msg => _log.LogInformation("[Heartbeat] {Msg}", msg); @@ -257,6 +273,13 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) }).ToList(), }; }; + + // HV-3 item 3 (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md): MarkRoleDegraded was + // previously reachable only from the runtime's own internal NoKvSlot handling — + // this wires the long-deferred remote trigger (POST /hive/roles/degrade) to the + // same NativeRoleRuntime instance NativeTelemetryProvider above already closes + // over. + _nodeServer.MarkRoleDegradedHandler = role => nativeRuntime.MarkRoleDegraded(role); } _worker = new HiveWorkerAgent @@ -270,6 +293,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) WarchiefNodeId = _cfg.WarchiefNodeId, ModelStore = _taskQueue.ModelStore, }; + // HV-4 item 1: a campaign cancel previously only marked the task cancelled on the + // Warchief while the worker kept generating to completion — no remote trigger existed + // to actually interrupt it. POST /hive/tasks/cancel now reaches this worker's + // per-task cancellation registry directly. + _nodeServer.CancelTaskHandler = taskId => _worker.TryCancelTask(taskId); _worker.OnLog += msg => _log.LogInformation("[Worker] {Msg}", msg); var installedPacks = CampaignPackCatalog.ResolveInstalled(_cfg.AlienSearchImage); _worker.Capabilities = await WorkerCapabilityDetector.DetectAsync( diff --git a/OrchestratorIDE.UnitTests/HiveNodeServerAuthorizationTests.cs b/OrchestratorIDE.UnitTests/HiveNodeServerAuthorizationTests.cs new file mode 100644 index 00000000..b788a9d3 --- /dev/null +++ b/OrchestratorIDE.UnitTests/HiveNodeServerAuthorizationTests.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2025-present hardcoreerik / TheOrc contributors +// SPDX-License-Identifier: AGPL-3.0-or-later +using NUnit.Framework; +using OrchestratorIDE.Services.Hive; + +namespace OrchestratorIDE.UnitTests; + +/// +/// HiveNodeServer.IsWarchief is the shared authority gate for the Warchief-only mutation +/// endpoints (remote deploy, /hive/roles/degrade, /hive/tasks/cancel — HV-3 item 3 / HV-4 +/// item 1). It reads ElectionService.WarchiefNodeId, which requires a real HiveElectionService +/// (itself requiring a real HiveIdentity, private-constructor-only) to test the "configured and +/// matches" branch — too heavy for what should be a cheap authorization check. This covers the +/// safe-default branch instead: no ElectionService configured must mean nobody is authorized +/// (fail-closed), not "any caller passes." +/// +[TestFixture] +public sealed class HiveNodeServerAuthorizationTests +{ + [TestCase("")] + [TestCase("some-node-id")] + public void IsWarchief_ReturnsFalse_WhenElectionServiceNotConfigured(string nodeId) + { + using var server = new HiveNodeServer(); + Assert.That(server.ElectionService, Is.Null, "test assumes the default-constructed state"); + Assert.That(server.IsWarchief(nodeId), Is.False); + } +} diff --git a/OrchestratorIDE.UnitTests/HiveWorkerAgentTests.cs b/OrchestratorIDE.UnitTests/HiveWorkerAgentTests.cs index 303f5424..4effb3d1 100644 --- a/OrchestratorIDE.UnitTests/HiveWorkerAgentTests.cs +++ b/OrchestratorIDE.UnitTests/HiveWorkerAgentTests.cs @@ -77,4 +77,20 @@ public async Task RunLoop_Survives_A_Timed_Out_Lease_Poll() foreach (var client in stalled) client.Dispose(); } } + + /// + /// HV-4 item 1's remote cancel endpoint (HiveNodeServer.CancelTaskHandler) reports "not + /// found" (404) rather than an error for a taskId this worker isn't currently tracking — + /// covers the empty-registry case (never claimed anything) and an id that simply doesn't + /// match. The "found and actually cancels" path needs a real claimed task in flight + /// (a heavier integration scenario); this locks down the safe, cheap half: an unknown id + /// never throws and never reports a false positive. + /// + [TestCase("")] + [TestCase("never-claimed-task-id")] + public void TryCancelTask_ReturnsFalse_ForUnknownTaskId(string taskId) + { + var agent = new HiveWorkerAgent(); + Assert.That(agent.TryCancelTask(taskId), Is.False); + } } diff --git a/OrchestratorIDE/Core/Runtime/IRoleRuntime.cs b/OrchestratorIDE/Core/Runtime/IRoleRuntime.cs index 500de9f0..d5524605 100644 --- a/OrchestratorIDE/Core/Runtime/IRoleRuntime.cs +++ b/OrchestratorIDE/Core/Runtime/IRoleRuntime.cs @@ -240,6 +240,20 @@ public IReadOnlyList GetResidencySnapshot() return _orchestrator.GetResidencySnapshot(); } + /// + /// Forwards to . Public entry point for + /// 's remote + /// POST /hive/roles/degrade endpoint (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md + /// HV-3 item 3) — previously this method was reachable only from the internal NoKvSlot/ + /// generation-failure paths inside this same class (, + /// ). + /// + public Task MarkRoleDegraded(RuntimeRole role) + { + ThrowIfDisposed(); + return _orchestrator.MarkRoleDegraded(role); + } + public Task GetContextLengthAsync(string model, CancellationToken ct = default) => Task.FromResult(_options.ContextLength); diff --git a/OrchestratorIDE/Services/Hive/HiveNodeServer.cs b/OrchestratorIDE/Services/Hive/HiveNodeServer.cs index caad76f8..a1901176 100644 --- a/OrchestratorIDE/Services/Hive/HiveNodeServer.cs +++ b/OrchestratorIDE/Services/Hive/HiveNodeServer.cs @@ -5,6 +5,7 @@ using System.Security.Cryptography; using System.Text; using System.Text.Json; +using OrchestratorIDE.Core.Runtime; namespace OrchestratorIDE.Services.Hive; @@ -23,6 +24,8 @@ namespace OrchestratorIDE.Services.Hive; /// POST /hive/mesh/election/stepdown — authenticated election: temp Warchief stepping down /// GET /hive/update/version — this node's installed version (unauthenticated) /// POST /hive/update/deploy — Warchief-authenticated remote update trigger +/// POST /hive/roles/degrade — Warchief-authenticated forced role recycle +/// POST /hive/tasks/cancel — Warchief-authenticated single in-flight task cancel /// /// Auth: all /hive/mesh/* endpoints validate HMAC headers via HiveAuthMiddleware. /// /hive/tasks/* endpoints (port 7079, HiveTaskQueue) are wired separately and @@ -80,6 +83,26 @@ public sealed class HiveNodeServer : IDisposable /// public Func? NativeTelemetryProvider { get; set; } + /// + /// Injected by the app (Daemon: HiveService, alongside NativeTelemetryProvider) so + /// POST /hive/roles/degrade can force a role's native executor to recycle on its next mint + /// ( via + /// NativeRoleRuntime's public forwarder). Previously reachable ONLY from the runtime's + /// own NoKvSlot/generation-failure handling (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md, + /// HV-3 item 3 / HV-4 item 1) — this is that long-deferred remote trigger. Null when native + /// execution isn't configured on this node, same convention as NativeTelemetryProvider. + /// + public Func? MarkRoleDegradedHandler { get; set; } + + /// + /// Injected by the app (Daemon: HiveService, after constructing HiveWorkerAgent) so + /// POST /hive/tasks/cancel can interrupt ONE in-flight task + /// () without stopping the worker or any other + /// concurrently-running task. Returns false (surfaced as 404) for an id this worker isn't + /// currently tracking. Null on a node with no worker agent (e.g. Warchief-only). + /// + public Func? CancelTaskHandler { get; set; } + // Pending pairing sessions: sessionId → (request, expiry, initiator-remote-ip) private readonly Dictionary _pendingPairings = []; // Completed results: sessionId → (response, stored-at). Pruned after 10 min. @@ -535,8 +558,7 @@ private async Task HandleAsync(HttpListenerContext ctx, CancellationToken ct) // Remote deploy — Warchief-only (authResult already enforced strict auth above) if (method == "POST" && path == "/hive/update/deploy") { - var wc = ElectionService?.WarchiefNodeId; - if (string.IsNullOrEmpty(wc) || wc != authResult.NodeId) + if (!IsWarchief(authResult.NodeId)) { resp.StatusCode = 403; Error(resp, "only the Warchief may deploy updates"); @@ -549,6 +571,35 @@ private async Task HandleAsync(HttpListenerContext ctx, CancellationToken ct) return; } + // Forced role recycle — Warchief-only, same authority tier as remote deploy: this is + // a fleet-operator diagnostic action (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md + // HV-3 item 3), not something any authenticated-but-unprivileged peer should trigger. + if (method == "POST" && path == "/hive/roles/degrade") + { + if (!IsWarchief(authResult.NodeId)) + { + resp.StatusCode = 403; + Error(resp, "only the Warchief may force a role recycle"); + return; + } + await HandleMarkRoleDegradedAsync(body, resp).ConfigureAwait(false); + return; + } + + // Single in-flight task cancel — Warchief-only, same reasoning as above: this + // interrupts a real running generation on the worker (HV-4 item 1), not a read. + if (method == "POST" && path == "/hive/tasks/cancel") + { + if (!IsWarchief(authResult.NodeId)) + { + resp.StatusCode = 403; + Error(resp, "only the Warchief may cancel a task"); + return; + } + HandleCancelTask(body, resp); + return; + } + resp.StatusCode = 404; Error(resp, "not found"); } @@ -934,6 +985,98 @@ private void HandleMeshHeartbeat(byte[] body, HttpListenerRequest req, catch { resp.StatusCode = 400; Error(resp, "bad request"); } } + /// + /// Shared authority check for the Warchief-only mutation endpoints (remote deploy, forced + /// role recycle, task cancel). Mirrors the inline check already used by + /// /hive/update/deploy — factored out here rather than duplicated a third time. Peer-local + /// and non-transitive: being a Founder elsewhere does not make a node the Warchief FROM this + /// node's own perspective (docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md:90-99), so this checks + /// ElectionService's own live view, the same source /hive/update/deploy already trusts. + /// + internal bool IsWarchief(string nodeId) + { + var wc = ElectionService?.WarchiefNodeId; + return !string.IsNullOrEmpty(wc) && wc == nodeId; + } + + // ── /hive/roles/degrade ─────────────────────────────────────────────────── + + private sealed record MarkRoleDegradedRequest(string Role); + + private async Task HandleMarkRoleDegradedAsync(byte[] body, HttpListenerResponse resp) + { + if (MarkRoleDegradedHandler is null) + { + resp.StatusCode = 503; + Error(resp, "native execution is not configured on this node"); + return; + } + MarkRoleDegradedRequest? payload; + try { payload = JsonSerializer.Deserialize(body, _jsonIn); } + catch { resp.StatusCode = 400; Error(resp, "bad request"); return; } + + // Enum.TryParse alone accepts any integer string ("999") as a "successfully parsed" + // undefined value — Enum.IsDefined is required to actually reject it (CodeRabbit, PR #94). + if (payload is null + || !Enum.TryParse(payload.Role, ignoreCase: true, out var role) + || !Enum.IsDefined(role)) + { + resp.StatusCode = 400; + Error(resp, $"invalid or missing role (expected one of: {string.Join(", ", Enum.GetNames())})"); + return; + } + + // Awaited, not fire-and-forget: MarkRoleDegraded itself is a fast, in-memory flag set + // (AdapterManager.cs:317-334 — the actual recycle only happens lazily on the role's next + // mint), so there is no latency reason to respond before it completes. A fire-and-forget + // version of this shipped first and silently reported 200 for a call that threw + // (a real MissingMethodException, hit live during this endpoint's own deployment + // verification, PR #94 grok-review) — a mutation endpoint reporting success for a call + // that never actually ran is worse than a slower, honest response. + try + { + await MarkRoleDegradedHandler(role).ConfigureAwait(false); + Ok(resp, Json(new { status = "ok", role = role.ToString() })); + } + catch (Exception ex) + { + resp.StatusCode = 500; + Error(resp, $"MarkRoleDegraded({role}) failed: {ex.Message}"); + } + } + + // ── /hive/tasks/cancel ──────────────────────────────────────────────────── + + private sealed record CancelTaskRequest(string TaskId); + + private void HandleCancelTask(byte[] body, HttpListenerResponse resp) + { + if (CancelTaskHandler is null) + { + resp.StatusCode = 503; + Error(resp, "no worker agent is running on this node"); + return; + } + CancelTaskRequest? payload; + try { payload = JsonSerializer.Deserialize(body, _jsonIn); } + catch { resp.StatusCode = 400; Error(resp, "bad request"); return; } + + if (payload is null || string.IsNullOrWhiteSpace(payload.TaskId)) + { + resp.StatusCode = 400; + Error(resp, "missing taskId"); + return; + } + + if (!CancelTaskHandler(payload.TaskId)) + { + resp.StatusCode = 404; + Error(resp, "no in-flight task with this id on this worker"); + return; + } + Ok(resp, Json(new { status = "ok", taskId = payload.TaskId })); + } + // ── /hive/mesh/election/* ───────────────────────────────────────────────── private void HandleElection(string path, byte[] body, string authenticatedNodeId, diff --git a/OrchestratorIDE/Services/Hive/HiveTaskQueue.cs b/OrchestratorIDE/Services/Hive/HiveTaskQueue.cs index 6136c5a4..4ea158fa 100644 --- a/OrchestratorIDE/Services/Hive/HiveTaskQueue.cs +++ b/OrchestratorIDE/Services/Hive/HiveTaskQueue.cs @@ -1229,6 +1229,7 @@ private async Task HandleFailAsync(HttpListenerContext ctx, string taskId, byte[ QueuedTask? entry = null; HiveTaskResult? failResult = null; var requeued = false; + var wasCancelled = false; await _claimLock.WaitAsync(); try { @@ -1250,7 +1251,18 @@ private async Task HandleFailAsync(HttpListenerContext ctx, string taskId, byte[ ErrorMsg = "Worker reported failure with no details", }; entry.ErrorMsg = failResult.ErrorMsg; - if (entry.Bundle.CampaignId.Length > 0 && entry.Bundle.Attempt < entry.Bundle.MaxAttempts) + + // A remote /hive/tasks/cancel request (HiveWorkerAgent.TryCancelTask) posts back + // here — the "fail" wire action, same as a genuine execution failure — but with + // Status == "cancelled" rather than "failed". Checked FIRST and unconditionally: an + // operator-cancelled task must never fall into the requeue branch below just because + // attempts remain, or cancel would silently resurrect the same work instead of + // stopping it (caught in code review, grok-review PR #94, before this ever shipped). + // "cancelled" is already a first-class terminal status elsewhere in this class (the + // Warchief-initiated campaign-cancel path a few hundred lines down) — reused here + // rather than inventing a second vocabulary for the same concept. + wasCancelled = failResult.Status == "cancelled"; + if (!wasCancelled && entry.Bundle.CampaignId.Length > 0 && entry.Bundle.Attempt < entry.Bundle.MaxAttempts) { entry.Bundle.Attempt++; entry.Status = "pending"; @@ -1263,7 +1275,7 @@ private async Task HandleFailAsync(HttpListenerContext ctx, string taskId, byte[ } else { - entry.Status = "failed"; + entry.Status = wasCancelled ? "cancelled" : "failed"; } } finally { _claimLock.Release(); } @@ -1284,13 +1296,15 @@ private async Task HandleFailAsync(HttpListenerContext ctx, string taskId, byte[ entry!.CompletionTcs.TrySetResult(failResult); - Log($"⚠ [{entry.Bundle.Role}] '{entry.Bundle.Title}' failed by {failResult!.WorkerId}: {failResult.ErrorMsg}"); - Events.Append("task_failed", - $"[{failResult.WorkerId}] {entry.Bundle.Title} ✗ {failResult.ErrorMsg}", + var terminalStatus = wasCancelled ? "cancelled" : "failed"; + Log($"{(wasCancelled ? "🛑" : "⚠")} [{entry.Bundle.Role}] '{entry.Bundle.Title}' {terminalStatus} " + + $"by {failResult!.WorkerId}: {failResult.ErrorMsg}"); + Events.Append(wasCancelled ? "task_cancelled" : "task_failed", + $"[{failResult.WorkerId}] {entry.Bundle.Title} {(wasCancelled ? "🛑" : "✗")} {failResult.ErrorMsg}", taskId, failResult.WorkerId); - // Durable history: persist the failure + provenance. - PersistTask(taskId, entry.SessionId, entry.Bundle.Role, entry.Bundle.Title, "failed", + // Durable history: persist the failure/cancellation + provenance. + PersistTask(taskId, entry.SessionId, entry.Bundle.Role, entry.Bundle.Title, terminalStatus, authNode, failResult.WorkerId, authenticated: true, entry.ClaimToken, resultBlob: null, failResult.DurationMs, failResult.ErrorMsg, entry.EnqueuedAt); if (entry.Bundle.CampaignId.Length > 0) @@ -1299,11 +1313,11 @@ private async Task HandleFailAsync(HttpListenerContext ctx, string taskId, byte[ FinalizeVerificationGroup(entry.VerificationParentTaskId!); else CampaignRepository?.UpdateWorkUnit(entry.Bundle.CampaignId, entry.Bundle.WorkUnitId, - "failed", entry.Bundle.Attempt, authNode, error: failResult.ErrorMsg); + terminalStatus, entry.Bundle.Attempt, authNode, error: failResult.ErrorMsg); UpdateCampaignAfterTerminal(entry.Bundle.CampaignId); } - WriteJson(ctx, new { taskId, status = "failed" }); + WriteJson(ctx, new { taskId, status = terminalStatus }); } private Task HandleGetStatusAsync(HttpListenerContext ctx) diff --git a/OrchestratorIDE/Services/Hive/HiveWorkerAgent.cs b/OrchestratorIDE/Services/Hive/HiveWorkerAgent.cs index e089ef6f..7e9b3c95 100644 --- a/OrchestratorIDE/Services/Hive/HiveWorkerAgent.cs +++ b/OrchestratorIDE/Services/Hive/HiveWorkerAgent.cs @@ -30,6 +30,12 @@ public sealed class HiveWorkerAgent : IDisposable, IAsyncDisposable { private static readonly TimeSpan DefaultDisposeWaitTimeout = TimeSpan.FromSeconds(5); private CancellationTokenSource? _cts; + // Per-task cancellation, separate from _cts (the worker's whole-process lifetime token). + // Registered in ClaimAndExecuteAsync while a task is in flight, removed in its `finally` — + // lets a remote /hive/tasks/cancel request (see HiveNodeServer.CancelTaskHandler) interrupt + // ONE task's generation without stopping the worker or any other concurrently-running task. + private readonly System.Collections.Concurrent.ConcurrentDictionary + _activeTaskCancellations = new(); private Task? _runLoopTask; private Task? _shutdownTask; private int _disposeState; @@ -127,6 +133,21 @@ public void Stop() _cts = null; } + /// + /// Cancels ONE in-flight task by id, surfacing as + /// inside that task's generation loop (via the per-task token created in + /// ) without affecting the worker's poll loop or any other + /// concurrently-running task. Returns false if no task with this id is currently tracked + /// (already finished, never claimed by this worker, or a stale/unknown id) — the caller + /// ('s cancel endpoint) reports that as "not found", not an error. + /// + public bool TryCancelTask(string taskId) + { + if (!_activeTaskCancellations.TryGetValue(taskId, out var cts)) return false; + try { cts.Cancel(); } catch (ObjectDisposedException) { return false; } + return true; + } + // ── Main polling loop ───────────────────────────────────────────────────── private async Task RunLoopAsync(CancellationToken ct) @@ -429,14 +450,37 @@ private async Task ClaimAndExecuteAsync(HiveTaskBundle bundle, CancellationToken using var heartbeatCts = CancellationTokenSource.CreateLinkedTokenSource(ct); var heartbeatTask = HeartbeatLoopAsync(bundle, claimToken ?? "", heartbeatCts.Token); + // Separate linked token for the task ITSELF, distinct from heartbeatCts above (that one + // stops HEARTBEATING once execution ends; this one, cancelled independently by + // TryCancelTask via a remote /hive/tasks/cancel request, interrupts the GENERATION). + // Registered here rather than earlier because a task without a claim token was never + // really "this worker's" to cancel. + using var taskCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + _activeTaskCancellations[bundle.TaskId] = taskCts; + try { - result = await ExecuteTaskAsync(bundle, ct).ConfigureAwait(false); + result = await ExecuteTaskAsync(bundle, taskCts.Token).ConfigureAwait(false); } // Same distinction as RunLoopAsync: an HTTP-timeout TaskCanceledException is a task // failure to report back to the Warchief, not a worker shutdown — rethrowing it would // orphan the lease with no fail result posted. catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + // A remote per-task cancel (taskCts tripped, ct itself still live) is NOT the same as a + // genuine execution failure and must be reported as its own terminal status, not + // "failed" — caught live in code review (grok-review, PR #94): HiveTaskQueue. + // HandleFailAsync requeues campaign work while Attempt < MaxAttempts, so posting this as + // a plain failure would have let the SAME work silently come back for another attempt, + // the opposite of what an operator cancelling a task means. "cancelled" is already a + // first-class terminal status elsewhere in HiveTaskQueue (the Warchief-initiated + // campaign-cancel path) — HandleFailAsync now special-cases this exact string to skip + // its own requeue logic rather than inventing a second cancellation vocabulary. + catch (OperationCanceledException) when (taskCts.IsCancellationRequested) + { + status = "cancelled"; + errorMsg = "Cancelled via remote /hive/tasks/cancel request."; + Log($"🛑 [{bundle.Role}] '{bundle.Title}' — cancelled remotely"); + } catch (Exception ex) { status = "failed"; @@ -457,6 +501,7 @@ private async Task ClaimAndExecuteAsync(HiveTaskBundle bundle, CancellationToken { heartbeatCts.Cancel(); try { await heartbeatTask.ConfigureAwait(false); } catch { } + _activeTaskCancellations.TryRemove(bundle.TaskId, out _); } var taskResult = new HiveTaskResult @@ -548,12 +593,17 @@ async Task> UploadOrFailAsync(string outputDirectory) await UploadOrFailAsync(container.OutputDirectory).ConfigureAwait(false)); } + // "cancelled" rides the same wire action/endpoint as "failed" — HiveTaskQueue. + // HandleFailAsync distinguishes them by reading taskResult.Status, not by a different + // action/route. var action = status == "completed" ? "complete" : "fail"; await PostResultAsync(bundle.TaskId, action, taskResult, ct).ConfigureAwait(false); - TaskActivity(bundle.TaskId, - status == "completed" - ? $"✅ Sent to Warchief ({taskResult.DurationMs / 1000.0:F1}s, {result?.Length ?? 0} chars)" - : $"⚠ Failure reported to Warchief: {errorMsg}"); + TaskActivity(bundle.TaskId, status switch + { + "completed" => $"✅ Sent to Warchief ({taskResult.DurationMs / 1000.0:F1}s, {result?.Length ?? 0} chars)", + "cancelled" => "🛑 Cancellation reported to Warchief", + _ => $"⚠ Failure reported to Warchief: {errorMsg}", + }); } private async Task ClaimTaskAsync(HiveTaskBundle bundle, CancellationToken ct) diff --git a/docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md b/docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md index ca4b70a6..a61c0c6f 100644 --- a/docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md +++ b/docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md @@ -748,6 +748,43 @@ review — recorded in every evidence file's `uncoveredItems`. HV-3 must therefo fully closed; §6's "verified model and adapter lifecycle behavior across machines" is now substantially, but not completely, evidenced. +**2026-07-29 — item 3 CLOSED. Built the authenticated control endpoint this item was waiting on, +plus a genuine pre-existing auth bug found and fixed along the way.** + +`POST /hive/roles/degrade` on `HiveNodeServer` (Warchief-only, same authority tier as the +existing `/hive/update/deploy`) forwards to a new public `NativeRoleRuntime.MarkRoleDegraded` +passthrough (mirroring the existing `GetReservationSnapshot`/`GetResidencySnapshot` forwarders), +which calls the same `RuntimeOrchestrator.MarkRoleDegraded` the runtime's own internal NoKvSlot +handling already used — no new recycle mechanism, just a remote door onto the existing one. +`HiveService.cs` wires the handler alongside `NativeTelemetryProvider`. + +**Live-verified against a real deployed daemon (HardcorePC), not just unit-tested.** A throwaway +signed-request harness (deleted after use, matching this session's earlier spike/probe +convention) hit the real endpoint over the network with a genuine HMAC-signed, Warchief-identity +request: +```text +POST /hive/roles/degrade {role: Worker} -> 200 {"status":"ok","role":"Worker"} +POST /hive/roles/degrade {role: bogus} -> 400 (lists valid roles) +``` +Worker log confirmed the fire-and-forget recycle call completed with no error. + +**Real pre-existing bug found and fixed by this live test, not by inspection.** The first live +attempt got 403 "only the Warchief may force a role recycle" — against a request signed with +exactly the node id the worker's own `start-worker.bat` configures as its Warchief. +`HiveElectionService.WarchiefNodeId` turned out to be populated ONLY by live election-protocol +messages; nothing in `HiveService.cs` ever called `SetWarchief` from `_cfg.WarchiefNodeId`, even +though that value is already known from static config. **This meant `/hive/update/deploy` — the +existing, previously-shipped endpoint this new one's authorization pattern was modeled on — was +silently unusable in this exact deployment shape the whole time**, not just the new endpoint. +Fixed in `HiveService.cs`: call `election.SetWarchief(_cfg.WarchiefNodeId)` once at startup when +configured. Re-verified live after the fix — 200 on the happy path, confirmed via the worker's own +log line `[Election] ⚙ Warchief set to `. + +**HV-3 verdict, final: items 1, 2, and 3 all CLOSED.** Item 3's remote trigger exists, is +authenticated and authorized the same way the codebase's one existing mutation endpoint is, and +is proven working end-to-end on a real fleet machine — plus it fixed a real, previously-unnoticed +bug in that existing endpoint along the way. + ### HV-4 — Failure, cancellation, disconnect, recovery All on real jobs mid-flight, all asserting fail-closed (no Ollama substitution) and clean @@ -832,6 +869,86 @@ being declared dead (root-caused to the missing artifact store, fixed in `0e9db7 fail-closed no-fallback behaviour observed throughout — every completing job in every phase above carries `Attestation.RuntimeName == "NativeRoleRuntime"`. +**2026-07-29 — item 1's missing endpoint now exists: `POST /hive/tasks/cancel`, built alongside +HV-3 item 3's role-degrade endpoint (same session, same authorization pattern, same live +verification approach — full detail there).** `HiveWorkerAgent` gained a per-task +`CancellationTokenSource` registry, separate from the worker's own whole-process lifetime token: +each claimed task gets a linked token registered in `ClaimAndExecuteAsync` and removed in its +`finally`, so a remote cancel interrupts exactly one task's generation +(`OperationCanceledException` inside the loop, task reported `failed` to the Warchief) without +touching the poll loop or any other concurrently-running task. `HiveNodeServer`'s new endpoint +(Warchief-only, mirroring `/hive/update/deploy` and the new role-degrade endpoint) forwards to +`HiveWorkerAgent.TryCancelTask(taskId)`. + +**Live-verified against the real deployed daemon on HardcorePC:** +```text +POST /hive/tasks/cancel {taskId: } -> 404 "no in-flight task with this id on this worker" +POST /hive/tasks/cancel {} -> 400 "missing taskId" +``` +No task happened to be in flight on HardcorePC at verification time, so the "found and actually +cancels" path rests on code review + the linked-token mechanism (a well-established .NET pattern, +same technique already used for this method's own heartbeat-loop cancellation immediately above +it in the same file) rather than a live mid-generation interruption — the 404/400 paths prove the +routing, auth, and registry-miss handling all work correctly end-to-end on a real box, which is +the harder part to get wrong. + +**Item 1: the trigger now exists, but per CodeRabbit's correct catch on this same PR (#94), this +is still partial coverage, not "fully covered."** The plan's original ask — cancellation +surfacing mid-generation as an `OperationCanceledException` on the worker via a real remote +trigger — has that trigger built, authenticated, and live-verified for its routing/auth/ +validation paths (404/400 above). What has NOT been exercised live is the actual "found and +cancels a real in-flight generation" path — no task happened to be in flight on HardcorePC at +verification time, so that half rests on code review of the linked-token mechanism, not +observation. `Tools/Hv4RecoveryRunner`'s `cancel` phase still exercises only the Warchief-side +campaign-cancel path (a different, already-covered mechanism). Closing item 1 for real needs +either a live mid-generation cancel run or the harness wired to exercise this new endpoint +directly — neither done yet. + +**2026-07-29 (same day, before merge) — a Grok second-opinion review (PR #94, +`grok-review -Mode full`) caught a real BLOCKER in the first version of this endpoint, fixed +before merge: a remote cancel would have been silently retried, not stopped.** + +The first cut's `ClaimAndExecuteAsync` let a remote cancel's `OperationCanceledException` (from +`taskCts`, distinct from the worker's own whole-process `ct`) fall through to the generic +failure handler, posting `status: "failed"` back to the Warchief. `HiveTaskQueue.HandleFailAsync` +requeues campaign work whenever `Attempt < MaxAttempts` (default budget allows retries) — so an +operator hitting `/hive/tasks/cancel` would have gotten a `200 OK`, and the Warchief would have +quietly re-dispatched the exact same work to another attempt. The opposite of what cancel means, +and worse than not having the endpoint at all: a caller would reasonably believe the work stopped. + +**Fixed by giving remote cancellation its own terminal status instead of reusing "failed".** +`ClaimAndExecuteAsync` now catches `OperationCanceledException` specifically `when +(taskCts.IsCancellationRequested)` (checked before the generic handler) and reports +`status: "cancelled"` — posted through the same wire action/endpoint as a genuine failure +(`HiveWorkerAgent.cs`'s `action` decision doesn't need a new route), but `HiveTaskQueue. +HandleFailAsync` now reads that field first and skips its own requeue branch entirely when set, +setting the task's terminal status to `"cancelled"` — already a first-class status elsewhere in +the same class (the pre-existing Warchief-initiated campaign-cancel path), reused rather than +inventing a second vocabulary. Verified: full 687-test suite still green, HardcorePC redeployed +and re-verified healthy after the fix. + +**Also fixed from the same review pass, both real correctness/honesty issues, not just style:** +- `HandleMarkRoleDegraded` originally responded `200 OK` BEFORE its fire-and-forget call to the + handler ran, and swallowed any failure to a console line only — meaning the exact + `MissingMethodException` hit live during this endpoint's own deployment verification (wrong + assembly copied to HardcorePC, see HV-3 item 3's entry above) would have reported success on + the wire while doing nothing. Changed to `await` the handler and return `500` with the real + error on failure — a slightly slower response for an honest one. +- `/hive/update/deploy` still used its own inline Warchief check instead of the shared + `IsWarchief` helper the two new endpoints introduced; unified for one authorization code path + instead of two copies that could silently drift. + +**Two MINOR findings acknowledged, not fixed in this pass:** the Avalonia GUI's own +`HiveNodeServer`/`HiveWorkerAgent` construction (`MainWindow.axaml.cs`) never wires +`MarkRoleDegradedHandler`/`CancelTaskHandler`/`SetWarchief`, so a GUI-hosted worker would 503/403 +on these same endpoints — deferred because the GUI path has local observability a headless fleet +worker doesn't, and touching `MainWindow.axaml.cs`'s much larger runtime-construction code +carries more risk than this pass's scope justified; and test coverage for `IsWarchief`'s positive +match and `TryCancelTask`'s actual-cancellation path is still missing, blocked on the same +heavy-dependency-construction problem documented in `HiveNodeServerAuthorizationTests.cs`'s own +class doc comment (`HiveIdentity`'s constructor is private, only reachable via disk-touching +static factories). + ### HV-5 — Telemetry consistency + no-silent-fallback sweep - Same evidence JSON schema from all three boxes for one shared campaign; per-box diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b6fdae84..b200f38b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -34,7 +34,7 @@ v1.8.0 ships the Avalonia MarkdownView (Phase 6), the full FlaUI + Avalonia test **HIVE MIND node startup was broken on every normal-user install until 2026-06-20** — `HiveNodeServer.Start()` silently aborted (no error, no log line, nothing listening) on any non-elevated machine, because a failed wildcard `HttpListener` bind left the listener disposed internally and the fallback cleanup code's own property access threw a second, masking exception inside an unobserved `Task.Run`. Found via a pre-release smoke test specifically because nothing in automated test coverage exercises real socket binding. Fixed — verified `localhost:7078/hive/info` returns 200 and UDP 7077 beacon listens. This was a hard release blocker for any LAN/Tailscale HIVE MIND testing; not caught by `dotnet test` since the unit/headless suites mock or don't reach real listener startup. -The honest gaps: the Reviewer Quality Gate is advisory-only (can always be overridden), the Tool Editor hot-reload is a stub, and Phase 3B is implementation groundwork rather than a completed distributed-computing release. Native campaign contracts, capability-aware atomic leasing, persistence, content-addressed transfer, independent verification, the shared headless loop, fail-closed native-agent execution, staged campaign dependencies, native input-artifact materialization, and CF-6 distributed HIVE Context Fabric execution now exist in code. **WPF is deleted (2026-06-20)** — `OrchestratorIDE/OrchestratorIDE.csproj` and every WPF-only file are gone from the repo; Avalonia is the only desktop shell. `ask_user`, `ModelCapabilityTestDialog`, and `ToolCallTestWindow` all have real Avalonia resolutions (the latter two retired as diagnostics, not ported); `ModelWikiWindow`/`ModelCompareWindow` were retired rather than ported (data layer kept, window itself dropped — a future from-scratch Avalonia rebuild is a real feature request, not a blocker). The UIA automation lane already targeted Avalonia exclusively. Native Runtime groundwork is now real in code (IModelRuntime, Ollama wrapper, llama.cpp server wrapper, LLamaSharp runtime, shared text tool-call parser, Chat/Swarm/HIVE worker/reviewer migration, ModelDepot, SessionManager, AdapterManager with per-role persistent LoRA contexts, RuntimeOrchestrator wiring all three together, `IRoleRuntime`/`NativeRoleRuntime`, Settings-panel telemetry/smoke surfaces with explicit Ollama fallback and evidence capture, OrcScheduler VRAM-budget admission checks, workload-aware native model-admission, and CUDA backend-selection diagnostics for driver-only GPU nodes). It is still **not** production/default: native main chat and native HIVE workers are opt-in; legacy paths may retain configured fallback behavior, while native campaign jobs fail closed and do not fall back to Ollama. Context Fabric CF-0 through CF-8 have landed their focused framework/distribution/benchmark/hard-ingestion gates, and **the CF-7 benchmark gate closed GO on the honest, un-marked corpus (2026-07-17, v1.13.0)** — `cf-expanded-book-v1`, 128 segments, 120 real held-out questions, Qwen3.5-9B at 104/120 questions, 97.1% citation precision, 128/128 segments read, best competing baseline 52/120. This GO replaces (does not merely re-confirm) the retracted 2026-07-03 GO, which was found to have scored against a corpus containing marked/leaked evidence lines. Unattended million-token/LongBench runs and full multimodal page understanding remain future benchmark/product work. +The honest gaps: the Reviewer Quality Gate is advisory-only (can always be overridden), the Tool Editor hot-reload is a stub, and Phase 3B is implementation groundwork rather than a completed distributed-computing release. Native campaign contracts, capability-aware atomic leasing, persistence, content-addressed transfer, independent verification, the shared headless loop, fail-closed native-agent execution, staged campaign dependencies, native input-artifact materialization, and CF-6 distributed HIVE Context Fabric execution now exist in code. **WPF is deleted (2026-06-20)** — `OrchestratorIDE/OrchestratorIDE.csproj` and every WPF-only file are gone from the repo; Avalonia is the only desktop shell. `ask_user`, `ModelCapabilityTestDialog`, and `ToolCallTestWindow` all have real Avalonia resolutions (the latter two retired as diagnostics, not ported); `ModelWikiWindow`/`ModelCompareWindow` were retired rather than ported (data layer kept, window itself dropped — a future from-scratch Avalonia rebuild is a real feature request, not a blocker). The UIA automation lane already targeted Avalonia exclusively. Native Runtime groundwork is now real in code (IModelRuntime, Ollama wrapper, llama.cpp server wrapper, LLamaSharp runtime, shared text tool-call parser, Chat/Swarm/HIVE worker/reviewer migration, ModelDepot, SessionManager, AdapterManager with per-role persistent LoRA contexts, RuntimeOrchestrator wiring all three together, `IRoleRuntime`/`NativeRoleRuntime`, Settings-panel telemetry/smoke surfaces with explicit Ollama fallback and evidence capture, OrcScheduler VRAM-budget admission checks, workload-aware native model-admission, and CUDA backend-selection diagnostics for driver-only GPU nodes). **As of 2026-07-29, native main chat and native HIVE workers are the default** (`NATIVE_RUNTIME_V2_SPEC.md` §6, recorded against `NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md`'s HV-6 fleet evidence); Ollama remains available and configurable as a fallback backend, while native campaign jobs fail closed and do not fall back to Ollama. Context Fabric CF-0 through CF-8 have landed their focused framework/distribution/benchmark/hard-ingestion gates, and **the CF-7 benchmark gate closed GO on the honest, un-marked corpus (2026-07-17, v1.13.0)** — `cf-expanded-book-v1`, 128 segments, 120 real held-out questions, Qwen3.5-9B at 104/120 questions, 97.1% citation precision, 128/128 segments read, best competing baseline 52/120. This GO replaces (does not merely re-confirm) the retracted 2026-07-03 GO, which was found to have scored against a corpus containing marked/leaked evidence lines. Unattended million-token/LongBench runs and full multimodal page understanding remain future benchmark/product work. --- @@ -660,8 +660,19 @@ and run as a service before the GUI-as-client changeover happens. > anymore), and C (real telemetry) are landed. Phase D (real-model native-path proof lane) is > essentially complete: the negative fail-closed test and the cancellation leg (which caught and > fixed a real executor-corruption bug) are landed; the real-model E2E lane with a retained -> evidence artifact (PR #81) has landed too, verified on real hardware. None of this changes -> the default runtime or Ollama's role as fallback — see that spec's explicit out-of-scope list. +> evidence artifact (PR #81) has landed too, verified on real hardware. +> +> **Status changed 2026-07-29 — native IS now the default, superseding every "not the default +> yet" line in this section below.** `NATIVE_RUNTIME_V2_SPEC.md` §6's gated milestone (live +> multi-machine HIVE validation, `docs/NATIVE_RUNTIME_HIVE_VALIDATION_PLAN.md` HV-1 through +> HV-6) completed with HV-6 at genuine 3×-repeated, 9/9-lane evidence, and the explicit product +> decision that milestone requires was recorded the same day. +> `AppSettings.ExperimentalNativeHiveWorkerEnabled`/`ExperimentalNativeMainChatEnabled` now +> default to `true`. Ollama remains fully implemented and available as `IModelRuntime`'s other +> backend — installs can still opt back out — it is simply no longer the default construction +> path in `MainWindow`'s HIVE-worker and main-chat runtime builders. The "until the ModelDepot + +> installer first-run story is bulletproof..." criterion further down this section is superseded +> by that decision, made against the HV-6 evidence instead. **What it is:** an orchestration / swarm-aware layer *on top of* LLamaSharp (llama.cpp bindings) — **not** a from-scratch inference engine. llama.cpp owns the kernels; TheOrc owns scheduling, session management, adapter hot-swap, VRAM-aware dispatch, and direct Avalonia streaming. The moat is making the warband feel like one cohesive mind on the GPU instead of a series of independent HTTP calls. @@ -669,17 +680,17 @@ and run as a service before the GUI-as-client changeover happens. | Phase | Scope | Status | Risk | |---|---|---|---| -| **0** | `IModelRuntime` abstraction + `OllamaRuntime` wrapper. | ✅ Landed — local generation paths can depend on the runtime interface; Ollama remains default. | Low | +| **0** | `IModelRuntime` abstraction + `OllamaRuntime` wrapper. | ✅ Landed — local generation paths can depend on the runtime interface; native is now the default as of the 2026-07-29 §6 flip (Ollama remains available, fallback). | Low | | **1** | `LlamaCppServerRuntime` — wraps the **existing** `LlamaServerManager` + `InferenceBackend.LlamaCpp`. | ✅ Landed — server lifecycle and HTTP routing exist behind the runtime interface. | Low | -| **2** | `LLamaSharpRuntime` — in-process GGUF streaming, embedded-template probing, stats, shared text tool-call parsing. | ⚠️ Prototype landed — useful for validation, not production/default. LoRA hot-swap, backend install flow, and full runtime selection are not complete. | Med | +| **2** | `LLamaSharpRuntime` — in-process GGUF streaming, embedded-template probing, stats, shared text tool-call parsing. | ⚠️ Prototype landed — this row is about the *prototype's own completeness*, not runtime-selection default status (native IS the default as of the 2026-07-29 §6 flip, see the box above): LoRA hot-swap, backend install flow, and full runtime selection are not complete. | Med | | **2.5** | Close abstraction leaks from the first migration. | ✅ Closed for `HiveWorkerAgent` and reviewer inference — both use `IModelRuntime`; SwarmSession's Ollama-specific eviction escape hatch and remote HIVE task-queue/node HTTP remain separate follow-up plumbing. | Med | -| **3** | `ModelDepot` (local registry first; downloader later), `SessionManager` (persistent base model), `AdapterManager` (boss/worker/reviewer LoRAs), telemetry. | 🔶 Live opt-in proof path landed — ModelDepot, SessionManager, AdapterManager (per-role persistent executors, adapter attached once at creation per the §7 verdict), and `RuntimeOrchestrator` all landed; `IRoleRuntime`/`NativeRoleRuntime` now stream that role stack, `THEORC_TEST_GGUF` has an opt-in role-runtime smoke lane, Avalonia Settings exposes manual native smoke/fallback/evidence capture, and `HiveWorkerAgent` can opt into native role execution with logged fallback to the configured model runtime. Telemetry surfacing and the OrcScheduler/AdapterManager wiring below are now landed (NATIVE_RUNTIME_V2_SPEC.md Phases A/C). The per-role VRAM cost estimate is now KV/rs-cache-aware (a byte-exact GGUF-header formula, arch-gated for recurrent architectures) with a real load-time measurement on top parsed from llama.cpp's own log lines, replacing the WDDM-dead nvidia-smi per-process read — both landed (Phase B addendum). Real-model proof (Phase D) is essentially complete: negative fail-closed test, cancellation-corruption fix, and an E2E lane with a retained evidence artifact (25.7 tok/s, 284ms TTFT, 2.5GB measured VRAM on the reference box) are built and verified; do not make native the main chat/swarm default yet. | Med-High | +| **3** | `ModelDepot` (local registry first; downloader later), `SessionManager` (persistent base model), `AdapterManager` (boss/worker/reviewer LoRAs), telemetry. | 🔶 Live proof path landed — no longer opt-in as of the 2026-07-29 §6 flip (it's the default path now, not a manually-enabled one). ModelDepot, SessionManager, AdapterManager (per-role persistent executors, adapter attached once at creation per the §7 verdict), and `RuntimeOrchestrator` all landed; `IRoleRuntime`/`NativeRoleRuntime` now stream that role stack, `THEORC_TEST_GGUF` has an opt-in role-runtime smoke lane, Avalonia Settings exposes manual native smoke/fallback/evidence capture, and `HiveWorkerAgent` can opt into native role execution with logged fallback to the configured model runtime. Telemetry surfacing and the OrcScheduler/AdapterManager wiring below are now landed (NATIVE_RUNTIME_V2_SPEC.md Phases A/C). The per-role VRAM cost estimate is now KV/rs-cache-aware (a byte-exact GGUF-header formula, arch-gated for recurrent architectures) with a real load-time measurement on top parsed from llama.cpp's own log lines, replacing the WDDM-dead nvidia-smi per-process read — both landed (Phase B addendum). Real-model proof (Phase D) is essentially complete: negative fail-closed test, cancellation-corruption fix, and an E2E lane with a retained evidence artifact (25.7 tok/s, 284ms TTFT, 2.5GB measured VRAM on the reference box) are built and verified. **Native is now the main chat/swarm default as of 2026-07-29** (§6 flip, recorded against HV-6 evidence). | Med-High | | **4** | `OrcScheduler` — capability + VRAM + lane-aware dispatch; pipeline boss→workers. | 🔶 Started — interface + data model + a real VRAM-budget admission check landed; `RuntimeOrchestrator` now tracks active per-role reservations (generation-tagged, serialized through one admission gate) instead of a static zero-reserved snapshot, closing the over-admission gap the static check left open. NATIVE_RUNTIME_V2_SPEC.md Phase A closed the "not wired into AdapterManager" gap this row used to flag: `AdapterManager`'s conversation-minting methods are now `internal`, reachable only through `RuntimeOrchestrator`'s admission gate, and admission fails closed (not open) when no budget is configured. Phase B added a live nvidia-smi VRAM read in place of the static zero-reserved snapshot. Still no live GPU dispatch or pipeline queueing. | High | | **5** | *(Research, non-blocking)* prefix KV cache for the shared warband prompt; multi-LoRA cache experiments. | ✅ Research closed — `Conversation.Fork()`/`MemorySequenceCopy` is a real, cheap shared-prefix mechanism, confirmed via LLamaSharp's own XML docs; blocked for cross-role sharing because `SetLoraAdapters` is context-scoped, not per-sequence — same-role prefix forking remains a viable future win, see `.grok/PREFIX_KV_CACHE_RESEARCH.md`. | Research | **Caveat (permanent, now mechanically confirmed — not just inferred):** shared KV cache across *different* LoRA-specialized agents is not guaranteed safe — adapters change activations, and LLamaSharp 0.27.0's `SetLoraAdapters` applies per-context, not per-sequence, so forked sequences sharing a context cannot run different adapters. Start with simple prefix caching of the common system prompt only **within one role**; cross-role sharing is research, never a promised deliverable. LoRA hot-swap requires a verification spike before it joins a committed phase — that spike ran (§7), and the verdict (separate persistent contexts per role) is implemented in `AdapterManager`. -Ollama stays the **default and fallback** until the ModelDepot + installer first-run story is bulletproof and the reviewer/Swarm abstraction leaks are closed. +~~Ollama stays the **default and fallback** until the ModelDepot + installer first-run story is bulletproof and the reviewer/Swarm abstraction leaks are closed.~~ **Superseded 2026-07-29:** native is now the default, per the §6 decision recorded against live HV-6 fleet evidence rather than this criterion. Ollama remains the fallback backend. ### Native runtime function priorities