Files
archie/internal/infrastructure/kit/kit.go
T
sam abb9f8a04e 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

196 lines
6.3 KiB
Go

// Package kit decides whether archie can run a harness packaged as Kit v3
// images, and what it runs with. Descriptor grammar, validation and
// composition belong to the Kit spec package; this package owns only the
// runtime's half of the contract: which capability types archie implements,
// and the refusals that keep the host's guarantees intact.
package kit
import (
"errors"
"fmt"
"strings"
"github.com/docker/sandbox-kit-spec/v3/spec"
)
const (
typeCredential = "com.docker.sandbox/credential@1"
typeAgentSessions = "com.docker.sandbox/agent-sessions@1"
// contextPath is where the composed agent-context body is staged.
contextPath = "/usr/share/archie/agent-context.md"
)
// supported is every capability type archie provides. Anything else is
// refused when required and skipped when optional: approximating a type
// archie does not implement would grant a Kit something nobody reviewed.
var supported = map[string]bool{
typeCredential: true,
"com.docker.sandbox/network-policy@1": true,
"com.docker.sandbox/volume@1": true,
"com.docker.sandbox/lifecycle@1": true,
typeAgentSessions: true,
"com.docker.sandbox/agent-skills@1": true,
"com.docker.sandbox/agent-context@1": true,
"com.docker.sandbox/resources@1": true,
}
// forgeServices are credential services a harness never receives: the model
// never runs git, so it never holds a credential that could push.
var forgeServices = map[string]bool{
"github": true,
"gitlab": true,
"gitea": true,
"forgejo": true,
"bitbucket": true,
}
// Skip is an optional capability archie does not provide, recorded so the
// step that ran without it can say so.
type Skip struct {
Type string
Reason string
}
// Refusal is a required capability archie will not provide.
type Refusal struct {
Type string
Reason string
}
// RefusedError carries every refusal, so an operator fixes a Kit in one pass.
type RefusedError struct {
Refusals []Refusal
}
func (e *RefusedError) Error() string {
parts := make([]string, len(e.Refusals))
for i, r := range e.Refusals {
parts[i] = r.Type + ": " + r.Reason
}
return "kit refused: " + strings.Join(parts, "; ")
}
// Plan is what archie launches: the composed descriptor, the capabilities
// it provides, and what it skipped.
type Plan struct {
Descriptor *spec.Descriptor
Capabilities []spec.Capability
Skipped []Skip
Sessions *spec.AgentSessions
ContextSources []spec.ContextSource
}
// DecodePublished reads the descriptor from an image's manifest annotations
// and holds it to the published form: strict decoding, full validation, and
// no unexpanded build-phase args.
func DecodePublished(annotations map[string]string) (*spec.Descriptor, error) {
raw, ok := annotations[spec.AnnotationDescriptor]
if !ok {
return nil, fmt.Errorf("image is not a kit: no %s annotation", spec.AnnotationDescriptor)
}
d, err := spec.Decode([]byte(raw))
if err != nil {
return nil, err
}
if _, err := spec.ValidatePublished([]byte(raw), d); err != nil {
return nil, err
}
return d, nil
}
// Admit applies archie's capability support to one descriptor. Every
// required capability archie will not provide is collected into a
// RefusedError; optional ones are skipped.
func Admit(d *spec.Descriptor) (*Plan, error) {
plan := &Plan{Descriptor: d}
var refusals []Refusal
for _, c := range d.Capabilities {
reason, err := refusalReason(c)
if err != nil {
return nil, err
}
switch {
case reason == "":
plan.Capabilities = append(plan.Capabilities, c)
case c.Optional:
plan.Skipped = append(plan.Skipped, Skip{Type: c.Type, Reason: reason})
default:
refusals = append(refusals, Refusal{Type: c.Type, Reason: reason})
}
}
if len(refusals) > 0 {
return nil, &RefusedError{Refusals: refusals}
}
return plan, nil
}
// Compose merges one workload Kit and its mixins, in the order given, and
// admits the result. archie drives a harness headlessly, so the composition
// must carry an agent-sessions prompt verb.
func Compose(contributions []spec.Contribution) (*Plan, error) {
merged, err := spec.Merge(contributions, MergeOptions)
if err != nil {
return nil, err
}
return FromMerge(merged)
}
// MergeOptions are the options every composition archie runs is merged with.
var MergeOptions = spec.MergeOptions{ContextPath: contextPath}
// FromMerge admits an already-merged composition, such as one the Kit spec's
// fetch package assembled from a registry.
func FromMerge(merged *spec.MergeResult) (*Plan, error) {
if merged.Descriptor.Kind != spec.KindWorkload {
return nil, errors.New("kit composition has no workload: a harness needs exactly one base kit")
}
plan, err := Admit(merged.Descriptor)
if err != nil {
return nil, err
}
sessions, err := spec.AgentSessionsOf(plan.Capabilities)
if err != nil {
return nil, err
}
if sessions == nil || len(sessions.Prompt) == 0 {
return nil, fmt.Errorf("kit composition declares no %s prompt verb: archie cannot run it headlessly", typeAgentSessions)
}
plan.Sessions = sessions
plan.ContextSources = merged.ContextSources
return plan, nil
}
// ValidateNeeds rejects a Plan that cannot meet what the workflow's stages
// declared they need (docs/prds/external-agent-harness.md, "Contract"): a
// gate that may retry needs the Kit's agent-sessions resume verb, because
// archie resumes the session with the gate's output rather than starting
// over. gateRetries is zero for a workflow with no gated stage, which no
// Kit composition can fail to meet.
func ValidateNeeds(plan *Plan, gateRetries int) error {
if gateRetries > 0 && (plan.Sessions == nil || len(plan.Sessions.Resume) == 0) {
return fmt.Errorf("needs.gate_retries is %d, but the kit declares no %s resume verb to retry with", gateRetries, typeAgentSessions)
}
return nil
}
func refusalReason(c spec.Capability) (string, error) {
if !supported[c.Type] {
return "not provided by archie", nil
}
if c.Type != typeCredential {
return "", nil
}
var cred spec.Credential
if err := spec.DecodeCapabilityConfig(c, &cred); err != nil {
return "", err
}
if forgeServices[cred.Service] {
return fmt.Sprintf("service %q is a forge credential; harnesses never hold one", cred.Service), nil
}
if cred.OAuth != nil && cred.OAuth.Passthrough {
return fmt.Sprintf("service %q asks for OAuth passthrough; real tokens never enter the container", cred.Service), nil
}
return "", nil
}