Grossaufgaben und Sonderbudget (#717, Stufe 2+3)
Eine Aufgabe, deren eigene Schaetzung (gemessen, Geschwister oder Autor) ueber der Haelfte der Tageskostengrenze liegt, bekommt zuerst einen Planungslauf: teilen (Teile unter der Elternaufgabe) oder Sonderbudget beantragen. Danach wartet sie auf ihre Teile bzw. die Freigabe und laeuft einmal zum Zusammenfuehren. Sonderbudget ueber Escalation.request_budget, ausnahmslos freigabepflichtig (auch gegen Werkzeugkonfiguration und Dauerfreigabe). Laeufe im Baum ziehen den Topf statt der Tagesgrenzen, tragen BudgetPot in Verbrauch und Beleg und sind in der Kostenanalyse (nach Budget) und auf der Aufgabenkarte gesondert sichtbar. Aufgebraucht zaehlen sie wieder gegen den Tag. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
183e922278
commit
67649559f5
@@ -54,6 +54,9 @@ public sealed class BudgetGuard
|
||||
private readonly Dictionary<string, RunEstimate> _reservedByAgent = new(StringComparer.OrdinalIgnoreCase);
|
||||
private RunEstimate _reservedInstance;
|
||||
|
||||
/// <summary>#717: What runs in flight have reserved of each special budget.</summary>
|
||||
private readonly Dictionary<string, RunEstimate> _reservedByPot = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public BudgetGuard(IUsageRepository usage, Func<DateTime>? now = null)
|
||||
{
|
||||
_usage = usage;
|
||||
@@ -109,7 +112,7 @@ public sealed class BudgetGuard
|
||||
_reservedInstance += estimate;
|
||||
}
|
||||
|
||||
return (status, new Reservation(this, agent.AgentId, estimate));
|
||||
return (status, new Reservation(() => Release(agent.AgentId, estimate)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -117,9 +120,49 @@ public sealed class BudgetGuard
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #717: Reserves a run on a special budget instead of the daily limits. Refused once what
|
||||
/// the pot's runs used, plus what runs in flight reserved, has reached the amount — the
|
||||
/// same rule as for the daily limit: a run is not refused for its own estimate.
|
||||
/// </summary>
|
||||
public async Task<IDisposable?> ReservePotAsync(SpecialBudget pot, decimal spent, string agentId, CancellationToken ct)
|
||||
{
|
||||
var estimate = await EstimateRunAsync(agentId, ct);
|
||||
|
||||
await _reserveGate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
lock (_reservedLock)
|
||||
{
|
||||
var reserved = _reservedByPot.GetValueOrDefault(pot.TaskId);
|
||||
if (spent + reserved.CostUsd >= pot.AmountUsd)
|
||||
return null;
|
||||
_reservedByPot[pot.TaskId] = reserved + estimate;
|
||||
}
|
||||
|
||||
return new Reservation(() => ReleasePot(pot.TaskId, estimate));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reserveGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleasePot(string potId, RunEstimate estimate)
|
||||
{
|
||||
lock (_reservedLock)
|
||||
{
|
||||
var left = _reservedByPot.GetValueOrDefault(potId) - estimate;
|
||||
if (left.CostUsd <= 0 && left.Tokens <= 0)
|
||||
_reservedByPot.Remove(potId);
|
||||
else
|
||||
_reservedByPot[potId] = left;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Today's usage of an agent, or with an empty id of the whole instance.</summary>
|
||||
public Task<DailyUsage> GetUsedTodayAsync(string agentId, CancellationToken ct)
|
||||
=> _usage.GetDailyAsync(DateOnly.FromDateTime(_now()), agentId, ct);
|
||||
=> _usage.GetDailyForBudgetAsync(DateOnly.FromDateTime(_now()), agentId, ct);
|
||||
|
||||
/// <summary>What is currently reserved by runs in flight — for the agent, or with an
|
||||
/// empty id for the whole instance.</summary>
|
||||
@@ -159,14 +202,14 @@ public sealed class BudgetGuard
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Reservation(BudgetGuard guard, string agentId, RunEstimate estimate) : IDisposable
|
||||
private sealed class Reservation(Action release) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
guard.Release(agentId, estimate);
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +223,7 @@ public sealed class BudgetGuard
|
||||
var agentBudget = agent.Budget;
|
||||
if (agentBudget.HasAnyLimit)
|
||||
{
|
||||
var used = await _usage.GetDailyAsync(today, agent.AgentId, ct);
|
||||
var used = await _usage.GetDailyForBudgetAsync(today, agent.AgentId, ct);
|
||||
|
||||
if (Exceeds(agentBudget.DailyCostUsd, used.CostUsd + agentReserved.CostUsd))
|
||||
{
|
||||
@@ -203,7 +246,7 @@ public sealed class BudgetGuard
|
||||
// Instanzgrenze — gilt für alle Agenten zusammen
|
||||
if (instanceBudget.HasAnyLimit)
|
||||
{
|
||||
var used = await _usage.GetDailyAsync(today, agentId: "", ct);
|
||||
var used = await _usage.GetDailyForBudgetAsync(today, agentId: "", ct);
|
||||
|
||||
if (Exceeds(instanceBudget.DailyCostUsd, used.CostUsd + instanceReserved.CostUsd))
|
||||
{
|
||||
@@ -232,7 +275,7 @@ public sealed class BudgetGuard
|
||||
if (agent.Budget.DailyCostUsd <= 0)
|
||||
return null;
|
||||
|
||||
var used = await _usage.GetDailyAsync(DateOnly.FromDateTime(_now()), agent.AgentId, ct);
|
||||
var used = await _usage.GetDailyForBudgetAsync(DateOnly.FromDateTime(_now()), agent.AgentId, ct);
|
||||
return Math.Max(0m, agent.Budget.DailyCostUsd - used.CostUsd);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Globalization;
|
||||
using ClawdDotNet.Core.Config;
|
||||
using ClawdDotNet.Core.Tasks;
|
||||
|
||||
namespace ClawdDotNet.Core.Budget;
|
||||
|
||||
/// <summary>
|
||||
/// #717: A task whose estimate exceeds a large share of the agent's daily cost limit (default
|
||||
/// half) is not simply started. Its run plans instead: split it into parts, or ask a human for
|
||||
/// a special budget. Which way, the agent proposes; a special budget is always a human's call.
|
||||
///
|
||||
/// <para><b>Only on an estimate of this task.</b> Measured runs, its siblings' runs, or its
|
||||
/// author's estimate. The agent's average run says nothing about one task — were it enough, an
|
||||
/// agent with expensive runs would have every task stopped for planning.</para>
|
||||
///
|
||||
/// <para>Not for a task already split (it has parts), nor for one in a funded tree, nor for a
|
||||
/// recurring one — its runs are the day's regular work and have their own limit.</para>
|
||||
/// </summary>
|
||||
public sealed class LargeTaskCheck(
|
||||
TaskCostEstimator estimator,
|
||||
ITaskRepository tasks,
|
||||
ISpecialBudgetRepository? pots,
|
||||
Func<IReadOnlyList<AgentConfig>> agents,
|
||||
Func<FillWorkSettings> settings) : ILargeTaskCheck
|
||||
{
|
||||
public async Task<string?> PlanningInstructionAsync(TaskItem task, CancellationToken ct)
|
||||
{
|
||||
var agentId = TaskAssignee.AgentId(task.Assignee);
|
||||
var agent = agents().FirstOrDefault(a => string.Equals(a.AgentId, agentId, StringComparison.OrdinalIgnoreCase));
|
||||
var share = settings().LargeTaskShare;
|
||||
if (agent is not { Budget.DailyCostUsd: > 0 } || share <= 0)
|
||||
return null;
|
||||
|
||||
if (await IsFundedAsync(task, ct) || (await tasks.ListChildrenAsync(task.Id, ct)).Count > 0)
|
||||
return null;
|
||||
|
||||
var estimate = await estimator.EstimateAsync(task, ct);
|
||||
if (estimate.Source is EstimateSource.AgentAverage or EstimateSource.None)
|
||||
return null;
|
||||
|
||||
var threshold = agent.Budget.DailyCostUsd * share;
|
||||
return estimate.Run.CostUsd > threshold
|
||||
? Instruction(task, estimate, agent.Budget.DailyCostUsd, share)
|
||||
: null;
|
||||
}
|
||||
|
||||
public async Task<bool> IsFundedAsync(TaskItem task, CancellationToken ct)
|
||||
=> pots is not null && await SpecialBudgets.FindAsync(task.Id, tasks, pots, ct) is not null;
|
||||
|
||||
/// <summary>What the planning run is told — ahead of the task itself.</summary>
|
||||
public static string Instruction(TaskItem task, TaskEstimate estimate, decimal dailyLimit, decimal share)
|
||||
{
|
||||
var limit = dailyLimit.ToString("0.00", CultureInfo.InvariantCulture);
|
||||
var percent = (share * 100).ToString("0", CultureInfo.InvariantCulture);
|
||||
return $"""
|
||||
[Planning run — from the system, not from the task's author]
|
||||
Task {task.Id} is large: one run is expected to cost {FillWorkNotice.Describe(estimate)}, more than {percent} % of your daily budget of {limit} USD.
|
||||
Do not start the work in this run. Propose one of two ways:
|
||||
1. Split it: create parts with the taskboard (task_create, parent='{task.Id}'), each able to run on its own and small enough for a day. Parts that are not urgent can be fill work (fill_by). Task {task.Id} waits until its parts are done and then runs once more to bring them together.
|
||||
2. Ask for a special budget: Escalation, action request_budget, with task='{task.Id}', amount_usd and reasoning. A human decides. The budget is for this task and its parts only.
|
||||
End with one or two sentences: which way, and why.
|
||||
""";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Globalization;
|
||||
using ClawdDotNet.Core.Storage;
|
||||
using ClawdDotNet.Core.Tasks;
|
||||
|
||||
namespace ClawdDotNet.Core.Budget;
|
||||
|
||||
/// <summary>
|
||||
/// #717: A special budget — an amount for exactly one task and everything below it, approved
|
||||
/// by a human.
|
||||
///
|
||||
/// <para><b>The one exception to "budgets stay at the agent" (concept 8a).</b> It is a pot of
|
||||
/// its own: runs in the task tree draw on it instead of the agent's daily limit, so a large
|
||||
/// job neither eats the day's regular work nor fails at the daily limit halfway. It does not
|
||||
/// raise the daily limit — work outside the tree never sees it — and it is never silent: it
|
||||
/// exists only through a human's approval (staging), and its runs are marked in the cost
|
||||
/// analysis. Once it is used up, the tree's runs count against the daily budget again, like
|
||||
/// any other work.</para>
|
||||
/// </summary>
|
||||
public sealed record SpecialBudget
|
||||
{
|
||||
/// <summary>The task at the top of the tree the pot is for.</summary>
|
||||
public string TaskId { get; init; } = "";
|
||||
|
||||
public decimal AmountUsd { get; init; }
|
||||
public string Reason { get; init; } = "";
|
||||
|
||||
/// <summary>The agent that asked for it.</summary>
|
||||
public string RequestedBy { get; init; } = "";
|
||||
|
||||
public DateTime ApprovedAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>#717: Where special budgets are kept, and what they have used so far.</summary>
|
||||
public interface ISpecialBudgetRepository
|
||||
{
|
||||
Task<SpecialBudget?> GetAsync(string taskId, CancellationToken ct);
|
||||
|
||||
/// <summary>Sets or replaces the pot of a task — a second approval replaces the amount.</summary>
|
||||
Task SetAsync(SpecialBudget budget, CancellationToken ct);
|
||||
|
||||
Task<IReadOnlyList<SpecialBudget>> ListAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>What runs have drawn on the pot, from the usage records marked with it.</summary>
|
||||
Task<decimal> SpentAsync(string taskId, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class SqliteSpecialBudgetRepository(SqliteStorage storage) : ISpecialBudgetRepository
|
||||
{
|
||||
public async Task<SpecialBudget?> GetAsync(string taskId, CancellationToken ct)
|
||||
{
|
||||
await using var conn = await storage.OpenConnectionAsync(ct);
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT TaskId, AmountUsd, Reason, RequestedBy, ApprovedAt FROM SpecialBudgets WHERE TaskId = @id COLLATE NOCASE";
|
||||
cmd.Parameters.AddWithValue("@id", taskId.Trim());
|
||||
await using var reader = await cmd.ExecuteReaderAsync(ct);
|
||||
return await reader.ReadAsync(ct) ? Read(reader) : null;
|
||||
}
|
||||
|
||||
public Task SetAsync(SpecialBudget budget, CancellationToken ct)
|
||||
=> storage.WriteAsync(async conn =>
|
||||
{
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO SpecialBudgets (TaskId, AmountUsd, Reason, RequestedBy, ApprovedAt)
|
||||
VALUES (@id, @amount, @reason, @by, @at)
|
||||
ON CONFLICT(TaskId) DO UPDATE SET
|
||||
AmountUsd = excluded.AmountUsd, Reason = excluded.Reason,
|
||||
RequestedBy = excluded.RequestedBy, ApprovedAt = excluded.ApprovedAt
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("@id", budget.TaskId.Trim());
|
||||
cmd.Parameters.AddWithValue("@amount", budget.AmountUsd.ToString(CultureInfo.InvariantCulture));
|
||||
cmd.Parameters.AddWithValue("@reason", budget.Reason);
|
||||
cmd.Parameters.AddWithValue("@by", budget.RequestedBy);
|
||||
cmd.Parameters.AddWithValue("@at", budget.ApprovedAt.ToUniversalTime().ToString("O"));
|
||||
await cmd.ExecuteNonQueryAsync(ct);
|
||||
}, ct);
|
||||
|
||||
public async Task<IReadOnlyList<SpecialBudget>> ListAsync(CancellationToken ct)
|
||||
{
|
||||
await using var conn = await storage.OpenConnectionAsync(ct);
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT TaskId, AmountUsd, Reason, RequestedBy, ApprovedAt FROM SpecialBudgets ORDER BY ApprovedAt DESC";
|
||||
var result = new List<SpecialBudget>();
|
||||
await using var reader = await cmd.ExecuteReaderAsync(ct);
|
||||
while (await reader.ReadAsync(ct))
|
||||
result.Add(Read(reader));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<decimal> SpentAsync(string taskId, CancellationToken ct)
|
||||
{
|
||||
await using var conn = await storage.OpenConnectionAsync(ct);
|
||||
using var cmd = conn.CreateCommand();
|
||||
// Amounts are text (exact decimals); summed here, not in SQL.
|
||||
cmd.CommandText = "SELECT CostUsd FROM RunUsage WHERE BudgetPot = @id COLLATE NOCASE";
|
||||
cmd.Parameters.AddWithValue("@id", taskId.Trim());
|
||||
var spent = 0m;
|
||||
await using var reader = await cmd.ExecuteReaderAsync(ct);
|
||||
while (await reader.ReadAsync(ct))
|
||||
spent += decimal.TryParse(reader.GetString(0), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : 0m;
|
||||
return spent;
|
||||
}
|
||||
|
||||
private static SpecialBudget Read(Microsoft.Data.Sqlite.SqliteDataReader r) => new()
|
||||
{
|
||||
TaskId = r.GetString(0),
|
||||
AmountUsd = decimal.TryParse(r.GetString(1), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : 0m,
|
||||
Reason = r.GetString(2),
|
||||
RequestedBy = r.GetString(3),
|
||||
ApprovedAt = DateTime.TryParse(r.GetString(4), null, DateTimeStyles.RoundtripKind, out var at) ? at : DateTime.MinValue
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>#717: Finding the pot a task draws on — its own, or the nearest one above it.</summary>
|
||||
public static class SpecialBudgets
|
||||
{
|
||||
/// <summary>A tree deeper than this is a mistake, not a plan; the walk stops there.</summary>
|
||||
private const int MaxDepth = 32;
|
||||
|
||||
public static async Task<SpecialBudget?> FindAsync(
|
||||
string taskId, ITaskRepository tasks, ISpecialBudgetRepository pots, CancellationToken ct)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var current = taskId.Trim();
|
||||
for (var depth = 0; depth < MaxDepth && current.Length > 0 && seen.Add(current); depth++)
|
||||
{
|
||||
if (await pots.GetAsync(current, ct) is { } pot)
|
||||
return pot;
|
||||
current = (await tasks.GetAsync(current, ct))?.ParentId?.Trim() ?? "";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user