Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions src/Capacitor.Cli/Commands/Harness/CursorHookCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,17 @@ internal static async Task<int> HandleCore(
Func<string?, CancellationToken, Task<HttpClient>>? memoryClientFactory = null,
Func<SessionStartMemoryLeaseStore>? memoryStoreFactory = null,
TimeSpan? memoryBudgetOverride = null,
ISessionStartMemoryScopeResolver? memoryScopeResolver = null
ISessionStartMemoryScopeResolver? memoryScopeResolver = null,
// Testability seam: drives the memory-budget timer so a test can fire it deterministically
// after the request has entered its handler. Production leaves it null (system clock).
TimeProvider? memoryBudgetClock = null
) {
using var cts = new CancellationTokenSource(budgetTotal);
var kindSignal = new ResolvedEventKindSignal();

var inner = HandleCoreInner(client, baseUrl, stdin, spool, budgetTotal, cts.Token, kindSignal,
memoryClientFactory, memoryStoreFactory, memoryBudgetOverride, memoryScopeResolver);
memoryClientFactory, memoryStoreFactory, memoryBudgetOverride, memoryScopeResolver,
memoryBudgetClock);
var deadline = Task.Delay(budgetTotal);
var winner = await Task.WhenAny(inner, deadline);

Expand Down Expand Up @@ -226,7 +230,8 @@ sealed class ResolvedEventKindSignal {
Func<string?, CancellationToken, Task<HttpClient>>? memoryClientFactory,
Func<SessionStartMemoryLeaseStore>? memoryStoreFactory,
TimeSpan? memoryBudgetOverride,
ISessionStartMemoryScopeResolver? memoryScopeResolver
ISessionStartMemoryScopeResolver? memoryScopeResolver,
TimeProvider? memoryBudgetClock
) {
var sw = Stopwatch.StartNew();
bool BudgetExpired() => sw.Elapsed >= budgetTotal;
Expand Down Expand Up @@ -512,7 +517,8 @@ await CursorTranscriptBackfill.RunAsync(
if (eventName != "sessionStart") return null;
var fragment = await RunMemoryOrchestrationAsync(
client, baseUrl, sessionId, workspaceRoot, sw, budgetTotal, ct,
memoryClientFactory, memoryStoreFactory, memoryBudgetOverride, memoryScopeResolver);
memoryClientFactory, memoryStoreFactory, memoryBudgetOverride, memoryScopeResolver,
memoryBudgetClock);
// The static work-items nudge, isolated from the lease-driven fragment above and
// merged only at render. The opt-out flag is not in scope here (it lives inside the
// orchestration), so re-read it; sessionStart fires once per session and the read is
Expand Down Expand Up @@ -555,7 +561,8 @@ await CursorTranscriptBackfill.RunAsync(
Func<string?, CancellationToken, Task<HttpClient>>? memoryClientFactory,
Func<SessionStartMemoryLeaseStore>? memoryStoreFactory,
TimeSpan? memoryBudgetOverride,
ISessionStartMemoryScopeResolver? memoryScopeResolver
ISessionStartMemoryScopeResolver? memoryScopeResolver,
TimeProvider? memoryBudgetClock
) {
if (sessionId is null) return null;

Expand All @@ -577,8 +584,10 @@ await CursorTranscriptBackfill.RunAsync(
if (disabled && guidelinesDisabled) return null;

try {
using var memCts = CancellationTokenSource.CreateLinkedTokenSource(dispatcherCt);
memCts.CancelAfter(memBudget);
// The budget timer runs on memoryBudgetClock (system clock in production); a test can
// pass a fake clock and advance it to fire this deadline deterministically.
using var budgetCts = new CancellationTokenSource(memBudget, memoryBudgetClock ?? TimeProvider.System);
using var memCts = CancellationTokenSource.CreateLinkedTokenSource(dispatcherCt, budgetCts.Token);

var store = memoryStoreFactory?.Invoke() ?? new SessionStartMemoryLeaseStore();
// Both lanes share the one factory (the shared hook client by default). disposeClients is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,11 @@ public async Task Stop_force_alone_without_all_or_an_id_still_reports_usage() {
// A string, not ArgumentList: quote-aware parsing, so an argument may contain a space.
psi.Arguments = $"{argLine} --no-update-check";

// Isolate from the developer's own profile so these assertions don't depend on whether
// this machine happens to have a server configured.
// Isolate the config surface to a FRESH dir: clearing KCAP_URL alone isn't enough — the CLI
// also reads a persisted profile under the assembly's SHARED KCAP_CONFIG_DIR, which a sibling
// test can populate. A per-call dir makes KCAP_URL the only server signal.
using var configDir = new TempDir();
psi.Environment["KCAP_CONFIG_DIR"] = configDir.Path;
psi.Environment["KCAP_URL"] = clearServerUrl ? "" : "http://127.0.0.1:1";

using var process = Process.Start(psi)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Capacitor.Cli.Core.Harness.Cursor;
using Capacitor.Cli.Harness.Cursor;
using Capacitor.Cli.SessionStartMemory;
using Microsoft.Extensions.Time.Testing;

namespace Capacitor.Cli.Tests.Unit.Commands.Harness;

Expand Down Expand Up @@ -875,21 +876,31 @@ public async Task CancelledFetch_leaves_lease_uncommitted() {
var handler = new CancelAwareHandler();
using var neverRespondingClient = new HttpClient(handler);

// Nothing here is wall-clock derived: the override pins the memory stage's budget, the stub
// resolver keeps a git spawn out of it, and budgetTotal sits far enough above the inner
// phase that the outer deadline can't pre-empt it. The 250ms is the cancellation window.
// Deterministic, not wall-clock: the memory budget runs on a FakeTimeProvider, so the 250ms
// deadline fires only when the test advances the clock — after the request has entered the
// handler (EnteredSignal). That removes the entry race the real 250ms budget had while still
// cancelling through the production budget token (not the 15s outer deadline, never advanced
// here). The stub resolver keeps a git spawn out of the path.
var budgetClock = new FakeTimeProvider();
var elapsed = System.Diagnostics.Stopwatch.StartNew();
var exit1 = await CursorHookCommand.HandleCore(
var call = CursorHookCommand.HandleCore(
fx.Client, "http://localhost", new StringReader(payload), fx.Spool, TimeSpan.FromSeconds(15),
memoryClientFactory: (_, _) => Task.FromResult(neverRespondingClient),
memoryStoreFactory: storeFactory,
memoryBudgetOverride: TimeSpan.FromMilliseconds(250),
memoryScopeResolver: new StubScopeResolver());
memoryScopeResolver: new StubScopeResolver(),
memoryBudgetClock: budgetClock);

// Wait (bounded, real-time) for the request to ENTER the handler, then fire the budget clock.
await handler.EnteredSignal.Task.WaitAsync(TimeSpan.FromSeconds(30));
budgetClock.Advance(TimeSpan.FromMilliseconds(250));

var exit1 = await call;
elapsed.Stop();
await Assert.That(exit1).IsEqualTo(0);
// Entered rules out a skipped attempt (which would prove nothing); Cancelled rules out the
// request being abandoned by a wrapper while it kept running; and returning far inside the
// 15s deadline rules that deadline out as the thing that ended it, leaving the 250ms budget.
// Cancelled fires only because advancing the budget clock cancelled the request's OWN token —
// proving the memory-budget token governs the fetch. Entered rules out a skipped attempt, and
// returning far inside the 15s outer deadline rules that out as the cause.
await Assert.That(handler.Entered).IsTrue();
await Assert.That(handler.Cancelled).IsTrue();
await Assert.That(elapsed.Elapsed.TotalSeconds).IsLessThan(10);
Expand Down Expand Up @@ -1131,19 +1142,21 @@ public Task<SessionStartMemoryScope> ResolveAsync(string? cwd, TimeSpan budget,
Task.FromResult(new SessionStartMemoryScope(RepoHash: null, MachineTag: "test-machine"));
}

// A GET that never resolves on its own — it only ends via the caller's own
// cancellation, honoured properly (unlike StubHandler, which ignores its ct). Used to
// prove a memory fetch cancelled at the budget deadline leaves the lease uncommitted
// rather than committing a spurious "completed" record.
// A GET that never resolves on its own — it ends only when its OWN CancellationToken (the memory
// budget/deadline) fires, honoured properly (unlike StubHandler, which ignores ct). Signals entry
// so the test advances the budget clock strictly after the request has entered.
sealed class CancelAwareHandler : HttpMessageHandler {
volatile bool _entered;
volatile bool _cancelled;
// Separate "never fetched at all", "fetched and abandoned", and "fetched and cancelled".
public bool Entered => _entered;
public bool Cancelled => _cancelled;
// Fires the moment SendAsync is entered, so the test advances the budget clock only after entry.
public TaskCompletionSource EnteredSignal { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct) {
_entered = true;
EnteredSignal.TrySetResult();
try {
await Task.Delay(Timeout.InfiniteTimeSpan, ct);
} catch (OperationCanceledException) {
Expand Down