Files
archie/internal/daemon/kit_task.go
T
sam a6ab4ef538 feat(harness): declare and enforce a workflow's harness needs at dispatch
docs/prds/external-agent-harness.md ("Contract"): workflow definition
validation must reject a stage whose needs the selected harness cannot
meet -- capture tools without an adapter, or a gate retry without a
resume verb. The step vocabulary had no static way to declare either.

Added task.WorkflowInterface.Needs{Captures, GateRetries}, parsed and
validated (GateRetries >= 0) the same way Inputs/Repository already are.
Only a Kit profile is checked against it: an image profile's built-in
agent loop always supports both, so Needs constrains only the harness path.

Two enforcement points, chosen for where each fact is actually known
without a network fetch at save time:
- Captures vs adapter is knowable from config alone (profile.Adapter, the
  agentexec.harnessAdapters table), so daemon.pinTaskProfile checks it
  right where it already resolves the profile (validateProfileMeetsNeeds),
  parking the task the same way an unconfigured profile already does.
- GateRetries vs the Kit's actual agent-sessions resume verb is only known
  once the Kit composition is fetched, which kitrun.Launcher.Launch
  already does -- so kit.ValidateNeeds runs there (new kitrun.Request.
  GateRetries field, threaded from the workflow's parsed Needs in
  daemon.runKitTask) rather than inventing an image-fetching workflow-save
  validator.

Deliberately NOT built: "a Kit profile named by no workflow is a
validation error" (external-agent-harness.md "Selection"). Read literally
("a Kit profile [that is] named by no workflow"), this is a
cross-resource check -- an agent-profiles entry unreferenced by anything
in workflow-definitions -- and no control-plane Definition validator can
see another resource today (Definition.Validate is a pure []byte->error
function by design, matching every existing resource kind). Building
that crossing is a real, separate piece of infrastructure with its own
ordering questions (does defining a Kit profile before its workflow now
fail?), not a two-line addition, so it is left for a follow-on rather
than bolted on here.

Also fixes a test bug caught by rerunning with a short -timeout per
instruction: TestRunKitTaskThreadsGateRetriesToTheLauncher's fake NATS
subscriber never responded, so runKitTask's call into runViaAgent blocked
forever waiting for a reply bounded by a zero (unconfigured) wall-clock
budget. Fixed by responding, matching the sibling test's pattern.
2026-09-27 05:25:39 +10:00

106 lines
3.8 KiB
Go

package daemon
import (
"context"
"fmt"
"os"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// KitLauncher starts and ends the container of a task whose agent profile
// is a Kit.
type KitLauncher interface {
Launch(ctx context.Context, req kitrun.Request) (*kitrun.Run, error)
Release(ctx context.Context, run *kitrun.Run) error
RemoveVolumes(ctx context.Context, volumes []kit.Volume) error
}
// runKitTask runs a task in its Kit's container, every agent stage on the
// Kit's harness. The worker reaches NATS and the State Store only through
// the egress relay, and its environment carries no model provider key.
func (d *Daemon) runKitTask(ctx context.Context, task *workflow.Task, repo config.Repo, workDir string, profile config.AgentProfile) {
park := func(reason string, err error) {
d.Log.Error(reason, "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error(), taskstate.ParkTransient)
}
if d.KitLauncher == nil {
park("kit profile", fmt.Errorf("kit harness runs are unavailable on this daemon"))
return
}
if err := writeTaskBrief(workDir, task); err != nil {
park("task.json write failed", err)
return
}
stateStoreToken, revokeStateStoreGrant, err := d.stateStoreGrantToken(task)
if err != nil {
park("state store grant failed", err)
return
}
defer revokeStateStoreGrant()
env, err := kitrun.WorkerEnv(kitrun.Endpoints{
NATS: d.ConnectedNATS.URL, NATSToken: d.ConnectedNATS.Token,
StateStore: d.ConnectedStateStore.URL, StateStoreToken: stateStoreToken,
}, os.Getuid(), os.Getgid())
if err != nil {
park("kit worker environment", err)
return
}
// The interface is reparsed rather than threaded through pinTaskProfile's
// return: task.WorkflowDefinitionYAML is already pinned by the time this
// runs, parsing it is pure and cheap, and pinTaskProfile's signature stays
// unchanged for its other callers.
iface, err := workflowtask.ParseWorkflowInterface(task.WorkflowDefinitionYAML)
if err != nil {
park("kit workflow interface", err)
return
}
run, err := d.KitLauncher.Launch(ctx, kitrun.Request{
Execution: fmt.Sprintf("task-%d", task.ID),
Kit: profile.Kit,
Adapter: profile.Adapter,
WorkDir: workDir,
WorkerEnv: env,
GateRetries: iface.Needs.GateRetries,
})
if err != nil {
park("kit launch failed", err)
return
}
limitCtx, stopLimit := withTaskTimeLimit(ctx, d.configFor(task).Budgets.TaskWallClock.Std())
runCtx, stopWatch := withContainerExit(limitCtx, run.Container.Exited())
d.runViaAgent(runCtx, task, repo, profile, &run.Harness)
stopWatch()
stopLimit()
if err := d.KitLauncher.Release(ctx, run); err != nil {
d.Log.Warn("kit release failed", "task", task.ID, "err", err)
}
d.removeEndedKitVolumes(ctx, task.ID, run.Volumes)
}
// removeEndedKitVolumes removes the execution's Kit volumes unless the task
// parked: a retry of a parked task is the same execution and resumes from
// them.
func (d *Daemon) removeEndedKitVolumes(ctx context.Context, taskID int64, volumes []kit.Volume) {
if len(volumes) == 0 || d.Store == nil {
return
}
lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
latest, err := d.Store.TaskByID(lookupCtx, taskID)
if err != nil || latest == nil || latest.Status == workflow.StatusParked {
return
}
if err := d.KitLauncher.RemoveVolumes(lookupCtx, volumes); err != nil {
d.Log.Warn("kit volume removal failed", "task", taskID, "err", err)
}
}