Zielkette, Stufe 1: jede Aufgabe kann sagen, wofuer sie da ist (#714)

- TaskItem.ParentId, in der Datei als parent, in der DB als ParentId. Die
  Elternaufgabe ist der Zweck ("wofuer"), blocked_by die Voraussetzung
  ("wann").
- GoalChain: Eltern bis zu acht Stufen, Zyklen brechen den Gang ab und
  werden beim Setzen abgelehnt. Oben steht das Ziel der Einheit - der
  obersten Aufgabe, die zu einer Einheit gehoert (ein Ziel, das ein Mensch
  auf der obersten Ebene setzt, gehoert keiner), sonst der naechsten Einheit
  darueber mit Ziel.
- Der Lauf einer Aufgabe bekommt den Absatz "Why this task exists" und die
  Bitte, zu melden, wenn die Aufgabe ihrem Zweck nicht mehr dient.
- Taskboard-Tool: parent bei task_create/task_update, geprueft auf Existenz,
  Sichtbarkeit (#684) und Zyklen; task_list zeigt "Serves".
- WebUI: Feld im Aufgabendialog, Anzeige auf der Karte; die Verwaltung
  prueft wie das Tool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Richard
2026-09-24 18:45:15 +02:00
co-authored by Claude Opus 5.5
parent b75b68c786
commit b22272345e
16 changed files with 482 additions and 18 deletions
@@ -380,6 +380,9 @@ public sealed class SqliteStorage
// #684: Who created a task — decides its board when nobody in particular is assigned.
SpalteErgaenzen(connection, "Tasks", "CreatedBy", "TEXT NOT NULL DEFAULT ''");
// #714: The task a task serves — the goal chain.
SpalteErgaenzen(connection, "Tasks", "ParentId", "TEXT NOT NULL DEFAULT ''");
// Findet offene Aufrufe beim Start, ohne die ganze Tabelle zu lesen.
using var index = connection.CreateCommand();
index.CommandText = """
@@ -30,6 +30,7 @@ public sealed class EngineTaskDispatcher : ITaskDispatcher
private readonly IStateStore _stateStore;
private readonly ILogger _logger;
private readonly TimeProvider _clock;
private readonly ITaskRepository? _tasks;
public EngineTaskDispatcher(
AgentEngine engine,
@@ -38,8 +39,10 @@ public sealed class EngineTaskDispatcher : ITaskDispatcher
ToolRegistry toolRegistry,
IStateStore stateStore,
ILoggerFactory loggerFactory,
TimeProvider? clock = null)
TimeProvider? clock = null,
ITaskRepository? tasks = null)
{
_tasks = tasks;
_engine = engine;
_agents = agents;
_instanceId = instanceId;
@@ -56,7 +59,7 @@ public sealed class EngineTaskDispatcher : ITaskDispatcher
return await DispatchToolJobAsync(task, ct);
var agents = _agents();
var message = BuildMessage(task);
var message = BuildMessage(task, await WhyAsync(task, ct));
var kind = TaskAssignee.KindOf(task.Assignee);
AgentRunResult result;
@@ -158,7 +161,27 @@ public sealed class EngineTaskDispatcher : ITaskDispatcher
return agents.Count == 1 ? agents[0] : null;
}
internal string BuildMessage(TaskItem task)
/// <summary>
/// #714: The goal chain of the task — its parents up to the goal of the unit. A lookup
/// that fails costs the paragraph, never the run.
/// </summary>
private async Task<string?> WhyAsync(TaskItem task, CancellationToken ct)
{
if (_tasks is null)
return null;
try
{
var parents = await GoalChain.ParentsAsync(task, _tasks.GetAsync, ct);
return GoalChain.Describe(task, parents, _engine.OrganisationProvider?.Invoke());
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Goal chain of task {TaskId} could not be read; the run goes ahead without it", task.Id);
return null;
}
}
internal string BuildMessage(TaskItem task, string? why = null)
{
var sb = new StringBuilder();
sb.AppendLine($"[Aufgabe {task.Id}] {task.Title}");
@@ -168,6 +191,12 @@ public sealed class EngineTaskDispatcher : ITaskDispatcher
// und ein Modell ohne diese Zeile raet aus seinem Trainingsstand.
sb.AppendLine(Zeitangabe(task, _clock.GetUtcNow()));
if (!string.IsNullOrWhiteSpace(why))
{
sb.AppendLine();
sb.AppendLine(why.Trim());
}
if (!string.IsNullOrWhiteSpace(task.Body))
{
sb.AppendLine();
+104
View File
@@ -0,0 +1,104 @@
using System.Text;
using ClawdDotNet.Core.Organisation;
namespace ClawdDotNet.Core.Tasks;
/// <summary>
/// #714: Why a task exists — its parent, that one's parent, up to the goal of the unit.
/// Taken from Paperclip (Organisation-Konzept, 9a): an agent that only sees its own order
/// cannot weigh it. "Write a product text" is a different job when it serves "launch the
/// spring collection by Friday" than when it serves "clean up old listings".
///
/// <para><b>Purpose, not precondition.</b> <see cref="TaskItem.BlockedBy"/> says when a task
/// may run; the parent says what it is for. Both can point to the same task, and mean
/// different things.</para>
///
/// <para>Walked at run time, never stored as text: a parent that is renamed or finished
/// shows up as it is now. The walk stops at a cycle and after <see cref="MaxDepth"/> steps,
/// so a broken chain cannot hang a run or flood its prompt.</para>
/// </summary>
public static class GoalChain
{
public const int MaxDepth = 8;
/// <summary>The parents of a task, nearest first. Stops at a missing parent or a cycle.</summary>
public static async Task<IReadOnlyList<TaskItem>> ParentsAsync(
TaskItem task, Func<string, CancellationToken, Task<TaskItem?>> lookup, CancellationToken ct)
{
var parents = new List<TaskItem>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { task.Id };
var next = task.ParentId;
while (!string.IsNullOrWhiteSpace(next) && parents.Count < MaxDepth && seen.Add(next))
{
if (await lookup(next, ct) is not { } parent)
break;
parents.Add(parent);
next = parent.ParentId;
}
return parents;
}
/// <summary>
/// Whether making <paramref name="parentId"/> the parent of <paramref name="taskId"/>
/// would close a circle — the parent is the task itself or lies below it.
/// </summary>
public static async Task<bool> WouldCycleAsync(
string taskId, string parentId, Func<string, CancellationToken, Task<TaskItem?>> lookup, CancellationToken ct)
{
if (string.Equals(taskId, parentId, StringComparison.OrdinalIgnoreCase))
return true;
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var next = parentId;
while (!string.IsNullOrWhiteSpace(next) && seen.Add(next))
{
if (string.Equals(next, taskId, StringComparison.OrdinalIgnoreCase))
return true;
next = (await lookup(next, ct))?.ParentId;
}
return false;
}
/// <summary>
/// The goal above the chain: that of the unit of the topmost task that belongs to one —
/// a goal a human set on the top level belongs to no unit, so the next one down counts —
/// or of the nearest unit above it that has a goal. <c>null</c> without units or without
/// a goal.
/// </summary>
public static (string UnitName, string Goal)? UnitGoal(IReadOnlyList<TaskItem> fromTop, OrgChart? org)
{
if (org is not { HasUnits: true })
return null;
var unitId = fromTop.Select(t => TaskBoard.UnitOf(t, org)).FirstOrDefault(u => u is not null);
if (org.Unit(unitId) is not { } unit)
return null;
foreach (var candidate in new[] { unit }.Concat(org.Ancestors(unit.Id)))
{
if (!string.IsNullOrWhiteSpace(candidate.Goal))
return (candidate.Name, candidate.Goal.Trim());
}
return null;
}
/// <summary>
/// The paragraph that goes into the run: "you do this because … because … because".
/// <c>null</c> when there is nothing above the task — then the run looks as before.
/// </summary>
public static string? Describe(TaskItem task, IReadOnlyList<TaskItem> parents, OrgChart? org)
{
var goal = UnitGoal([.. parents.Reverse(), task], org);
if (parents.Count == 0 && goal is null)
return null;
var sb = new StringBuilder();
sb.AppendLine("Why this task exists — it serves, from nearest to farthest:");
foreach (var parent in parents)
sb.AppendLine($"- {parent.Id} \"{parent.Title}\" ({TaskText.Of(parent.Status)})");
if (goal is { } g)
sb.AppendLine($"- the goal of the unit \"{g.UnitName}\": {g.Goal}");
sb.Append("Weigh your work against this. If the task no longer serves it — the parent is done or canceled, or the task contradicts the goal — say so in your result instead of working blindly.");
return sb.ToString();
}
}
@@ -34,11 +34,11 @@ public sealed class SqliteTaskRepository : ITaskRepository
INSERT INTO Tasks
(Id, Title, Status, Type, Priority, Assignee, WhenKind, WhenValue, WhenTz,
RequireApproval, Acceptance, BlockedBy, OnlyWhenMarketOpen, Body, FileName,
ToolName, JobTypeId, LastOccurrence, ClaimToken, ClaimedAt, CreatedAt, UpdatedAt, CreatedBy)
ToolName, JobTypeId, LastOccurrence, ClaimToken, ClaimedAt, CreatedAt, UpdatedAt, CreatedBy, ParentId)
VALUES
(@id, @title, @status, @type, @priority, @assignee, @whenKind, @whenValue, @whenTz,
@requireApproval, @acceptance, @blockedBy, @market, @body, @fileName,
@toolName, @jobType, NULL, NULL, NULL, @createdAt, @updatedAt, @createdBy);
@toolName, @jobType, NULL, NULL, NULL, @createdAt, @updatedAt, @createdBy, @parentId);
""";
BindDefinition(insert, task);
insert.Parameters.AddWithValue("@status", TaskText.Of(task.Status));
@@ -61,6 +61,7 @@ public sealed class SqliteTaskRepository : ITaskRepository
BlockedBy = @blockedBy, OnlyWhenMarketOpen = @market, Body = @body,
FileName = @fileName, ToolName = @toolName, JobTypeId = @jobType,
CreatedBy = CASE WHEN @createdBy = '' THEN CreatedBy ELSE @createdBy END,
ParentId = @parentId,
UpdatedAt = @updatedAt
WHERE Id = @id
""";
@@ -332,7 +333,7 @@ public sealed class SqliteTaskRepository : ITaskRepository
"Id, Title, Status, Type, Priority, Assignee, WhenKind, WhenValue, WhenTz, " +
"RequireApproval, Acceptance, BlockedBy, OnlyWhenMarketOpen, Body, FileName, " +
"ToolName, JobTypeId, LastOccurrence, ClaimToken, ClaimedAt, CreatedAt, UpdatedAt, "
+ "BudgetMissCount, LastBudgetMissAt, DeferredUntil, CatchUpPending, CreatedBy";
+ "BudgetMissCount, LastBudgetMissAt, DeferredUntil, CatchUpPending, CreatedBy, ParentId";
private static void BindDefinition(SqliteCommand cmd, TaskItem task)
{
@@ -354,6 +355,7 @@ public sealed class SqliteTaskRepository : ITaskRepository
cmd.Parameters.AddWithValue("@jobType", task.JobTypeId);
// #684: a file without it (written by hand, or older) keeps what the database knows.
cmd.Parameters.AddWithValue("@createdBy", task.CreatedBy ?? "");
cmd.Parameters.AddWithValue("@parentId", task.ParentId ?? "");
}
private static async Task<TaskItem?> ReadAsync(SqliteConnection conn, string id, CancellationToken ct)
@@ -405,7 +407,8 @@ public sealed class SqliteTaskRepository : ITaskRepository
LastBudgetMissAt = r.IsDBNull(23) ? null : Parse(r.GetString(23)),
DeferredUntil = r.IsDBNull(24) ? null : Parse(r.GetString(24)),
CatchUpPending = r.GetInt32(25) != 0,
CreatedBy = r.GetString(26)
CreatedBy = r.GetString(26),
ParentId = r.GetString(27)
};
}
@@ -153,6 +153,7 @@ public static class TaskFrontmatter
ToolName = scalars.GetValueOrDefault("tool_name", ""),
JobTypeId = scalars.GetValueOrDefault("job_type", ""),
CreatedBy = scalars.GetValueOrDefault("created_by", ""),
ParentId = scalars.GetValueOrDefault("parent", ""),
Body = body
};
return true;
@@ -172,6 +173,8 @@ public static class TaskFrontmatter
sb.Append($"assignee: {Scalar(task.Assignee)}\n");
if (!string.IsNullOrWhiteSpace(task.CreatedBy))
sb.Append($"created_by: {Scalar(task.CreatedBy)}\n");
if (!string.IsNullOrWhiteSpace(task.ParentId))
sb.Append($"parent: {Scalar(task.ParentId)}\n");
if (task.When is { } w)
{
+7
View File
@@ -235,6 +235,13 @@ public sealed record TaskItem
/// </summary>
public string CreatedBy { get; init; } = "";
/// <summary>
/// #714: The task this one serves — its purpose ("what for"), where <see cref="BlockedBy"/>
/// is its precondition ("when"). Empty for a task at the top; above the top stands the
/// goal of the unit. See <see cref="GoalChain"/>.
/// </summary>
public string ParentId { get; init; } = "";
/// <summary>A one-time task that was refused for lack of budget and carried over.</summary>
public bool IsCarriedOver => !IsRecurring && BudgetMissCount > 0;