Stages: optional skills block loading pinned library skills per visit

A model stage may declare a skills block (name or name@N per line).
Drafts and publications are validated against the server skill library;
human/ntfy stages reject the block. Each run resolves unpinned names to the
latest version at admission and records name@N per stage (run
stage_skills, step skills); retry reuses the recorded versions. Every visit
gets a private read-only copy of exactly those bundles under the run's
artifact tree, and the harness loads only them: Claude via a session
plugin (--plugin-dir, Skill tool with per-skill allow rules, bundled skills
off, ambient loads fail the visit), Pi via --skill under --no-skills, and
OpenCode via per-session instruction entries (V2 only). The app shows the
block in the stage definition and the resolved versions on each visit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 19:17:16 +00:00
parent 509d4c624f
commit 85a7284fba
34 changed files with 1418 additions and 35 deletions
+24 -3
View File
@@ -228,6 +228,19 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
if err != nil {
return nil, err
}
// Pin every skills block to library versions now. A retry reuses the
// versions its source run recorded for unpinned names, so a newer import
// never changes what a replayed stage loads.
var priorSkills map[string][]string
if request.RetrySource > 0 {
if priorSkills, err = r.store.RunStageSkills(r.ctx, request.RetrySource); err != nil {
return nil, err
}
}
stageSkills, err := r.store.ResolveStageSkills(r.ctx, d.Graph, priorSkills)
if err != nil {
return nil, err
}
for _, s := range d.Graph.Stages {
if stage.EffectiveType(s.Type) != stage.ModelType {
continue
@@ -345,7 +358,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
workspace = tree
request.Input["pwd"] = workspace
}
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat}, runTitle, retryOf...)
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat, StageSkills: stageSkills}, runTitle, retryOf...)
if isolated != "" && (err != nil || !created) {
// The run was refused or an identical request won the race: the fresh
// tree holds nothing yet.
@@ -1857,6 +1870,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
def.ArtifactsDir = artifactsDir
def.Turn = stageTurnPaths(visitTurn)
publicBefore = publicFileSet(visitTurn.RunDir)
skillSet, skillErr := r.visitSkills(ctx, id, key, visitTurn, adopted != nil)
if skillErr != nil {
finish("failed", "error", "skills: "+skillErr.Error())
return
}
def.Skills = skillSet
}
operations := &stage.OperationLog{}
var landing stage.LandingAccess
@@ -1874,6 +1893,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
landing = access
}
client := r.agentClient(id, sequence, state.artifactDirs, workspace, artifactsDir, operations, request.WritePaths, tools)
client.Skills = def.Skills
client.LandingAccess = landing
client.OnSession = func(session string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -1943,6 +1963,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
return
}
piClient = r.piClient(id, sequence, state.artifactDirs, profile.Executable, workspace, artifactsDir, request.WritePaths, tools)
piClient.Skills = def.Skills
piClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -1952,7 +1973,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
stageSession = piClient.SessionID
client.Transcript = piClient.Transcript
} else if modelConfig.Harness == stage.ClaudeBackend {
claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir}
claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills}
claudeClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -1965,7 +1986,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
result, err = (stage.ModelStage{Client: client}).Run(stageCtx, def, input)
stageSession = client.SessionID
} else if stage.EffectiveType(def.Type) == stage.ModelType {
plain := &stage.OpenCodeClient{Directory: workspace, Operations: operations, ArtifactsDir: artifactsDir}
plain := &stage.OpenCodeClient{Directory: workspace, Operations: operations, ArtifactsDir: artifactsDir, Skills: def.Skills}
if adopted != nil {
plain.Backend, plain.Reference = adopted.owner.Backend, adopted.owner.Reference
}
+28
View File
@@ -0,0 +1,28 @@
package server
import (
"context"
"path/filepath"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/turn"
)
// visitSkillsRoot is a model visit's private skills directory. It sits beside
// the visit's turn directory, not inside it, so the copied bundles are never
// inventoried as stage artifacts, and under the run's artifact root, so run
// deletion and retention remove it with the run.
func visitSkillsRoot(paths turn.Paths) string {
return filepath.Join(paths.RunDir, "skills", filepath.Base(paths.TurnDir))
}
// visitSkills materialises the skills the run recorded for this stage at
// admission (nil when it has none). A re-adopted visit keeps the copy its
// still-running session was started with.
func (r *runner) visitSkills(ctx context.Context, runID int64, key string, paths turn.Paths, adopted bool) (*stage.SkillSet, error) {
recorded, err := r.store.RunStageSkills(context.WithoutCancel(ctx), runID)
if err != nil {
return nil, err
}
return r.store.MaterializeSkills(context.WithoutCancel(ctx), recorded[key], visitSkillsRoot(paths), adopted)
}
+122
View File
@@ -0,0 +1,122 @@
package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func importServerTestSkill(t *testing.T, store *pipeline.Store, name, body string) {
t.Helper()
files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte("---\nname: " + name + "\ndescription: Test.\n---\n" + body + "\n")}}
h := sha256.New()
for _, f := range files {
fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes))
h.Write(f.Bytes)
}
if _, err := store.ImportSkill(context.Background(), name, "Test.", hex.EncodeToString(h.Sum(nil)), "/src", files); err != nil {
t.Fatal(err)
}
}
func TestRunPinsSkillsMaterialisesThemAndRetriesReuseVersions(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dir := t.TempDir()
store, err := pipeline.Open(filepath.Join(dir, "skills.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
importServerTestSkill(t, store, "review", "version one")
model := "```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
source := "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n" + model +
"\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\n```\n\n```skills\nreview\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n" + model
if _, err := store.Submit(ctx, "skilled", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
artifacts := filepath.Join(dir, "artifacts")
r, err := newRunnerAt(ctx, store, artifacts)
if err != nil {
t.Fatal(err)
}
defer func() { cancel(); r.wg.Wait() }()
workspace := t.TempDir()
fail := true
var seen []string
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "a" {
if def.Skills != nil {
t.Error("a stage without a skills block got skills", def.Skills)
}
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-a"}}, nil
}
if def.Skills.Empty() || len(def.Skills.Bundles) != 1 {
t.Fatalf("b got no skills: %+v", def.Skills)
}
bundle := def.Skills.Bundles[0]
data, err := os.ReadFile(filepath.Join(bundle.Dir, "SKILL.md"))
if err != nil {
t.Fatal(err)
}
// Private to this visit, under the run's artifact tree, outside the
// workspace and outside the inventoried turn directory.
if !strings.HasPrefix(def.Skills.Root, artifacts+string(os.PathSeparator)) || strings.HasPrefix(def.Skills.Root, def.Turn.Dir) || strings.HasPrefix(def.Skills.Root, workspace) || filepath.Base(def.Skills.Root) != filepath.Base(def.Turn.Dir) {
t.Errorf("skills root %s (turn %s)", def.Skills.Root, def.Turn.Dir)
}
seen = append(seen, fmt.Sprintf("%s@%d:%s", bundle.Name, bundle.Version, strings.TrimSpace(string(data[strings.LastIndex(string(data), "---")+3:]))))
if fail {
return stage.Result{}, fmt.Errorf("deliberate failure")
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
original, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "original", Workspace: workspace, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
original, err = store.GetRun(ctx, original.ID)
if err != nil || original.Status != "failed" || !slices.Equal(original.StageSkills["b"], []string{"review@1"}) {
t.Fatalf("%+v %v", original, err)
}
if len(original.Steps) != 2 || original.Steps[0].Skills != nil || !slices.Equal(original.Steps[1].Skills, []string{"review@1"}) {
t.Fatalf("step skills %+v", original.Steps)
}
// A newer import after the run started must not reach its retries.
importServerTestSkill(t, store, "review", "version two")
fail = false
for _, mode := range []string{"resume", "restart"} {
retried, err := r.retry(protocol.Message{RunID: original.ID, RequestKey: "retry-" + mode, RetryMode: mode})
if err != nil {
t.Fatal(mode, err)
}
r.wg.Wait()
retried, err = store.GetRun(ctx, retried.ID)
if err != nil || retried.Status != "succeeded" || !slices.Equal(retried.StageSkills["b"], []string{"review@1"}) {
t.Fatalf("%s: %+v %v", mode, retried, err)
}
}
fresh, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "fresh", Workspace: workspace, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if fresh, err = store.GetRun(ctx, fresh.ID); err != nil || !slices.Equal(fresh.StageSkills["b"], []string{"review@2"}) {
t.Fatalf("fresh run: %+v %v", fresh, err)
}
want := []string{"review@1:version one", "review@1:version one", "review@1:version one", "review@2:version two"}
if !slices.Equal(seen, want) {
t.Fatalf("visits loaded %q, want %q", seen, want)
}
}
+3
View File
@@ -384,6 +384,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
} else if request.Type == protocol.Validate {
graph, warnings, err := pipeline.ParseDefinitionReport(request.Source)
if err == nil && len(stores) > 0 {
err = stores[0].ValidateSkills(ctx, graph)
}
response.Type = protocol.Validated
response.Warnings = warnings
if err != nil {