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
@@ -116,6 +116,12 @@ List<StageDefinitionField> stageDefinitionFields(dynamic stage) {
if (tools != null && text.trim().isNotEmpty) { if (tools != null && text.trim().isNotEmpty) {
fields.add(StageDefinitionField('Tools', text, block: true)); fields.add(StageDefinitionField('Tools', text, block: true));
} }
// One library skill per line: `name` (latest at run start) or `name@N`.
final skills = blocks['skills'];
final skillText = _text(skills);
if (skills != null && skillText.trim().isNotEmpty) {
fields.add(StageDefinitionField('Skills', skillText.trim(), block: true));
}
} }
final limits = stage['limits']; final limits = stage['limits'];
@@ -81,6 +81,8 @@ List<VisitFact> detailVisitFacts(JsonMap step) {
if (duration != null) facts.add((label: 'Duration', value: duration)); if (duration != null) facts.add((label: 'Duration', value: duration));
final model = detailVisitProviderModel(step); final model = detailVisitProviderModel(step);
if (model != null) facts.add((label: 'Provider/model', value: model)); if (model != null) facts.add((label: 'Provider/model', value: model));
final skills = detailVisitSkills(step);
if (skills != null) facts.add((label: 'Skills', value: skills));
final usage = stageTokenUsage(step); final usage = stageTokenUsage(step);
if (usage != null) { if (usage != null) {
facts.add((label: 'Tokens', value: tokenUsageDetail(usage))); facts.add((label: 'Tokens', value: tokenUsageDetail(usage)));
@@ -111,6 +113,15 @@ String? detailVisitProviderModel(JsonMap step) {
return provider ?? model; return provider ?? model;
} }
/// The skill library versions (`name@N`) this visit loaded, resolved when
/// the run started; null when the stage configured none.
String? detailVisitSkills(JsonMap step) {
final skills = step['skills'];
if (skills is! List) return null;
final names = <String>[for (final skill in skills) ?_text(skill)];
return names.isEmpty ? null : names.join(', ');
}
/// A recorded verdict, or null when the server recorded no option and no /// A recorded verdict, or null when the server recorded no option and no
/// reason. An empty recorded verdict is not rendered as a decision. /// reason. An empty recorded verdict is not rendered as a decision.
({String? option, String? reason})? detailVisitVerdict(JsonMap step) { ({String? option, String? reason})? detailVisitVerdict(JsonMap step) {
@@ -25,7 +25,10 @@ JsonMap _stage() => <String, dynamic>{
'skipped_blank': ' ', 'skipped_blank': ' ',
'skipped_null': null, 'skipped_null': null,
}, },
'blocks': <String, dynamic>{'tools': 'shell\nread_file'}, 'blocks': <String, dynamic>{
'tools': 'shell\nread_file',
'skills': 'review-checklist\nrelease-notes@3\n',
},
'limits': <String, dynamic>{ 'limits': <String, dynamic>{
'max_visits': 3, 'max_visits': 3,
'on': <String>['success', 'error'], 'on': <String>['success', 'error'],
@@ -56,6 +59,7 @@ void main() {
'Retries', 'Retries',
'Timeout', 'Timeout',
'Tools', 'Tools',
'Skills',
'Max visits', 'Max visits',
'Limit on', 'Limit on',
'Memory', 'Memory',
@@ -75,12 +79,14 @@ void main() {
expect(fields[4].value, '12.5'); expect(fields[4].value, '12.5');
expect(fields[5].value, 'codex'); expect(fields[5].value, 'codex');
expect(fields[10].value, 'shell\nread_file'); expect(fields[10].value, 'shell\nread_file');
expect(fields[11].value, '3'); expect(fields[11].value, 'review-checklist\nrelease-notes@3');
expect(fields[12].value, 'success, error'); expect(fields[11].block, isTrue);
expect(fields[13].value, 'context: latest\nnotes: keep'); expect(fields[12].value, '3');
expect(fields[14].value, 'failure'); expect(fields[13].value, 'success, error');
expect(fields[15].value, 'ops@example.test'); expect(fields[14].value, 'context: latest\nnotes: keep');
expect(fields[16].value, 'run.log'); expect(fields[15].value, 'failure');
expect(fields[16].value, 'ops@example.test');
expect(fields[17].value, 'run.log');
}); });
test('a blank or absent type reads model; an authored type is kept', () { test('a blank or absent type reads model; an authored type is kept', () {
@@ -0,0 +1,32 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_facts.dart';
void main() {
test('a visit lists the skill versions it loaded after the model', () {
final facts = detailVisitFacts(<String, dynamic>{
'status': 'completed',
'provider': 'anthropic',
'model': 'claude-haiku',
'skills': <String>['review@2', 'notes@1'],
});
final labels = [for (final fact in facts) fact.label];
expect(labels.indexOf('Skills'), labels.indexOf('Provider/model') + 1);
expect(facts, contains((label: 'Skills', value: 'review@2, notes@1')));
});
test('a visit without recorded skills has no skills row', () {
for (final skills in <dynamic>[
null,
<String>[],
<String>[' '],
'x',
]) {
final facts = detailVisitFacts(<String, dynamic>{
'status': 'completed',
'skills': skills,
});
expect(facts.any((fact) => fact.label == 'Skills'), isFalse);
}
});
}
+28 -2
View File
@@ -161,6 +161,17 @@ default model with `opencode api get /api/model/default`.
turn runs is stored in the server's durable queue (up to 8 per chat) and sent turn runs is stored in the server's durable queue (up to 8 per chat) and sent
in order when the turn ends, also after a server restart. in order when the turn ends, also after a server restart.
**Skills in stages:** the stage service is shared and discovers skills per
location, not per session, so a stage cannot be given private skills through
OpenCode's skill discovery; its own `skill` tool stays denied by the stage's
deny-all permission rules, which keeps ambient skills unusable. A stage's
`skills` block is attached to each new session before its prompt as one
`PUT /api/experimental/session/<id>/instructions/entries/pipelines-skill-<name>`
entry carrying the skill's `SKILL.md` and the read-only directory of its
bundled files (readable when the stage declares `read`/`glob`/`grep`). This needs
the V2 service; a V1 backend fails the visit instead of dropping the skills, and
a `SKILL.md` too large for one 64 KiB request fails it too.
## Pi ## Pi
**Used for:** pipeline stages with `harness=pi`, and `new`/`edit`/`debug` **Used for:** pipeline stages with `harness=pi`, and `new`/`edit`/`debug`
@@ -171,8 +182,11 @@ refused unless that profile exists on the server.
**Launched as:** `pi --mode rpc --provider P --model M --session-dir <run dir> **Launched as:** `pi --mode rpc --provider P --model M --session-dir <run dir>
--no-approve --no-extensions --no-skills --no-context-files --no-approve --no-extensions --no-skills --no-context-files
--no-prompt-templates --no-themes --extension policy.js`. The policy extension --no-prompt-templates --no-themes --extension policy.js`, plus one `--skill
enforces the stage's tool and edit permissions. `reasoning_effort` maps to Pi's <dir>` per skill in the stage's `skills` block (Pi documents that explicit
`--skill` paths still load under `--no-skills`; a skills stage must declare
`read`, which the policy also allows inside the visit's skills directory). The
policy extension enforces the stage's tool and edit permissions. `reasoning_effort` maps to Pi's
thinking level and is verified before the task is sent. thinking level and is verified before the task is sent.
**Install and sign in:** **Install and sign in:**
@@ -243,6 +257,18 @@ directory that chooses its own account keeps it).
- **Isolation.** User, project and local Claude Code settings, hooks, MCP - **Isolation.** User, project and local Claude Code settings, hooks, MCP
servers, plugins and slash commands are not loaded. A `CLAUDE.md` in the run servers, plugins and slash commands are not loaded. A `CLAUDE.md` in the run
directory is still read by the CLI. directory is still read by the CLI.
- **Skills.** With a `skills` block the visit's private copy is loaded as a
session-only plugin (`--plugin-dir`, skills named `pipelines-stage:<name>`),
`Skill` is added to `--tools` with one `Skill(pipelines-stage:<name>)` allow
rule per skill, and `--disable-slash-commands` (which also disables plugin
skills) is replaced by `--settings
'{"disableBundledSkills":true,"enabledPlugins":{"cc-plugin-plugin-authoring@builtin":false}}'`.
Claude Code 2.1.332 then lists only the configured skills plus the
user-only `design` and `doctor` commands, which the model cannot invoke (a
live haiku session saw only `pipelines-stage:<name>`; `dataviz` and
`plugin-authoring` were "Unknown skill"). If a Skill call nevertheless loads
any other skill, the visit fails; a refused call is harmless. Without a
`skills` block the arguments are unchanged.
- **Usage.** Cost and tokens come from the CLI's final result and count toward - **Usage.** Cost and tokens come from the CLI's final result and count toward
stage and run budgets; a result without usage fails a budgeted stage. stage and run budgets; a result without usage fails a budgeted stage.
- **Failures.** Diagnostics are fixed text. A billing, quota or rate-limit - **Failures.** Diagnostics are fixed text. A billing, quota or rate-limit
+12 -2
View File
@@ -7,8 +7,18 @@ frontmatter (`name` and `description`) and may contain only `references/`,
executables outside `scripts/`, and oversized bundles are rejected. Files are executables outside `scripts/`, and oversized bundles are rejected. Files are
fingerprinted in sorted path order with SHA-256; importing the same digest is fingerprinted in sorted path order with SHA-256; importing the same digest is
idempotent. The server keeps immutable versions in SQLite metadata and stores idempotent. The server keeps immutable versions in SQLite metadata and stores
their files below its data directory. Skills are metadata-only at this stage: their files below its data directory. Chats do not load library skills.
they are not executed or injected into stages or chats.
A model stage turns skills on with a `skills` block, one `name` (latest at run
start) or `name@N` (pinned) per line; drafts and publications are validated
against this library. A run records the resolved `name@N` per stage when it
starts (`stage_skills` on the run, `skills` on each step) and `retry` reuses
those versions, so importing a newer version never changes a run or its
retries. Each visit copies exactly the resolved bundles, read-only, into
`<artifacts>/<run>/skills/<NN>-<stage>/skills/<name>/` (outside the workspace
and the inventoried turn directory) and gives the harness only those skills:
see the Skills section of `internal/author/skill/references/format.md` and the
per-harness notes in [harnesses.md](harnesses.md).
Use `pipelines skills list` and `pipelines skills show NAME [--version N]` to Use `pipelines skills list` and `pipelines skills show NAME [--version N]` to
inspect imported versions. inspect imported versions.
+27 -2
View File
@@ -1,8 +1,8 @@
# Definition format # Definition format
A definition is Markdown made only of `# stage KEY` headings and fenced blocks; A definition is Markdown made only of `# stage KEY` headings and fenced blocks;
no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `edges`, `checks`, no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`,
`limits` (`references/control.md`), `permissions` and `notify` `checks`, `limits` (`references/control.md`), `permissions` and `notify`
(`references/notifications.md`). There are no memory, links, input or output (`references/notifications.md`). There are no memory, links, input or output
blocks; stages communicate through `output.md` (`# handoff`) and `public/`. blocks; stages communicate through `output.md` (`# handoff`) and `public/`.
Schedules are saved run configurations, never definition blocks Schedules are saved run configurations, never definition blocks
@@ -143,6 +143,31 @@ internally to `mcp__<server>__<tool>`; claude.ai connectors may look like
MCP tools; server configuration is not inspected during validation, so an MCP tools; server configuration is not inspected during validation, so an
unknown name may fail at runtime. unknown name may fail at runtime.
## Skills
Optional `skills` (model stages only) turns on skills from the server skill
library (`pipelines skills list`), one per line: `name` loads the latest version
at run start, `name@N` pins version N. An empty or missing block loads none.
Drafts and publications are rejected for an unknown skill, a missing version,
`@0`/non-numeric versions, a skill listed twice (pinned or not) and a `skills`
block on a human or ntfy stage.
```skills
review-checklist
release-notes@3
```
When a run starts every entry is resolved to `name@N` and recorded on the run
(shown on each step), so a later import never changes a running stage; `retry`
(resume and restart) reuses the recorded versions for unpinned names. Each visit
gets a private read-only copy of exactly those bundles under the run's artifact
directory and only those skills: every other (user, project, bundled) skill
stays off. Harness notes: Claude loads them as a session plugin (`Skill` tool,
listed as `pipelines-stage:<name>`; a call that loads any other skill fails the visit);
Pi loads them with `--skill` and needs `read` in `tools` to open `SKILL.md`;
OpenCode attaches each `SKILL.md` as a session instruction entry (V2 service
only; bundled `references/` are readable with `read`).
## Checks ## Checks
Every model stage that can modify the workspace (`edit` or `shell`, no `tools` Every model stage that can modify the workspace (`edit` or `shell`, no `tools`
@@ -45,6 +45,20 @@ attempts and visits; missing required accounting fails closed. Session/RPC audit
lives in the execution user's cache under `pipelines/pi-sessions`; unconfirmed lives in the execution user's cache under `pipelines/pi-sessions`; unconfirmed
cleanup blocks continuation and retry. cleanup blocks continuation and retry.
A `skills` block (`references/format.md`, Skills) is supported by all three
stage harnesses. Claude stages drop `--disable-slash-commands` only when skills
are configured and instead pass `--plugin-dir <visit skills dir>`, a
`--settings` layer with `disableBundledSkills` and the builtin
plugin-authoring plugin off, `Skill` in `--tools` and one
`Skill(pipelines-stage:<name>)` allow rule per skill; user/project skills stay
unloaded by `--setting-sources ""`. Pi keeps `--no-skills` (it disables every
discovered and configured skill) and adds `--skill <dir>` per skill. OpenCode
stages share one service whose skill discovery is not per session, and its own
skill tool stays denied by the stage's deny-all permissions; the configured
skills are attached as per-session instruction entries instead, which needs the
OpenCode V2 service (a V1 backend fails the visit) and a SKILL.md small enough
for one 64 KiB request.
Claude stages may additionally allow named MCP servers/tools in the `tools` Claude stages may additionally allow named MCP servers/tools in the `tools`
block. These are Claude-only, exact allowlist entries; other MCP tools remain block. These are Claude-only, exact allowlist entries; other MCP tools remain
denied in unattended `dontAsk` sessions. Use `mcp:<server>` or denied in unattended `dontAsk` sessions. Use `mcp:<server>` or
+1
View File
@@ -644,6 +644,7 @@ func deleteRunRows(ctx context.Context, tx *sql.Tx, ids []int64) error {
{"run_session_owners", "run_id"}, {"run_session_owners", "run_id"},
{"attention_dismissals", "run_id"}, {"attention_dismissals", "run_id"},
{"run_schedule_origin", "run_id"}, {"run_schedule_origin", "run_id"},
{"run_stage_skills", "run_id"},
{"run_steps", "run_id"}, {"run_steps", "run_id"},
} { } {
if err := deleteRetentionBatch(ctx, tx, table.name, table.column, ids); err != nil && !missingTable(err) { if err := deleteRetentionBatch(ctx, tx, table.name, table.column, ids); err != nil && !missingTable(err) {
+1
View File
@@ -86,6 +86,7 @@ var runDBBytesQuery = func() string {
{"run_notifications", "run_id=?1", []string{"event", "channel", "title", "body", "click", "diagnostic", "message_id"}}, {"run_notifications", "run_id=?1", []string{"event", "channel", "title", "body", "click", "diagnostic", "message_id"}},
{"retry_checkpoints", "run_id=?1", []string{"mode", "handoff_json", "source_hash"}}, {"retry_checkpoints", "run_id=?1", []string{"mode", "handoff_json", "source_hash"}},
{"run_schedule_origin", "run_id=?1", []string{"name"}}, {"run_schedule_origin", "run_id=?1", []string{"name"}},
{"run_stage_skills", "run_id=?1", []string{"skills_json"}},
} }
terms := make([]string, 0, len(parts)) terms := make([]string, 0, len(parts))
for _, p := range parts { for _, p := range parts {
+4
View File
@@ -306,6 +306,10 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
return nil, err return nil, err
} }
} }
if r.StageSkills, err = runStageSkills(ctx, tx, id); err != nil {
return nil, err
}
stepSkills(r.Steps, r.StageSkills)
// The run total is one pass over the steps already loaded above: it adds no // The run total is one pass over the steps already loaded above: it adds no
// query and no transcript parse. // query and no transcript parse.
r.Usage = protocol.TotalUsage(r.Steps) r.Usage = protocol.TotalUsage(r.Steps)
+8
View File
@@ -23,6 +23,11 @@ type RunOverrides struct {
StageModels map[string]string StageModels map[string]string
// NotifyMode is auto, on or off for this run. Empty means auto. // NotifyMode is auto, on or off for this run. Empty means auto.
NotifyMode string NotifyMode string
// StageSkills is the run's resolved skills (stage key -> name@N, see
// ResolveStageSkills). It is recorded at admission only and is not part of
// the request-key comparison: a replay resolved after a newer import is
// still the same run and keeps the versions recorded first.
StageSkills map[string][]string
} }
// CreateRun inserts a run and derives its title from the prompt. It is the entry // CreateRun inserts a run and derives its title from the prompt. It is the entry
@@ -127,6 +132,9 @@ func (s *Store) CreateRunTitled(ctx context.Context, d *protocol.PipelineDetail,
return 0, false, err return 0, false, err
} }
} }
if err := recordStageSkills(ctx, tx, id, overrides.StageSkills); err != nil {
return 0, false, err
}
if err := tx.Commit(); err != nil { if err := tx.Commit(); err != nil {
return 0, false, err return 0, false, err
} }
+4 -1
View File
@@ -20,7 +20,10 @@ func (s *Store) initSkills() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS skills (name TEXT PRIMARY KEY, description TEXT NOT NULL, latest_version INTEGER NOT NULL, digest TEXT NOT NULL, imported_at TEXT NOT NULL); _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS skills (name TEXT PRIMARY KEY, description TEXT NOT NULL, latest_version INTEGER NOT NULL, digest TEXT NOT NULL, imported_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS skill_versions (name TEXT NOT NULL REFERENCES skills(name), version INTEGER NOT NULL, digest TEXT NOT NULL, source_path TEXT NOT NULL, imported_at TEXT NOT NULL, PRIMARY KEY(name,version), UNIQUE(name,digest)); CREATE TABLE IF NOT EXISTS skill_versions (name TEXT NOT NULL REFERENCES skills(name), version INTEGER NOT NULL, digest TEXT NOT NULL, source_path TEXT NOT NULL, imported_at TEXT NOT NULL, PRIMARY KEY(name,version), UNIQUE(name,digest));
CREATE TABLE IF NOT EXISTS skill_files (name TEXT NOT NULL, version INTEGER NOT NULL, path TEXT NOT NULL, size INTEGER NOT NULL, PRIMARY KEY(name,version,path), FOREIGN KEY(name,version) REFERENCES skill_versions(name,version));`) CREATE TABLE IF NOT EXISTS skill_files (name TEXT NOT NULL, version INTEGER NOT NULL, path TEXT NOT NULL, size INTEGER NOT NULL, PRIMARY KEY(name,version,path), FOREIGN KEY(name,version) REFERENCES skill_versions(name,version));`)
return err if err != nil {
return err
}
return s.initStageSkills()
} }
// skillImports serialises imports in this server process, so the // skillImports serialises imports in this server process, so the
+255
View File
@@ -0,0 +1,255 @@
package pipeline
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// initStageSkills records each run's resolved skills: stage key -> name@N, the
// exact library versions its model stages load. It is written once at run
// admission and never changes, so every visit (and a retry) is reproducible.
func (s *Store) initStageSkills() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS run_stage_skills (run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id), skills_json TEXT NOT NULL)`)
return err
}
// stageSkillRefs returns the parsed skills block of every model stage that has
// one, in graph order.
func stageSkillRefs(g Graph) (keys []string, refs map[string][]stage.SkillRef, err error) {
refs = map[string][]stage.SkillRef{}
for _, s := range g.Stages {
if stage.EffectiveType(s.Type) != stage.ModelType {
continue
}
parsed, err := stage.SkillRefs(StageDefinition(s))
if err != nil {
return nil, nil, fmt.Errorf("stage %s: %w", s.Key, err)
}
if len(parsed) > 0 {
keys = append(keys, s.Key)
refs[s.Key] = parsed
}
}
return keys, refs, nil
}
// skillVersion checks that the library has ref (a pinned version, or any
// version when unpinned) and returns the version a run would load.
func (s *Store) skillVersion(ctx context.Context, ref stage.SkillRef) (int, error) {
var latest int
if err := s.db.QueryRowContext(ctx, `SELECT latest_version FROM skills WHERE name=?`, ref.Name).Scan(&latest); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("skill %s is not in the server skill library; import it with pipelines skills import", ref.Name)
}
return 0, err
}
if ref.Version == 0 {
return latest, nil
}
var found int
if err := s.db.QueryRowContext(ctx, `SELECT version FROM skill_versions WHERE name=? AND version=?`, ref.Name, ref.Version).Scan(&found); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, fmt.Errorf("skill %s has no version %d in the server skill library (latest is %d)", ref.Name, ref.Version, latest)
}
return 0, err
}
return found, nil
}
// ValidateSkills checks every model stage's skills block against the server
// skill library: each named skill and each pinned version must exist. Drafts
// and publications call it after structural parsing.
func (s *Store) ValidateSkills(ctx context.Context, g Graph) error {
keys, refs, err := stageSkillRefs(g)
if err != nil {
return err
}
for _, key := range keys {
for _, ref := range refs[key] {
if _, err := s.skillVersion(ctx, ref); err != nil {
return fmt.Errorf("stage %s: %w", key, err)
}
}
}
return nil
}
// ResolveStageSkills pins every model stage's skills for one run: name@N stays
// N and an unpinned name takes the library's latest version. prior is the
// resolution recorded on the run a retry replays: an unpinned name it already
// resolved for the same stage keeps that version, so a retry loads the same
// skills even after a newer version was imported. The result maps stage key to
// name@N in definition order and omits stages without skills.
func (s *Store) ResolveStageSkills(ctx context.Context, g Graph, prior map[string][]string) (map[string][]string, error) {
keys, refs, err := stageSkillRefs(g)
if err != nil {
return nil, err
}
resolved := map[string][]string{}
for _, key := range keys {
previous := map[string]int{}
for _, entry := range prior[key] {
if ref, err := stage.ParseSkillRef(entry); err == nil && ref.Version > 0 {
previous[ref.Name] = ref.Version
}
}
for _, ref := range refs[key] {
if ref.Version == 0 && previous[ref.Name] > 0 {
ref.Version = previous[ref.Name]
}
version, err := s.skillVersion(ctx, ref)
if err != nil {
return nil, fmt.Errorf("stage %s: %w", key, err)
}
resolved[key] = append(resolved[key], ref.Name+"@"+strconv.Itoa(version))
}
}
return resolved, nil
}
func recordStageSkills(ctx context.Context, tx *sql.Tx, runID int64, skills map[string][]string) error {
if len(skills) == 0 {
return nil
}
encoded, err := json.Marshal(skills)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, `INSERT INTO run_stage_skills(run_id,skills_json) VALUES(?,?)`, runID, string(encoded))
return err
}
// RunStageSkills returns the skills recorded for a run at admission (nil for
// a run whose stages configure none, including every historical run).
func (s *Store) RunStageSkills(ctx context.Context, runID int64) (map[string][]string, error) {
return runStageSkills(ctx, s.db, runID)
}
func runStageSkills(ctx context.Context, q interface {
QueryRowContext(context.Context, string, ...any) *sql.Row
}, runID int64) (map[string][]string, error) {
var encoded string
err := q.QueryRowContext(ctx, `SELECT skills_json FROM run_stage_skills WHERE run_id=?`, runID).Scan(&encoded)
if errors.Is(err, sql.ErrNoRows) || missingTable(err) {
// No skills, or a read-only database predating skill pinning.
return nil, nil
}
if err != nil {
return nil, err
}
var skills map[string][]string
if err := json.Unmarshal([]byte(encoded), &skills); err != nil {
return nil, err
}
return skills, nil
}
// MaterializeSkills copies exactly the resolved bundles (the files the library
// recorded for each name@N) into root, a directory private to one stage visit,
// as root/skills/<name>/. root is also a Claude Code plugin root: its
// .claude-plugin/plugin.json names the plugin stage.ClaudeSkillPlugin. Files
// are read-only (scripts keep their execute bit); directories stay owner
// writable so run deletion can remove them. It returns nil for no skills.
// reuse keeps an existing copy (a re-adopted visit whose session already loaded
// it); otherwise any leftover at root is replaced, never merged.
func (s *Store) MaterializeSkills(ctx context.Context, resolved []string, root string, reuse bool) (*stage.SkillSet, error) {
if len(resolved) == 0 {
return nil, nil
}
if !filepath.IsAbs(root) {
return nil, fmt.Errorf("skills directory must be absolute")
}
_, statErr := os.Lstat(root)
reuse = reuse && statErr == nil
if statErr == nil && !reuse {
if err := os.RemoveAll(root); err != nil {
return nil, err
}
}
set := &stage.SkillSet{Root: root}
for _, entry := range resolved {
ref, err := stage.ParseSkillRef(entry)
if err != nil || ref.Version == 0 {
return nil, fmt.Errorf("recorded skill %q is not name@version", entry)
}
target := filepath.Join(root, "skills", ref.Name)
if reuse {
set.Bundles = append(set.Bundles, stage.SkillBundle{Name: ref.Name, Version: ref.Version, Dir: target})
continue
}
manifest, err := s.skillManifest(ctx, ref.Name, ref.Version)
if err != nil {
return nil, err
}
if len(manifest) == 0 {
return nil, fmt.Errorf("skill %s is missing from the server skill library", entry)
}
source := filepath.Join(s.dir, "skills", ref.Name, fmt.Sprintf("v%d", ref.Version))
for _, file := range manifest {
if file.Path == "" || filepath.IsAbs(file.Path) || filepath.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "..") {
return nil, fmt.Errorf("skill %s has an invalid file path", entry)
}
if err := copySkillFile(source, target, file.Path, file.Size); err != nil {
return nil, fmt.Errorf("skill %s: %w", entry, err)
}
}
set.Bundles = append(set.Bundles, stage.SkillBundle{Name: ref.Name, Version: ref.Version, Dir: target})
}
if reuse {
return set, nil
}
manifest, _ := json.Marshal(map[string]string{"name": stage.ClaudeSkillPlugin, "description": "Skills configured for this Pipelines stage visit"})
if err := os.MkdirAll(filepath.Join(root, ".claude-plugin"), 0o700); err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(root, ".claude-plugin", "plugin.json"), manifest, 0o400); err != nil {
return nil, err
}
return set, nil
}
func copySkillFile(sourceDir, targetDir, rel string, size int64) error {
source := filepath.Join(sourceDir, filepath.FromSlash(rel))
target := filepath.Join(targetDir, filepath.FromSlash(rel))
info, err := os.Lstat(source)
if err != nil {
return err
}
if !info.Mode().IsRegular() || info.Size() != size {
return fmt.Errorf("library file %s changed since import", rel)
}
data, err := os.ReadFile(source)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return err
}
mode := os.FileMode(0o400)
if strings.HasPrefix(rel, "scripts/") {
mode = 0o500
}
return os.WriteFile(target, data, mode)
}
// stepSkills sets each model step's resolved skills from the run's record.
func stepSkills(steps []protocol.RunStep, skills map[string][]string) {
if len(skills) == 0 {
return
}
for i := range steps {
if names := skills[steps[i].Stage]; len(names) > 0 {
steps[i].Skills = append([]string(nil), names...)
}
}
}
+196
View File
@@ -0,0 +1,196 @@
package pipeline
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
func skillSource(skills string) string {
return "# stage worker\n\n```prompt\nDo it.\n```\n\n```tools\nread\n```\n\n```skills\n" + skills + "\n```\n\n```edges\nsuccess -> ask\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\n```\n\n# stage ask\n\n```prompt\nPick.\n```\n\n```edges\nyes -> #success\n```\n\n```configs\ntype=human\n```\n"
}
func importTestSkill(t *testing.T, s *Store, name, body string, extra ...protocol.SkillFile) protocol.SkillVersion {
t.Helper()
files := append([]protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte("---\nname: " + name + "\ndescription: Test skill.\n---\n" + body + "\n")}}, extra...)
v, err := s.ImportSkill(context.Background(), name, "Test skill.", digestSkill(files), "/src/"+name, files)
if err != nil {
t.Fatal(err)
}
return v
}
func TestSkillsBlockValidatedAgainstTheLibraryOnSubmit(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "pipelines.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
importTestSkill(t, s, "review", "one")
importTestSkill(t, s, "review", "two")
for skills, want := range map[string]string{
"missing": "not in the server skill library",
"review@3": "has no version 3",
"review\nreview@1": "duplicate skill review",
"Review": "lowercase slug",
"review@0": "positive integer",
} {
if _, err := s.PublishChecked(ctx, "skills-bad", skillSource(skills), false, 0); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%q: got %v, want %q", skills, err, want)
}
if _, err := s.SubmitChecked(ctx, "skills-bad", skillSource(skills), false, 0); err == nil {
t.Errorf("%q: draft submission accepted", skills)
}
}
if _, err := s.Submit(ctx, "skills-human", strings.Replace(skillSource("review"), "```configs\ntype=human\n```", "```skills\nreview\n```\n\n```configs\ntype=human\n```", 1)); err == nil || !strings.Contains(err.Error(), "only on model stages") {
t.Fatal("human stage skills:", err)
}
for _, skills := range []string{"review", "review@1", ""} {
if _, err := s.PublishChecked(ctx, "skills-ok-"+skills, skillSource(skills), false, 0); err != nil {
t.Fatalf("%q: %v", skills, err)
}
}
}
func TestRunPinsSkillsAndRetryReusesThem(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "pipelines.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
importTestSkill(t, s, "review", "one")
importTestSkill(t, s, "review", "two")
importTestSkill(t, s, "notes", "first")
if _, err := s.Submit(ctx, "pinned", skillSource("review\nnotes@1")); err != nil {
t.Fatal(err)
}
items, err := s.List(ctx)
if err != nil {
t.Fatal(err)
}
d, err := s.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
resolved, err := s.ResolveStageSkills(ctx, d.Graph, nil)
if err != nil || len(resolved) != 1 || !slices.Equal(resolved["worker"], []string{"review@2", "notes@1"}) {
t.Fatal(resolved, err)
}
id, _, err := s.CreateRunTitled(ctx, d, "first", "workspace", false, nil, map[string]any{"prompt": "go"}, RunOverrides{StageSkills: resolved}, summarise.Title{})
if err != nil {
t.Fatal(err)
}
// A newer import must not change what this run, or a retry of it, loads.
importTestSkill(t, s, "review", "three")
importTestSkill(t, s, "notes", "second")
recorded, err := s.RunStageSkills(ctx, id)
if err != nil || !slices.Equal(recorded["worker"], []string{"review@2", "notes@1"}) {
t.Fatal(recorded, err)
}
retried, err := s.ResolveStageSkills(ctx, d.Graph, recorded)
if err != nil || !slices.Equal(retried["worker"], []string{"review@2", "notes@1"}) {
t.Fatal("retry must reuse recorded versions", retried, err)
}
fresh, err := s.ResolveStageSkills(ctx, d.Graph, nil)
if err != nil || !slices.Equal(fresh["worker"], []string{"review@3", "notes@1"}) {
t.Fatal("a fresh run takes the latest unpinned version", fresh, err)
}
// A replay of the same request key is the same run even though a fresh
// resolution now differs.
again, created, err := s.CreateRunTitled(ctx, d, "first", "workspace", false, nil, map[string]any{"prompt": "go"}, RunOverrides{StageSkills: fresh}, summarise.Title{})
if err != nil || created || again != id {
t.Fatal("replay", again, created, err)
}
if err := s.BeginStep(ctx, id, 1, "worker", map[string]any{}); err != nil {
t.Fatal(err)
}
detail, err := s.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(detail.StageSkills["worker"], []string{"review@2", "notes@1"}) || len(detail.Steps) != 1 || !slices.Equal(detail.Steps[0].Skills, []string{"review@2", "notes@1"}) {
t.Fatalf("detail skills %v step %+v", detail.StageSkills, detail.Steps)
}
if err := s.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "worker", Status: "failed", Outcome: "error"}); err != nil {
t.Fatal(err)
}
if err := s.FinishRun(ctx, id, "failed", "error", "stop", nil); err != nil {
t.Fatal(err)
}
if result, err := s.DeleteRuns(ctx, []int64{id}, t.TempDir(), nil); err != nil || len(result.Deleted) != 1 {
t.Fatal(result, err)
}
if left, err := s.RunStageSkills(ctx, id); err != nil || left != nil {
t.Fatal("deleted run keeps skills", left, err)
}
}
func TestMaterializeSkillsCopiesExactlyTheResolvedBundles(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "pipelines.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
importTestSkill(t, s, "review", "one", protocol.SkillFile{Path: "references/guide.md", Bytes: []byte("guide v1")})
importTestSkill(t, s, "review", "two")
importTestSkill(t, s, "other", "unused")
root := filepath.Join(t.TempDir(), "run", "skills", "01-worker")
if set, err := s.MaterializeSkills(ctx, nil, root, false); err != nil || set != nil {
t.Fatal("no skills", set, err)
}
if _, err := os.Stat(root); !os.IsNotExist(err) {
t.Fatal("no skills must create no directory")
}
set, err := s.MaterializeSkills(ctx, []string{"review@1"}, root, false)
if err != nil {
t.Fatal(err)
}
if set.Root != root || len(set.Bundles) != 1 || set.Bundles[0].Name != "review" || set.Bundles[0].Version != 1 || set.Bundles[0].Dir != filepath.Join(root, "skills", "review") {
t.Fatalf("%+v", set)
}
var files []string
_ = filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() {
rel, _ := filepath.Rel(root, path)
files = append(files, filepath.ToSlash(rel))
if info, _ := d.Info(); info.Mode().Perm()&0o222 != 0 {
t.Errorf("%s is writable: %v", rel, info.Mode())
}
}
return nil
})
if !slices.Equal(files, []string{".claude-plugin/plugin.json", "skills/review/SKILL.md", "skills/review/references/guide.md"}) {
t.Fatal(files)
}
if data, _ := os.ReadFile(filepath.Join(root, "skills", "review", "SKILL.md")); !strings.Contains(string(data), "one") {
t.Fatalf("SKILL.md %q", data)
}
if data, _ := os.ReadFile(filepath.Join(root, ".claude-plugin", "plugin.json")); !strings.Contains(string(data), `"name":"pipelines-stage"`) {
t.Fatalf("plugin.json %q", data)
}
// A re-adopted visit keeps its copy; a fresh one replaces leftovers.
if again, err := s.MaterializeSkills(ctx, []string{"review@1"}, root, true); err != nil || again.Bundles[0].Dir != set.Bundles[0].Dir {
t.Fatal(again, err)
}
if _, err := s.MaterializeSkills(ctx, []string{"review@2"}, root, false); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(root, "skills", "review", "references")); !os.IsNotExist(err) {
t.Fatal("version 2 must not carry version 1's files")
}
if err := os.RemoveAll(filepath.Dir(root)); err != nil {
t.Fatal("read-only copies must still be removable with the run", err)
}
if _, err := s.MaterializeSkills(ctx, []string{"review"}, root, false); err == nil {
t.Fatal("unresolved entries must be refused")
}
}
+4
View File
@@ -358,6 +358,10 @@ func (s *Store) submit(ctx context.Context, name, source string, createOnly bool
defer s.mu.Unlock() defer s.mu.Unlock()
name = strings.TrimSpace(name) name = strings.TrimSpace(name)
g, validation := parse(source) g, validation := parse(source)
if validation == nil {
// Skills blocks name library skills and versions that must exist here.
validation = s.ValidateSkills(ctx, g)
}
if expectedVersion < 0 { if expectedVersion < 0 {
validation = fmt.Errorf("expected version must be nonnegative") validation = fmt.Errorf("expected version must be nonnegative")
} }
+6
View File
@@ -265,6 +265,9 @@ type RunStep struct {
// for non-model stages and historical steps. // for non-model stages and historical steps.
Provider string `json:"provider,omitempty"` Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"` Model string `json:"model,omitempty"`
// Skills are the skill library versions (name@N) this model stage loads,
// resolved once when the run started; empty when it configures none.
Skills []string `json:"skills,omitempty"`
// ArtifactsSkipped and ArtifactsTruncated count files excluded from the // ArtifactsSkipped and ArtifactsTruncated count files excluded from the
// bounded per-step scan (over the file/size cap) and by the total budget. // bounded per-step scan (over the file/size cap) and by the total budget.
ArtifactsSkipped int `json:"artifacts_skipped,omitempty"` ArtifactsSkipped int `json:"artifacts_skipped,omitempty"`
@@ -512,6 +515,9 @@ type RunDetail struct {
Input map[string]any `json:"input"` Input map[string]any `json:"input"`
Output map[string]any `json:"output"` Output map[string]any `json:"output"`
Steps []RunStep `json:"steps"` Steps []RunStep `json:"steps"`
// StageSkills maps a model stage key to the skills (name@N) its skills
// block resolved to when the run started. A retry reuses these versions.
StageSkills map[string][]string `json:"stage_skills,omitempty"`
// Warnings are run-level, read-time notes an operator should see before // Warnings are run-level, read-time notes an operator should see before
// trusting the evidence, e.g. that a visit's file-change capture was partial. // trusting the evidence, e.g. that a visit's file-change capture was partial.
// Derived from Steps by RunWarnings; absent when there is nothing to flag. // Derived from Steps by RunWarnings; absent when there is nothing to flag.
+24 -3
View File
@@ -228,6 +228,19 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
if err != nil { if err != nil {
return nil, err 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 { for _, s := range d.Graph.Stages {
if stage.EffectiveType(s.Type) != stage.ModelType { if stage.EffectiveType(s.Type) != stage.ModelType {
continue continue
@@ -345,7 +358,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
workspace = tree workspace = tree
request.Input["pwd"] = workspace 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) { if isolated != "" && (err != nil || !created) {
// The run was refused or an identical request won the race: the fresh // The run was refused or an identical request won the race: the fresh
// tree holds nothing yet. // 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.ArtifactsDir = artifactsDir
def.Turn = stageTurnPaths(visitTurn) def.Turn = stageTurnPaths(visitTurn)
publicBefore = publicFileSet(visitTurn.RunDir) 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{} operations := &stage.OperationLog{}
var landing stage.LandingAccess var landing stage.LandingAccess
@@ -1874,6 +1893,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
landing = access landing = access
} }
client := r.agentClient(id, sequence, state.artifactDirs, workspace, artifactsDir, operations, request.WritePaths, tools) client := r.agentClient(id, sequence, state.artifactDirs, workspace, artifactsDir, operations, request.WritePaths, tools)
client.Skills = def.Skills
client.LandingAccess = landing client.LandingAccess = landing
client.OnSession = func(session string, active bool) error { client.OnSession = func(session string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second) 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 return
} }
piClient = r.piClient(id, sequence, state.artifactDirs, profile.Executable, workspace, artifactsDir, request.WritePaths, tools) 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 { piClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second) c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
@@ -1952,7 +1973,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
stageSession = piClient.SessionID stageSession = piClient.SessionID
client.Transcript = piClient.Transcript client.Transcript = piClient.Transcript
} else if modelConfig.Harness == stage.ClaudeBackend { } 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 { claudeClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second) c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() 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) result, err = (stage.ModelStage{Client: client}).Run(stageCtx, def, input)
stageSession = client.SessionID stageSession = client.SessionID
} else if stage.EffectiveType(def.Type) == stage.ModelType { } 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 { if adopted != nil {
plain.Backend, plain.Reference = adopted.owner.Backend, adopted.owner.Reference 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 { } else if request.Type == protocol.Validate {
graph, warnings, err := pipeline.ParseDefinitionReport(request.Source) graph, warnings, err := pipeline.ParseDefinitionReport(request.Source)
if err == nil && len(stores) > 0 {
err = stores[0].ValidateSkills(ctx, graph)
}
response.Type = protocol.Validated response.Type = protocol.Validated
response.Warnings = warnings response.Warnings = warnings
if err != nil { if err != nil {
+6
View File
@@ -217,6 +217,12 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
if c.Policy.Shell != nil { if c.Policy.Shell != nil {
prompt += "\nPermitted shell commands: " + strings.Join(c.Policy.Shell, "; ") prompt += "\nPermitted shell commands: " + strings.Join(c.Policy.Shell, "; ")
} }
if resume == "" {
// Owned but not yet prompted: the deferred cleanup stops the session.
if err = c.attachSkills(ctx, c.SessionID); err != nil {
return "", err
}
}
ctx, watch, err = c.watchBudget(ctx, config.Budget, c.SessionID) ctx, watch, err = c.watchBudget(ctx, config.Budget, c.SessionID)
if err != nil { if err != nil {
return "", err return "", err
+88 -11
View File
@@ -50,9 +50,12 @@ type ClaudeStageClient struct {
Tools []string Tools []string
WritePaths []string WritePaths []string
ArtifactsDir string ArtifactsDir string
Policy ToolPolicy // Skills are the visit's configured skills, loaded as a session-only
OnOwnership func(string, string, bool) error // plugin; nil keeps every skill and slash command disabled.
WorkStarted bool Skills *SkillSet
Policy ToolPolicy
OnOwnership func(string, string, bool) error
WorkStarted bool
budget *Budget budget *Budget
// Session totals across the visit's invocations (the prompt and one // Session totals across the visit's invocations (the prompt and one
@@ -145,20 +148,44 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
return rules return rules
} }
// claudeSkillSettings is the flag-settings layer of a Claude stage with
// configured skills. --disable-slash-commands would also disable the plugin
// skills, so ambient skills are turned off individually instead: user, project
// and local settings (and their skills directories) are already not loaded,
// disableBundledSkills turns off the skills that ship with Claude Code, and
// the builtin plugin that contributes a model-invocable skill is disabled. The
// stream guard (claudeSkillGuard) fails the visit if any other skill is
// still invoked.
const claudeSkillSettings = `{"disableBundledSkills":true,"enabledPlugins":{"cc-plugin-plugin-authoring@builtin":false}}`
func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort string, resume bool) []string { func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort string, resume bool) []string {
skilled := !c.Skills.Empty()
// Permission rules come from the declared tools only: a bare Skill rule
// would approve every skill, so each configured skill is approved by name.
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir)
if skilled {
tools = append(append([]string(nil), tools...), "Skill")
}
args := []string{"-p", "--output-format", "stream-json", "--verbose", args := []string{"-p", "--output-format", "stream-json", "--verbose",
"--model", config.Model, "--model", config.Model,
"--permission-mode", "dontAsk", "--permission-mode", "dontAsk",
"--setting-sources", "", "--setting-sources", ""}
"--disable-slash-commands",
"--tools", strings.Join(tools, ",")}
mcpRules, _ := claudeMCPAllowRules(c.Tools) mcpRules, _ := claudeMCPAllowRules(c.Tools)
if len(mcpRules) == 0 { if len(mcpRules) == 0 {
tail := append([]string(nil), args[10:]...) args = append(args, "--strict-mcp-config")
args = append(append(append([]string(nil), args[:10]...), "--strict-mcp-config"), tail...)
} }
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir) if skilled {
args = append(args, "--settings", claudeSkillSettings, "--plugin-dir", c.Skills.Root)
} else {
args = append(args, "--disable-slash-commands")
}
args = append(args, "--tools", strings.Join(tools, ","))
rules = append(rules, mcpRules...) rules = append(rules, mcpRules...)
if skilled {
for _, bundle := range c.Skills.Bundles {
rules = append(rules, "Skill("+ClaudeSkillPlugin+":"+bundle.Name+")")
}
}
if len(rules) > 0 { if len(rules) > 0 {
args = append(args, "--allowedTools") args = append(args, "--allowedTools")
args = append(args, rules...) args = append(args, rules...)
@@ -338,11 +365,55 @@ type claudeStreamRecord struct {
} `json:"rate_limit_info"` } `json:"rate_limit_info"`
Message *struct { Message *struct {
Error string `json:"error"` Error string `json:"error"`
// Content stays raw: a string content must not make the record
// undecodable (it would drop the line from the evidence stream).
Content json.RawMessage `json:"content"`
} `json:"message"` } `json:"message"`
} }
// run executes one CLI invocation and returns its final result text. The // claudeContent is the part of a message content item the skill guard reads.
// process group is always gone when it returns; otherwise ErrStageCleanup. type claudeContent struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name"`
ToolUseID string `json:"tool_use_id"`
IsError bool `json:"is_error"`
Input struct {
Skill string `json:"skill"`
} `json:"input"`
}
// claudeSkillGuard tracks Skill tool calls for skills the visit did not
// configure. A call Claude Code refuses (an unknown or disabled skill) is
// harmless; one whose tool result succeeded loaded an ambient skill, which
// fails the visit.
type claudeSkillGuard struct {
configured *SkillSet
pending map[string]bool
violated bool
}
func (g *claudeSkillGuard) observe(record claudeStreamRecord) {
if record.Message == nil || len(record.Message.Content) == 0 || record.Message.Content[0] != '[' {
return
}
var items []claudeContent
if json.Unmarshal(record.Message.Content, &items) != nil {
return
}
for _, item := range items {
switch {
case record.Type == "assistant" && item.Type == "tool_use" && item.Name == "Skill" && !g.configured.claudeAllowed(item.Input.Skill):
if g.pending == nil {
g.pending = map[string]bool{}
}
g.pending[item.ID] = true
case record.Type == "user" && item.Type == "tool_result" && g.pending[item.ToolUseID] && !item.IsError:
g.violated = true
}
}
}
func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) { func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) {
cmd := exec.Command(c.Executable, args...) cmd := exec.Command(c.Executable, args...)
cmd.Dir = c.Directory cmd.Dir = c.Directory
@@ -379,6 +450,7 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
var refusal, limited bool var refusal, limited bool
var resetsAt int64 var resetsAt int64
var authFailed, sessionMismatch, modelMismatch bool var authFailed, sessionMismatch, modelMismatch bool
skills := &claudeSkillGuard{configured: c.Skills}
scanned := make(chan error, 1) scanned := make(chan error, 1)
go func() { go func() {
scanner := bufio.NewScanner(out) scanner := bufio.NewScanner(out)
@@ -406,7 +478,10 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
limited = true limited = true
resetsAt = record.RateLimit.ResetsAt resetsAt = record.RateLimit.ResetsAt
} }
case "user":
skills.observe(record)
case "assistant": case "assistant":
skills.observe(record)
if record.Message != nil { if record.Message != nil {
switch record.Message.Error { switch record.Message.Error {
case "billing_error", "rate_limit": case "billing_error", "rate_limit":
@@ -480,6 +555,8 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan")) return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan"))
} }
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota) return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota)
case skills.violated:
return "", fmt.Errorf("Claude Code invoked a skill that is not configured for this stage; only the stage's skills block may be used")
case sessionMismatch || modelMismatch: case sessionMismatch || modelMismatch:
return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport) return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport)
case final == nil: case final == nil:
+10
View File
@@ -84,6 +84,16 @@ case "$FAKE_CLAUDE_CASE" in
init "$session" "$model" init "$session" "$model"
echo '{"type":"result","subtype":"error_max_turns","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}' echo '{"type":"result","subtype":"error_max_turns","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}'
;; ;;
skill|ambientskill|refusedskill)
init "$session" "$model"
name=pipelines-stage:hello; failed=false
if [ "$FAKE_CLAUDE_CASE" != skill ]; then name=dataviz; fi
if [ "$FAKE_CLAUDE_CASE" = refusedskill ]; then failed=true; fi
echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":"a plain string content"}}'
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Skill","input":{"skill":"'"$name"'"}}]}}'
echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"Launching skill: '"$name"'","is_error":'"$failed"'}]}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
;;
othermodel) othermodel)
init "$session" "some-other-model" init "$session" "some-other-model"
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}' echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
+2
View File
@@ -24,6 +24,8 @@ func (HumanStage) Validate(def Definition) error {
for name := range def.Blocks { for name := range def.Blocks {
switch name { switch name {
case "configs", "edges", "output", "prompt": case "configs", "edges", "output", "prompt":
case "skills":
return errSkillsModelOnly("human")
default: default:
return fmt.Errorf("unexpected block %q for human stage", name) return fmt.Errorf("unexpected block %q for human stage", name)
} }
+11 -2
View File
@@ -3,6 +3,7 @@ package stage
import ( import (
"context" "context"
"fmt" "fmt"
"slices"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -58,7 +59,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
} }
for block := range def.Blocks { for block := range def.Blocks {
switch block { switch block {
case "output", "prompt", "edges", "configs", "tools", "permissions", "checks", "verification": case "output", "prompt", "edges", "configs", "tools", "permissions", "checks", "verification", "skills":
default: default:
return ModelSpec{}, fmt.Errorf("unexpected block %q for model stage", block) return ModelSpec{}, fmt.Errorf("unexpected block %q for model stage", block)
} }
@@ -69,6 +70,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if _, err := StagePermissions(def); err != nil { if _, err := StagePermissions(def); err != nil {
return ModelSpec{}, err return ModelSpec{}, err
} }
skillRefs, err := SkillRefs(def)
if err != nil {
return ModelSpec{}, err
}
if _, err := VerificationTargetFor(def); err != nil { if _, err := VerificationTargetFor(def); err != nil {
return ModelSpec{}, err return ModelSpec{}, err
} }
@@ -113,10 +118,14 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
return ModelSpec{}, err return ModelSpec{}, err
} }
if backend == "pi" { if backend == "pi" {
tools, _, _ := ToolNames(def) tools, explicit, _ := ToolNames(def)
if _, err := piTools(tools); err != nil { if _, err := piTools(tools); err != nil {
return ModelSpec{}, err return ModelSpec{}, err
} }
if len(skillRefs) > 0 && explicit && !slices.Contains(tools, "read") {
// Pi advertises a skill by path and the model reads its SKILL.md.
return ModelSpec{}, fmt.Errorf("the pi harness loads skills with its read tool; add read to the tools block or remove the skills block")
}
} }
if backend != ClaudeBackend { if backend != ClaudeBackend {
tools, _, _ := ToolNames(def) tools, _, _ := ToolNames(def)
+2
View File
@@ -37,6 +37,8 @@ func (NtfyStage) Validate(def Definition) error {
for name := range def.Blocks { for name := range def.Blocks {
switch name { switch name {
case "configs", "edges", "output": case "configs", "edges", "output":
case "skills":
return errSkillsModelOnly("ntfy")
default: default:
return fmt.Errorf("unexpected block %q for ntfy stage", name) return fmt.Errorf("unexpected block %q for ntfy stage", name)
} }
+8
View File
@@ -36,6 +36,9 @@ type OpenCodeClient struct {
ArtifactsDir string ArtifactsDir string
Operations *OperationLog Operations *OperationLog
OnGenerationSession func(id, backend, reference string, active bool) error OnGenerationSession func(id, backend, reference string, active bool) error
// Skills are attached to each new session as instruction entries (see
// attachSkills); nil attaches none.
Skills *SkillSet
connection *opencode.Connection connection *opencode.Connection
command func(context.Context, string, ...string) ([]byte, error) command func(context.Context, string, ...string) ([]byte, error)
sessionPollInterval time.Duration // test seam; defaults to defaultSessionPollInterval sessionPollInterval time.Duration // test seam; defaults to defaultSessionPollInterval
@@ -413,6 +416,11 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
return "", err return "", err
} }
} }
if resume == "" {
if err = c.attachSkills(ctx, session.Data.ID); err != nil {
return "", err
}
}
ctx, watch, err = c.watchBudget(ctx, config.Budget, session.Data.ID) ctx, watch, err = c.watchBudget(ctx, config.Budget, session.Data.ID)
if err != nil { if err != nil {
return "", err return "", err
+57
View File
@@ -0,0 +1,57 @@
package stage
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
)
// OpenCode discovers skills per service location (config `skills` paths and
// the standard skills directories), and a stage shares one long-lived service,
// so a session cannot be given private skills through skill discovery. The
// stage session's deny-all permission rules already keep OpenCode's own skill
// tool, and with it every ambient skill, unavailable. The configured skills are
// attached instead as durable per-session instruction entries (the V2
// experimental session instructions API), one entry per skill carrying its
// SKILL.md and the private directory holding its bundled files.
// openCodeSkillEntryKey is the instruction entry key for one skill.
func openCodeSkillEntryKey(name string) string { return "pipelines-skill-" + name }
// openCodeSkillEntry is the instruction text for one materialised skill.
func openCodeSkillEntry(bundle SkillBundle) (string, error) {
data, err := os.ReadFile(filepath.Join(bundle.Dir, "SKILL.md"))
if err != nil {
return "", fmt.Errorf("skill %s@%d: read SKILL.md: %w", bundle.Name, bundle.Version, err)
}
return "Pipelines stage skill " + bundle.Name + " (version " + strconv.Itoa(bundle.Version) + ") is configured for this stage. " +
"Follow its instructions below when the task calls for them. Its bundled files (references/, scripts/, assets/) are in " + bundle.Dir +
" and are read-only.\n\n" + string(data), nil
}
// attachSkills gives a freshly created, not yet prompted session the visit's
// configured skills. A V1 service has no per-session instructions API, so a
// configured skill fails the visit there rather than being silently dropped.
func (c *OpenCodeClient) attachSkills(ctx context.Context, sessionID string) error {
if c.Skills.Empty() {
return nil
}
if c.Backend != "v2" {
return fmt.Errorf("skills need the OpenCode V2 service (per-session instruction entries); this stage's OpenCode backend is %q", c.Backend)
}
if !sessionIDPattern.MatchString(sessionID) {
return fmt.Errorf("OpenCode returned an invalid session ID")
}
for _, bundle := range c.Skills.Bundles {
value, err := openCodeSkillEntry(bundle)
if err != nil {
return err
}
if _, err := c.call(ctx, "put", "/api/experimental/session/"+sessionID+"/instructions/entries/"+openCodeSkillEntryKey(bundle.Name), map[string]string{"value": value}); err != nil {
return fmt.Errorf("attach skill %s@%d to the OpenCode session: %w", bundle.Name, bundle.Version, err)
}
}
return nil
}
+24 -1
View File
@@ -31,6 +31,9 @@ type PiClient struct {
// PIPELINES_ARTIFACTS_DIR so its tools can write stage artifacts. // PIPELINES_ARTIFACTS_DIR so its tools can write stage artifacts.
ArtifactsDir string ArtifactsDir string
ArtifactAccess ArtifactAccess ArtifactAccess ArtifactAccess
// Skills are loaded with --skill while --no-skills keeps every discovered
// and configured skill out; nil loads none.
Skills *SkillSet
Policy ToolPolicy Policy ToolPolicy
OnSession func(string, bool) error OnSession func(string, bool) error
OnOwnership func(string, string, bool) error OnOwnership func(string, string, bool) error
@@ -71,6 +74,11 @@ func piPolicyMap(c *PiClient, tools []string) map[string]any {
if paths == nil { if paths == nil {
paths = []string{} paths = []string{}
} }
read := c.ArtifactAccess.Read
if !c.Skills.Empty() {
// The model reads each skill's SKILL.md and bundled files by path.
read = append(append([]string(nil), read...), c.Skills.Root)
}
return map[string]any{ return map[string]any{
"directory": c.Directory, "directory": c.Directory,
"tools": tools, "tools": tools,
@@ -79,7 +87,7 @@ func piPolicyMap(c *PiClient, tools []string) map[string]any {
"shell": c.Policy.Shell, "shell": c.Policy.Shell,
"artifact_write": c.ArtifactAccess.Write, "artifact_write": c.ArtifactAccess.Write,
"artifact_write_shared": c.ArtifactAccess.WriteShared, "artifact_write_shared": c.ArtifactAccess.WriteShared,
"artifact_read": c.ArtifactAccess.Read, "artifact_read": read,
} }
} }
@@ -159,6 +167,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri
if thinking != "" { if thinking != "" {
args = append(args, "--thinking", thinking) args = append(args, "--thinking", thinking)
} }
args = append(args, piSkillArgs(c.Skills)...)
if len(tools) == 0 { if len(tools) == 0 {
args = append(args, "--no-tools") args = append(args, "--no-tools")
} else { } else {
@@ -652,3 +661,17 @@ func PiEvidence(reference string) (string, error) {
data, err = io.ReadAll(io.LimitReader(file, 8<<20)) data, err = io.ReadAll(io.LimitReader(file, 8<<20))
return RedactEvidence(string(data)), err return RedactEvidence(string(data)), err
} }
// piSkillArgs loads exactly the visit's configured skills. Pi documents that
// explicit --skill paths still load under --no-skills, which keeps disabling
// every discovered (user, project) and settings-configured skill.
func piSkillArgs(set *SkillSet) []string {
if set.Empty() {
return nil
}
args := make([]string, 0, 2*len(set.Bundles))
for _, bundle := range set.Bundles {
args = append(args, "--skill", bundle.Dir)
}
return args
}
+130
View File
@@ -0,0 +1,130 @@
package stage
import (
"fmt"
"strconv"
"strings"
"git.a-wan.net/alan/pipelines/internal/skills"
)
// SkillRef is one entry of a model stage's `skills` block: a server skill
// library name, pinned to Version when it is positive and otherwise resolved to
// the library's latest version when the run starts.
type SkillRef struct {
Name string
Version int
}
// String renders the entry as written in a definition: name or name@N.
func (r SkillRef) String() string {
if r.Version > 0 {
return r.Name + "@" + strconv.Itoa(r.Version)
}
return r.Name
}
// ParseSkillRef parses one `name` or `name@N` entry. N must be a positive
// integer without sign or leading zeros.
func ParseSkillRef(text string) (SkillRef, error) {
text = strings.TrimSpace(text)
name, version, pinned := strings.Cut(text, "@")
if err := skills.ValidateName(name); err != nil {
return SkillRef{}, fmt.Errorf("invalid skill %q: %w", text, err)
}
ref := SkillRef{Name: name}
if pinned {
n, err := strconv.Atoi(version)
if err != nil || n <= 0 || strconv.Itoa(n) != version {
return SkillRef{}, fmt.Errorf("invalid skill %q: the version after @ must be a positive integer", text)
}
ref.Version = n
}
return ref, nil
}
// SkillRefs parses a model stage's optional `skills` block, one entry per
// line. An absent or empty block configures no skills. A skill may appear
// only once, pinned or not.
func SkillRefs(def Definition) ([]SkillRef, error) {
text, present := def.Blocks["skills"]
if !present {
return nil, nil
}
var refs []SkillRef
seen := map[string]bool{}
for _, line := range strings.Split(text, "\n") {
if strings.TrimSpace(line) == "" {
continue
}
ref, err := ParseSkillRef(line)
if err != nil {
return nil, err
}
if seen[ref.Name] {
return nil, fmt.Errorf("duplicate skill %s", ref.Name)
}
seen[ref.Name] = true
refs = append(refs, ref)
}
return refs, nil
}
// errSkillsModelOnly is the clear diagnostic for a skills block on a stage that
// has no model session to load skills into.
func errSkillsModelOnly(kind string) error {
return fmt.Errorf("skills blocks are supported only on model stages, not %s stages", kind)
}
// ClaudeSkillPlugin is the name of the per-visit plugin a Claude stage's
// configured skills are loaded from; Claude Code names its skills
// ClaudeSkillPlugin:<skill>.
const ClaudeSkillPlugin = "pipelines-stage"
// SkillBundle is one resolved skill copied for a single stage visit. Dir holds
// the bundle (SKILL.md and its references/, scripts/ and assets/).
type SkillBundle struct {
Name string
Version int
Dir string
}
// SkillSet is the runtime-provided skill material for one model visit. Root is
// the visit's private skills directory: it is also a Claude Code plugin root
// (.claude-plugin/plugin.json) whose skills/<name>/ entries are the bundles.
// A nil or empty set means the stage configured no skills.
type SkillSet struct {
Root string
Bundles []SkillBundle
}
// Empty reports whether the set configures no skills.
func (s *SkillSet) Empty() bool { return s == nil || len(s.Bundles) == 0 }
// Names lists name@version for every bundle, in definition order.
func (s *SkillSet) Names() []string {
if s.Empty() {
return nil
}
names := make([]string, 0, len(s.Bundles))
for _, b := range s.Bundles {
names = append(names, b.Name+"@"+strconv.Itoa(b.Version))
}
return names
}
// claudeAllowed reports whether a Claude Code Skill tool call names one of the
// configured skills. Only the plugin-qualified name counts: a bare name could
// be an ambient skill of the same name.
func (s *SkillSet) claudeAllowed(name string) bool {
if s.Empty() {
return false
}
name = strings.TrimPrefix(strings.TrimSpace(name), "/")
for _, b := range s.Bundles {
if name == ClaudeSkillPlugin+":"+b.Name {
return true
}
}
return false
}
+269
View File
@@ -0,0 +1,269 @@
package stage
import (
"context"
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
func TestSkillRefsParsePinsAndRejectMistakes(t *testing.T) {
def := Definition{Blocks: map[string]string{"skills": "\n review-checklist \nrelease-notes@3\n\n"}}
refs, err := SkillRefs(def)
if err != nil || !slices.Equal(refs, []SkillRef{{Name: "review-checklist"}, {Name: "release-notes", Version: 3}}) {
t.Fatal(refs, err)
}
if refs[0].String() != "review-checklist" || refs[1].String() != "release-notes@3" {
t.Fatal(refs)
}
for _, text := range []string{"", "\n \n"} {
if refs, err := SkillRefs(Definition{Blocks: map[string]string{"skills": text}}); err != nil || refs != nil {
t.Fatalf("empty block %q: %v %v", text, refs, err)
}
}
if refs, err := SkillRefs(Definition{}); err != nil || refs != nil {
t.Fatal("absent block", refs, err)
}
for text, want := range map[string]string{
"Bad_Name": "lowercase slug",
"a@0": "positive integer",
"a@-1": "positive integer",
"a@01": "positive integer",
"a@x": "positive integer",
"a@": "positive integer",
"a@1\nb\na@2": "duplicate skill a",
"a\na": "duplicate skill a",
"a b": "lowercase slug",
"../etc@1": "lowercase slug",
"review@1@2": "positive integer",
"name@1 # note": "positive integer",
} {
if _, err := SkillRefs(Definition{Blocks: map[string]string{"skills": text}}); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%q: got %v, want %q", text, err, want)
}
}
}
func TestSkillsBlockValidationByStageTypeAndHarness(t *testing.T) {
model := modelDefinition()
model.Blocks["skills"] = "review@2"
if err := (ModelStage{}).Validate(model); err != nil {
t.Fatal("opencode model stage:", err)
}
model.Blocks["skills"] = "review@0"
if err := (ModelStage{}).Validate(model); err == nil {
t.Fatal("a bad version must be rejected")
}
pi := modelDefinition()
pi.Configs["harness"] = "pi"
pi.Blocks["skills"] = "review"
pi.Blocks["tools"] = "grep"
if err := (ModelStage{}).Validate(pi); err == nil || !strings.Contains(err.Error(), "read tool") {
t.Fatal("pi without read:", err)
}
pi.Blocks["tools"] = "read\ngrep"
if err := (ModelStage{}).Validate(pi); err != nil {
t.Fatal("pi with read:", err)
}
delete(pi.Blocks, "tools") // the legacy bundle includes read
if err := (ModelStage{}).Validate(pi); err != nil {
t.Fatal("pi legacy tools:", err)
}
human := Definition{Key: "ask", Type: HumanType, Blocks: map[string]string{"prompt": "Pick", "skills": "review"}, Edges: map[string]string{"yes": "#success", "error": "#failure"}}
if err := (HumanStage{}).Validate(human); err == nil || !strings.Contains(err.Error(), "only on model stages") {
t.Fatal("human:", err)
}
ntfy := Definition{Key: "tell", Type: NtfyType, Blocks: map[string]string{"skills": "review"}, Configs: map[string]string{"destination": "phone"}, Edges: map[string]string{"success": "#success", "error": "#failure"}}
if err := (NtfyStage{}).Validate(ntfy); err == nil || !strings.Contains(err.Error(), "only on model stages") {
t.Fatal("ntfy:", err)
}
}
func testSkillSet(t *testing.T) *SkillSet {
t.Helper()
root := t.TempDir()
dir := filepath.Join(root, "skills", "hello")
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: hello\ndescription: Says hello.\n---\nSay hello.\n"), 0o400); err != nil {
t.Fatal(err)
}
return &SkillSet{Root: root, Bundles: []SkillBundle{{Name: "hello", Version: 2, Dir: dir}}}
}
func TestClaudeStageSkillsLoadAsSessionPlugin(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "skill")
client.Skills = testSkillSet(t)
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
calls := fakeClaudeArgs(t, root)
want := []string{"-p", "--output-format", "stream-json", "--verbose", "--model", "claude-haiku-5-5",
"--permission-mode", "dontAsk", "--setting-sources", "", "--strict-mcp-config",
"--settings", claudeSkillSettings, "--plugin-dir", client.Skills.Root,
"--tools", "Read,Skill", "--allowedTools", "Read", "Skill(pipelines-stage:hello)", "--session-id", client.SessionID}
if len(calls) != 1 || !slices.Equal(calls[0], want) {
t.Fatalf("args\n got %q\nwant %q", calls, want)
}
var settings map[string]any
if err := json.Unmarshal([]byte(claudeSkillSettings), &settings); err != nil || settings["disableBundledSkills"] != true {
t.Fatal("settings", settings, err)
}
}
func TestClaudeStageAmbientSkillFailsTheVisit(t *testing.T) {
client, _, _ := fakeClaudeClient(t, "ambientskill")
client.Skills = testSkillSet(t)
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err == nil || !strings.Contains(err.Error(), "not configured for this stage") {
t.Fatal(err)
}
// Without configured skills any loaded skill is a violation too.
client, _, _ = fakeClaudeClient(t, "skill")
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err == nil {
t.Fatal("a skill call without configured skills must fail")
}
// A call Claude Code refused (unknown or disabled skill) loaded nothing.
client, _, _ = fakeClaudeClient(t, "refusedskill")
client.Skills = testSkillSet(t)
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal("a refused ambient skill call must not fail the visit:", err)
}
// String message content stays in the evidence stream.
if !strings.Contains(client.Transcript, "a plain string content") {
t.Fatal("string-content record dropped from the transcript")
}
}
func TestPiSkillArgsAndReadScope(t *testing.T) {
if args := piSkillArgs(nil); args != nil {
t.Fatal(args)
}
set := testSkillSet(t)
if args := piSkillArgs(set); !slices.Equal(args, []string{"--skill", set.Bundles[0].Dir}) {
t.Fatal(args)
}
client := &PiClient{Directory: "/work", ArtifactAccess: ArtifactAccess{Read: []string{"/runs/1/stages/01-a"}}}
if read := piPolicyMap(client, nil)["artifact_read"].([]string); len(read) != 1 {
t.Fatal("no skills widened reads", read)
}
client.Skills = set
if read := piPolicyMap(client, nil)["artifact_read"].([]string); !slices.Equal(read, []string{"/runs/1/stages/01-a", set.Root}) {
t.Fatal(read)
}
if len(client.ArtifactAccess.Read) != 1 {
t.Fatal("caller's read list mutated")
}
}
func TestPiLaunchesWithExplicitSkillsOnly(t *testing.T) {
for _, skilled := range []bool{false, true} {
root := t.TempDir()
t.Setenv("XDG_CACHE_HOME", root)
t.Setenv("HOME", root)
t.Setenv("PIPELINES_PI_FIXTURE", "1")
t.Setenv("PI_FIXTURE_CASE", "success")
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
wrapper := filepath.Join(root, "pi")
script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > '" + filepath.Join(root, "args") + "'\nexec '" + executable + "' -test.run=^TestPiRPCFixture$\n"
if err := os.WriteFile(wrapper, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
client := &PiClient{Executable: wrapper, Directory: root, Tools: []string{"read"}}
if skilled {
client.Skills = testSkillSet(t)
}
if _, err := client.Generate(context.Background(), ModelConfig{Provider: "fixture", Model: "model", Budget: NewBudget(0, 100)}, "task"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(root, "args"))
if err != nil {
t.Fatal(err)
}
args := strings.Split(strings.TrimSpace(string(data)), "\n")
if !slices.Contains(args, "--no-skills") {
t.Fatal("--no-skills must stay", args)
}
index := slices.Index(args, "--skill")
if skilled != (index >= 0) || (skilled && args[index+1] != client.Skills.Bundles[0].Dir) {
t.Fatalf("skilled=%v args %q", skilled, args)
}
}
}
func TestOpenCodeSkillsAttachAsSessionInstructionEntries(t *testing.T) {
set := testSkillSet(t)
var calls [][]string
client := &OpenCodeClient{Backend: "v2", Skills: set, command: func(_ context.Context, _ string, args ...string) ([]byte, error) {
calls = append(calls, args)
return nil, nil
}}
if err := client.attachSkills(context.Background(), "ses_one"); err != nil {
t.Fatal(err)
}
if len(calls) != 1 || calls[0][1] != "put" || calls[0][2] != "/api/experimental/session/ses_one/instructions/entries/pipelines-skill-hello" {
t.Fatal(calls)
}
var body map[string]string
if err := json.Unmarshal([]byte(calls[0][4]), &body); err != nil || !strings.Contains(body["value"], "Say hello.") || !strings.Contains(body["value"], set.Bundles[0].Dir) || !strings.Contains(body["value"], "version 2") {
t.Fatal(body, err)
}
calls = nil
client.Skills = nil
if err := client.attachSkills(context.Background(), "ses_one"); err != nil || calls != nil {
t.Fatal("no skills must make no calls", calls, err)
}
client.Skills, client.Backend = set, "v1"
if err := client.attachSkills(context.Background(), "ses_one"); err == nil || !strings.Contains(err.Error(), "V2") || calls != nil {
t.Fatal("v1 must refuse configured skills", err)
}
}
func TestOpenCodeAgentSkillsAttachBeforePromptAndGrantReads(t *testing.T) {
client := &AgentClient{Tools: []string{"read"}}
client.Directory = "/work"
client.Backend = "v2"
client.Skills = testSkillSet(t)
allowed := false
for _, rule := range client.permissionRules() {
if rule["action"] == "external_directory" && rule["effect"] == "allow" && rule["resource"] == filepath.ToSlash(filepath.Join(client.Skills.Root, "*")) {
allowed = true
}
if rule["action"] == "skill" && rule["effect"] == "allow" {
t.Fatal("OpenCode's own skill tool must stay denied")
}
}
if !allowed {
t.Fatal("configured skills must be readable")
}
var order []string
client.command = func(_ context.Context, _ string, args ...string) ([]byte, error) {
order = append(order, args[1]+" "+args[2])
switch {
case args[2] == "/api/session":
return []byte(`{"data":{"id":"ses_owned"}}`), nil
case strings.HasSuffix(args[2], "/prompt"):
return nil, os.ErrDeadlineExceeded
}
return []byte(`{"data":[]}`), nil
}
_, _ = client.Generate(context.Background(), ModelConfig{}, "task")
entry := slices.Index(order, "put /api/experimental/session/ses_owned/instructions/entries/pipelines-skill-hello")
prompt := slices.Index(order, "post /api/session/ses_owned/prompt")
if entry < 0 || prompt < 0 || entry > prompt {
t.Fatal(order)
}
// Without read tools, no read grant is added for the skills directory.
client.Tools = []string{}
for _, rule := range client.permissionRules() {
if rule["action"] == "external_directory" && rule["effect"] == "allow" {
t.Fatal("text-only stages get no directory grants", rule)
}
}
}
+6 -3
View File
@@ -34,9 +34,12 @@ type Definition struct {
// visit; empty when the runner did not provide one (for example in tests). // visit; empty when the runner did not provide one (for example in tests).
ArtifactsDir string ArtifactsDir string
Turn TurnPaths Turn TurnPaths
Blocks map[string]string // Skills is the visit's materialised skills block (runtime-provided, like
Configs map[string]string // ArtifactsDir); nil when the stage configures none or in tests.
Edges map[string]string Skills *SkillSet
Blocks map[string]string
Configs map[string]string
Edges map[string]string
} }
// Result selects one declared outcome. The future graph runner owns resolving // Result selects one declared outcome. The future graph runner owns resolving
+6 -1
View File
@@ -293,7 +293,12 @@ func (c *AgentClient) permissionRules() []map[string]string {
writeArtifacts = writeArtifacts || tool == "edit" writeArtifacts = writeArtifacts || tool == "edit"
} }
if readArtifacts { if readArtifacts {
for _, directory := range c.ArtifactAccess.Read { read := c.ArtifactAccess.Read
if !c.Skills.Empty() {
// The configured skills' bundled references/, scripts/ and assets/.
read = append(append([]string(nil), read...), c.Skills.Root)
}
for _, directory := range read {
if artifactDirectory(directory) { if artifactDirectory(directory) {
allow("external_directory", filepath.ToSlash(filepath.Join(directory, "*"))) allow("external_directory", filepath.ToSlash(filepath.Join(directory, "*")))
} }