Finalize reviewed destination and skill changes

Preserve Settings as an independent navigation destination while landing the reviewed notification and skill-management updates. Keep the server and CLI skill contracts versioned and validated so the merged tree can be verified by the delivery gate.
This commit is contained in:
2026-11-12 11:30:17 +00:00
parent 26bb583f10
commit a733a927f3
33 changed files with 1344 additions and 42 deletions
@@ -94,8 +94,11 @@ produce the required three strings, so adding this stage alone cannot cover it.
Independently of any `notify` block, the server publishes one run-level attention
notification to the same already-configured `system` destination when a run needs a
person: when it enters `waiting` (a human stage asked for a decision), or when it
fails or is interrupted. An auto-mode run always notifies for failure/interruption;
a successful auto-mode run notifies only when the operator enables `run_finished`.
has an unexpected failure or interruption. A deliberate route to `#failure` with
its reason is recorded as an expected failure: it remains in Runs but does not
notify or appear in Needs you. Explicit `run_finished`/`on` completion notifications
still include expected failures. An auto-mode run always notifies unexpected
failure/interruption; a successful auto-mode run notifies only when the operator enables `run_finished`.
Runs marked `on` notify at completion, while `off` disables these notifications.
Queued and running runs send nothing. You do not author these; they are the operator
default, so a run you never wired still reaches the operator.
+3
View File
@@ -285,6 +285,9 @@ func parse(f *flag.FlagSet, args []string) error {
}
func (a App) Run(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "skills" {
return a.skillsCommand(ctx, args[1:])
}
if len(args) > 0 && args[0] == "choose-model" {
return a.chooseModel(ctx, args[1:])
}
+1
View File
@@ -2,6 +2,7 @@ package cli
// Help is also the public command inventory for agents and parity checks.
var usage = map[string]string{
"skills": "skills import <folder> [--yes] | skills list | skills show <name> [--version N]",
"repair-session-export": "repair-session-export RUN_ID SEQUENCE [--json]",
"provider-check": "provider-check --model PROVIDER/MODEL [--yes] [--json]",
"new": "new [name] [prompt] [--template KEY] [--no-open | --json]",
+126
View File
@@ -0,0 +1,126 @@
package cli
import (
"context"
"flag"
"fmt"
"git.a-wan.net/alan/pipelines/internal/client"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/skills"
)
func (a App) skillsCommand(ctx context.Context, args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: pipelines skills import|list|show")
}
if args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
_, err := fmt.Fprintln(a.Out, "Usage: pipelines skills import <folder> [--yes] | skills list | skills show <name> [--version N]")
return err
}
// Accept flags after the folder, matching the rest of the Pipelines CLI.
var flags, positionals []string
for i := 1; i < len(args); i++ {
if args[i] == "--yes" || args[i] == "--json" || args[i] == "-json" {
flags = append(flags, args[i])
continue
}
if args[i] == "--url" || args[i] == "--version" {
if i+1 >= len(args) {
return fmt.Errorf("%s needs a value", args[i])
}
flags = append(flags, args[i], args[i+1])
i++
continue
}
positionals = append(positionals, args[i])
}
args = append([]string{args[0]}, append(flags, positionals...)...)
sub := args[0]
fs := flag.NewFlagSet("skills "+sub, flag.ContinueOnError)
fs.SetOutput(a.Err)
url := envOr("PIPELINES_URL", "ws://127.0.0.1:8080/connect")
yes := false
version := 0
jsonMode := false
fs.StringVar(&url, "url", url, "Pipeline server WebSocket URL")
fs.BoolVar(&yes, "yes", false, "Confirm import without prompting")
fs.BoolVar(&jsonMode, "json", false, "Machine-readable JSON")
fs.IntVar(&version, "version", 0, "Immutable version (0 = latest)")
if err := fs.Parse(args[1:]); err != nil {
return err
}
pos := fs.Args()
if sub == "import" {
if len(pos) != 1 {
return fmt.Errorf("skills import requires a folder")
}
b, e := skills.Validate(pos[0])
if e != nil {
return e
}
if !yes {
if e = a.confirmAction(fmt.Sprintf("Import skill %s (%d files, %d bytes, digest %s)?", b.Name, len(b.Files), b.TotalBytes, b.Digest), false); e != nil {
return e
}
}
c, e := client.Open(ctx, url)
if e != nil {
return e
}
defer c.Close()
files := make([]protocol.SkillFile, len(b.Files))
for i, f := range b.Files {
files[i] = protocol.SkillFile{Path: f.Path, Bytes: f.Bytes}
}
r, e := c.Call(ctx, protocol.Message{Type: protocol.ImportSkill, Name: b.Name, Description: b.Description, Digest: b.Digest, SourcePath: pos[0], SkillFiles: files})
if e != nil {
return e
}
if r.SkillVersion == nil {
return fmt.Errorf("server returned no skill version")
}
return a.outputSkill(r.SkillVersion, jsonMode)
}
if sub != "list" && sub != "show" {
return fmt.Errorf("unknown skills command %q", sub)
}
c, e := client.Open(ctx, url)
if e != nil {
return e
}
defer c.Close()
if sub == "list" {
if len(pos) != 0 {
return fmt.Errorf("skills list takes no arguments")
}
r, e := c.Call(ctx, protocol.Message{Type: protocol.ListSkills})
if e != nil {
return e
}
if jsonMode {
return a.output(r)
}
for _, s := range r.SkillSummaries {
fmt.Fprintf(a.Out, "%s\tv%d\t%s\n", s.Name, s.LatestVersion, s.Digest)
}
return nil
}
if len(pos) != 1 {
return fmt.Errorf("skills show requires a name")
}
r, e := c.Call(ctx, protocol.Message{Type: protocol.ShowSkill, Name: pos[0], Version: version})
if e != nil {
return e
}
if r.SkillVersion == nil {
return fmt.Errorf("server returned no skill")
}
return a.outputSkill(r.SkillVersion, jsonMode)
}
func (a App) outputSkill(s *protocol.SkillVersion, jsonMode bool) error {
if jsonMode {
return a.output(s)
}
fmt.Fprintf(a.Out, "%s v%d\t%s\n%s\n", s.Name, s.Version, s.Digest, s.SkillMD)
return nil
}
@@ -176,6 +176,54 @@ func TestRunNotificationTransitionModesAndCoverage(t *testing.T) {
}
}
func TestFailedRunNotificationClassifiesExpectedAndUnexpectedCauses(t *testing.T) {
tests := []struct {
name, status, outcome, diagnostic string
expectedKind string
notify bool
completeStep bool
control *protocol.ControlEvidence
}{
{name: "blocked with reason", status: "failed", outcome: "blocked", diagnostic: "Blocked: approval is required", expectedKind: "expected", notify: false, completeStep: true},
{name: "harness error", status: "failed", outcome: "error", diagnostic: "agent exception: process exited", expectedKind: "unexpected", notify: true},
{name: "budget exceeded", status: "failed", outcome: "error", diagnostic: "token budget exceeded", expectedKind: "unexpected", notify: true},
{name: "timeout", status: "failed", outcome: "error", diagnostic: "stage timed out", expectedKind: "unexpected", notify: true},
{name: "interrupted", status: "interrupted", outcome: "", diagnostic: "Server stopped; run was not resumed", expectedKind: "unexpected", notify: true},
{name: "visit limit", status: "failed", outcome: "error", diagnostic: "stopped stage after 10 visits", expectedKind: "unexpected", notify: true},
{name: "blocked reason mentions stopping", status: "failed", outcome: "blocked", diagnostic: "Blocked: stopped until approval", expectedKind: "expected", notify: false, completeStep: true},
{name: "visit limit from control evidence", status: "failed", outcome: "rejected", diagnostic: "Pipelines stopped review after 3 visits on outcome rejected", expectedKind: "unexpected", notify: true, completeStep: true, control: &protocol.ControlEvidence{Visit: 3, MaxVisits: 3, LimitReached: true}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "classification.db"), "auto")
defer s.Close()
if test.completeStep {
if err := s.FinishStep(ctx, id, protocol.RunStep{Sequence: 1, Stage: "gate", Status: "completed", Outcome: test.outcome, Target: protocol.FailureEnd, Diagnostic: test.diagnostic, Control: test.control}); err != nil {
t.Fatal(err)
}
}
if err := s.FinishRun(ctx, id, test.status, test.outcome, test.diagnostic, nil); err != nil {
t.Fatal(err)
}
got, err := s.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if got.FailureKind != test.expectedKind || got.FailureReason != test.diagnostic {
t.Fatalf("classification: kind=%q reason=%q, want %q/%q", got.FailureKind, got.FailureReason, test.expectedKind, test.diagnostic)
}
ns, err := s.RunNotifications(ctx, id)
if err != nil {
t.Fatal(err)
}
if (len(ns) != 0) != test.notify {
t.Fatalf("notifications=%+v, want notify=%v", ns, test.notify)
}
})
}
}
func TestWaitingNotificationStageAndWorkerShareLease(t *testing.T) {
ctx := context.Background()
s, id := notificationTransitionRun(t, filepath.Join(t.TempDir(), "lease.db"), "on")
+12 -3
View File
@@ -26,12 +26,12 @@ type RunNotification struct {
// enqueueRunTransitionNotification must share the state mutation's transaction.
// Read the committed-to-be state, not a runner's proposed outcome or identity.
func enqueueRunTransitionNotification(ctx context.Context, tx *sql.Tx, id int64) error {
var mode, status, name, stage, diagnostic, graphJSON string
var mode, status, name, stage, diagnostic, failureKind, graphJSON string
var sequence int
if err := tx.QueryRowContext(ctx, `SELECT r.notify_mode,r.status,p.name,r.current_stage,r.diagnostic,
if err := tx.QueryRowContext(ctx, `SELECT r.notify_mode,r.status,p.name,r.current_stage,r.diagnostic,r.failure_kind,
COALESCE((SELECT MAX(sequence) FROM run_steps WHERE run_id=r.id),0),v.graph_json
FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id
JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&mode, &status, &name, &stage, &diagnostic, &sequence, &graphJSON); err != nil {
JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&mode, &status, &name, &stage, &diagnostic, &failureKind, &sequence, &graphJSON); err != nil {
return err
}
if mode == "off" {
@@ -43,6 +43,15 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version
title = "Run needs your decision"
body = "waiting for a human decision"
case "failed", "interrupted", "succeeded":
if status == "failed" && failureKind == "expected" && mode != "on" {
settings, err := readNotificationSettings(ctx, tx)
if err != nil {
return err
}
if !settings.RunFinished {
return nil
}
}
// Successful runs notify only for runs marked "on", unless the operator
// opted into every run end via run_finished, read in this transaction.
if status == "succeeded" && mode != "on" {
+2 -2
View File
@@ -20,7 +20,7 @@ const runFrom = `FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id`
const runStamps = `strftime('%Y-%m-%dT%H:%M:%SZ',r.created_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',r.finished_at),'')`
const runSelect = `SELECT r.id,r.pipeline_id,p.name,r.version,v.content_hash,r.status,r.outcome,r.current_stage,
` + runStamps + `,r.diagnostic,
` + runStamps + `,r.diagnostic,r.failure_kind,r.failure_reason,
CASE WHEN r.status='succeeded' THEN r.output_json ELSE COALESCE((SELECT output_json FROM run_steps WHERE run_id=r.id AND status='completed' ORDER BY sequence DESC LIMIT 1),'{}') END,
(SELECT COUNT(*) FROM run_steps WHERE run_id=r.id AND status='completed'),r.workspace,r.title,r.model,r.stage_models,r.notify_mode,r.cancel_requested,r.cleanup_unconfirmed,r.output_format,
CASE WHEN r.status='waiting' THEN COALESCE((SELECT sequence FROM session_export_gates WHERE run_id=r.id),0) ELSE 0 END,
@@ -32,7 +32,7 @@ MAX(r.size_bytes,0)
func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error {
var output, stageModels string
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil {
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil {
return err
}
if stageModels != "" && stageModels != "{}" {
+41 -3
View File
@@ -385,12 +385,15 @@ func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagno
return err
}
defer tx.Rollback()
failureKind, failureReason := classifyRunFailure(ctx, tx, id, status, diagnostic)
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET
status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE ? END,
outcome=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END,
output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, string(data), id)); err != nil {
diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END,
failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, string(data), id)); err != nil {
return err
}
if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil {
@@ -404,6 +407,41 @@ AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_a
return tx.Commit()
}
// classifyRunFailure uses the durable terminal visit rather than an error string
// alone. A completed visit that deliberately routes to #failure is expected;
// runtime failures, limits and interruptions require operator attention.
func classifyRunFailure(ctx context.Context, tx *sql.Tx, id int64, status, diagnostic string) (string, string) {
if status == "interrupted" {
return "unexpected", diagnostic
}
if status != "failed" {
return "", ""
}
var sequence int64
var stepStatus, outcome, target, stepDiagnostic string
err := tx.QueryRowContext(ctx, `SELECT sequence,status,outcome,target,diagnostic FROM run_steps WHERE run_id=? ORDER BY sequence DESC LIMIT 1`, id).Scan(&sequence, &stepStatus, &outcome, &target, &stepDiagnostic)
reason := strings.TrimSpace(diagnostic)
if reason == "" {
reason = strings.TrimSpace(stepDiagnostic)
}
if err == nil && target == protocol.FailureEnd && stepStatus == "completed" && outcome != "error" && reason != "" && !stepLimitReached(ctx, tx, id, sequence) {
return "expected", reason
}
return "unexpected", reason
}
// stepLimitReached reports whether the runner, not the stage, routed the visit
// to #failure because the stage exhausted its visit limit (the recorded control
// evidence), so a stage reason that merely mentions stopping stays expected.
func stepLimitReached(ctx context.Context, tx *sql.Tx, id, sequence int64) bool {
var data string
if tx.QueryRowContext(ctx, `SELECT evidence_json FROM step_control WHERE run_id=? AND sequence=?`, id, sequence).Scan(&data) != nil {
return false
}
var control protocol.ControlEvidence
return json.Unmarshal([]byte(data), &control) == nil && control.LimitReached
}
// SetRunEnvironment records the directory environment a run resolved (names
// and files only). A resumed run records its latest resolution.
func (s *Store) SetRunEnvironment(ctx context.Context, id int64, environment *protocol.RunEnvironment) error {
+7 -2
View File
@@ -79,6 +79,11 @@ CREATE TABLE IF NOT EXISTS retry_checkpoints (
if err := s.addColumnIfMissing("pipeline_runs", "environment_json", "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
for _, column := range []string{"failure_kind", "failure_reason"} {
if err := s.addColumnIfMissing("pipeline_runs", column, "TEXT NOT NULL DEFAULT ''"); err != nil {
return err
}
}
if err := s.dropResourceSchema(); err != nil {
return err
}
@@ -239,11 +244,11 @@ func (s *Store) RecoverRunsKeeping(ctx context.Context, keep map[int64]bool, rea
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET diagnostic=? WHERE run_id=? AND status='interrupted' AND sequence=(SELECT MAX(sequence) FROM run_steps WHERE run_id=?)", "Server restarted; "+reason, id, id); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", id); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil {
return err
}
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil {
return err
}
// An export checkpoint is a paused handoff, not an interrupted model call.
+168
View File
@@ -0,0 +1,168 @@
package pipeline
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/skills"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
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);
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));`)
return err
}
// skillImports serialises imports in this server process, so the
// deduplication check and the next-version allocation below see every
// earlier import's committed version and never hand out the same number.
var skillImports sync.Mutex
func (s *Store) ImportSkill(ctx context.Context, name, description, digest, source string, files []protocol.SkillFile) (protocol.SkillVersion, error) {
skillImports.Lock()
defer skillImports.Unlock()
if err := skills.ValidateName(name); err != nil {
return protocol.SkillVersion{}, err
}
if digest == "" || len(files) == 0 {
return protocol.SkillVersion{}, fmt.Errorf("invalid skill bundle")
}
if len(files) > skills.MaxFiles {
return protocol.SkillVersion{}, fmt.Errorf("skill has more than %d files", skills.MaxFiles)
}
ordered := append([]protocol.SkillFile(nil), files...)
sort.Slice(ordered, func(i, j int) bool { return ordered[i].Path < ordered[j].Path })
h := sha256.New()
total := 0
for _, f := range ordered {
if f.Path == "" || strings.HasPrefix(f.Path, "/") || filepath.Clean(f.Path) != f.Path || strings.HasPrefix(filepath.ToSlash(f.Path), "../") || strings.Contains(f.Path, "\\") {
return protocol.SkillVersion{}, fmt.Errorf("invalid skill file path: %s", f.Path)
}
if len(f.Bytes) > skills.MaxFileBytes {
return protocol.SkillVersion{}, fmt.Errorf("file %s exceeds %d bytes", f.Path, skills.MaxFileBytes)
}
total += len(f.Bytes)
fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes))
h.Write(f.Bytes)
}
if total > skills.MaxTotalBytes || hex.EncodeToString(h.Sum(nil)) != digest {
return protocol.SkillVersion{}, fmt.Errorf("skill digest or size limit is invalid")
}
var existing protocol.SkillVersion
err := s.db.QueryRowContext(ctx, `SELECT version, source_path, imported_at FROM skill_versions WHERE name=? AND digest=?`, name, digest).Scan(&existing.Version, &existing.SourcePath, &existing.ImportedAt)
if err == nil {
existing.SkillSummary = protocol.SkillSummary{Name: name, Description: description, LatestVersion: existing.Version, Digest: digest, ImportedAt: existing.ImportedAt}
existing.SkillMD, _ = s.skillMD(name, existing.Version)
existing.Manifest, _ = s.skillManifest(ctx, name, existing.Version)
return existing, nil
}
if err != sql.ErrNoRows {
return existing, err
}
var next int
_ = s.db.QueryRowContext(ctx, `SELECT COALESCE(MAX(version),0)+1 FROM skill_versions WHERE name=?`, name).Scan(&next)
now := time.Now().UTC().Format(time.RFC3339)
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return existing, err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO skills(name,description,latest_version,digest,imported_at) VALUES(?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET description=excluded.description,latest_version=excluded.latest_version,digest=excluded.digest,imported_at=excluded.imported_at`, name, description, next, digest, now); err != nil {
tx.Rollback()
return existing, err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO skill_versions(name,version,digest,source_path,imported_at) VALUES(?,?,?,?,?)`, name, next, digest, source, now); err != nil {
tx.Rollback()
return existing, err
}
dir := filepath.Join(s.dir, "skills", name, fmt.Sprintf("v%d", next))
if err = os.MkdirAll(dir, 0700); err != nil {
tx.Rollback()
return existing, err
}
for _, f := range files {
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if err = os.MkdirAll(filepath.Dir(p), 0700); err != nil {
tx.Rollback()
return existing, err
}
if err = os.WriteFile(p, f.Bytes, 0600); err != nil {
tx.Rollback()
return existing, err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO skill_files(name,version,path,size) VALUES(?,?,?,?)`, name, next, f.Path, len(f.Bytes)); err != nil {
tx.Rollback()
return existing, err
}
}
if err = tx.Commit(); err != nil {
return existing, err
}
return s.GetSkill(ctx, name, next)
}
func (s *Store) ListSkills(ctx context.Context) ([]protocol.SkillSummary, error) {
rows, e := s.db.QueryContext(ctx, `SELECT name,description,latest_version,digest,imported_at FROM skills ORDER BY name`)
if e != nil {
return nil, e
}
defer rows.Close()
var out []protocol.SkillSummary
for rows.Next() {
var x protocol.SkillSummary
if e = rows.Scan(&x.Name, &x.Description, &x.LatestVersion, &x.Digest, &x.ImportedAt); e != nil {
return nil, e
}
out = append(out, x)
}
return out, rows.Err()
}
func (s *Store) GetSkill(ctx context.Context, name string, version int) (protocol.SkillVersion, error) {
var x protocol.SkillVersion
var desc string
if version == 0 {
if e := s.db.QueryRowContext(ctx, `SELECT description,latest_version FROM skills WHERE name=?`, name).Scan(&desc, &version); e != nil {
return x, e
}
} else if e := s.db.QueryRowContext(ctx, `SELECT description FROM skills WHERE name=?`, name).Scan(&desc); e != nil {
return x, e
}
if e := s.db.QueryRowContext(ctx, `SELECT digest,source_path,imported_at FROM skill_versions WHERE name=? AND version=?`, name, version).Scan(&x.Digest, &x.SourcePath, &x.ImportedAt); e != nil {
return x, e
}
x.Name = name
x.Description = desc
x.Version = version
x.LatestVersion = version
x.SkillMD, _ = s.skillMD(name, version)
x.Manifest, _ = s.skillManifest(ctx, name, version)
return x, nil
}
func (s *Store) skillMD(name string, v int) (string, error) {
b, e := os.ReadFile(filepath.Join(s.dir, "skills", name, fmt.Sprintf("v%d", v), "SKILL.md"))
return string(b), e
}
func (s *Store) skillManifest(ctx context.Context, name string, v int) ([]protocol.SkillFileMeta, error) {
rows, e := s.db.QueryContext(ctx, `SELECT path,size FROM skill_files WHERE name=? AND version=? ORDER BY path`, name, v)
if e != nil {
return nil, e
}
defer rows.Close()
var out []protocol.SkillFileMeta
for rows.Next() {
var x protocol.SkillFileMeta
if e = rows.Scan(&x.Path, &x.Size); e != nil {
return nil, e
}
out = append(out, x)
}
return out, rows.Err()
}
+98
View File
@@ -0,0 +1,98 @@
package pipeline
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"git.a-wan.net/alan/pipelines/internal/protocol"
"path/filepath"
"sync"
"testing"
)
func digestSkill(files []protocol.SkillFile) string {
h := sha256.New()
for _, f := range files {
fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes))
h.Write(f.Bytes)
}
return hex.EncodeToString(h.Sum(nil))
}
func TestSkillImportDeduplicatesAndVersions(t *testing.T) {
s, err := Open(filepath.Join(t.TempDir(), "pipelines.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte("---\nname: demo\ndescription: Demo\n---\n")}}
first, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/one", files)
if err != nil {
t.Fatal(err)
}
same, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/two", files)
if err != nil {
t.Fatal(err)
}
if same.Version != first.Version {
t.Fatalf("dedup version = %d, want %d", same.Version, first.Version)
}
files[0].Bytes = append(files[0].Bytes, '\n')
second, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/three", files)
if err != nil {
t.Fatal(err)
}
if second.Version != 2 {
t.Fatalf("new version = %d, want 2", second.Version)
}
}
func TestSkillImportRejectsUnsafeName(t *testing.T) {
s, err := Open(filepath.Join(t.TempDir(), "pipelines.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte("skill")}}
if _, err := s.ImportSkill(context.Background(), "../../outside", "", digestSkill(files), "/source", files); err == nil {
t.Fatal("expected unsafe skill name to be rejected")
}
}
func TestSkillImportConcurrentVersionsAreDistinct(t *testing.T) {
s, err := Open(filepath.Join(t.TempDir(), "pipelines.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
const n = 8
var wg sync.WaitGroup
versions := make([]int, n)
errs := make([]error, n)
for i := range n {
wg.Add(1)
go func() {
defer wg.Done()
files := []protocol.SkillFile{{Path: "SKILL.md", Bytes: []byte(fmt.Sprintf("---\nname: demo\ndescription: Demo %d\n---\n", i))}}
v, err := s.ImportSkill(context.Background(), "demo", "Demo", digestSkill(files), "/src", files)
versions[i], errs[i] = v.Version, err
}()
}
wg.Wait()
seen := map[int]bool{}
for i := range n {
if errs[i] != nil {
t.Fatalf("import %d: %v", i, errs[i])
}
if seen[versions[i]] {
t.Fatalf("version %d allocated twice: %v", versions[i], versions)
}
seen[versions[i]] = true
}
for v := 1; v <= n; v++ {
if !seen[v] {
t.Fatalf("versions = %v, want 1..%d", versions, n)
}
}
}
+4
View File
@@ -129,6 +129,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
db.Close()
return nil, err
}
if err := s.initSkills(); err != nil {
db.Close()
return nil, err
}
return s, nil
}
+12
View File
@@ -23,6 +23,12 @@ const (
PipelineArchived = "pipeline_archived"
UnarchivePipeline = "unarchive_pipeline"
PipelineUnarchived = "pipeline_unarchived"
ImportSkill = "import_skill"
SkillImported = "skill_imported"
ListSkills = "list_skills"
Skills = "skills"
ShowSkill = "show_skill"
Skill = "skill"
)
type Stage struct {
@@ -127,6 +133,9 @@ type PipelineSummary struct {
// are optional so older peers ignore them. See search.go for the per-type payloads
// and the ranking/kind/bound vocabulary.
type Message struct {
SkillFiles []SkillFile `json:"skill_files,omitempty"`
SkillSummaries []SkillSummary `json:"skill_summaries,omitempty"`
SkillVersion *SkillVersion `json:"skill_version,omitempty"`
Storage *StorageOverview `json:"storage,omitempty"`
StoragePolicy *StoragePolicy `json:"storage_policy,omitempty"`
StorageCleanup *StorageCleanupResult `json:"storage_cleanup,omitempty"`
@@ -154,6 +163,9 @@ type Message struct {
Error string `json:"error,omitempty"`
Warnings []string `json:"warnings,omitempty"` // non-blocking authoring lint for validate/submit
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Digest string `json:"digest,omitempty"`
SourcePath string `json:"source_path,omitempty"`
Source string `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Version int `json:"version,omitempty"`
+2
View File
@@ -54,6 +54,8 @@ type RunEventFrame struct {
CompletedSteps int `json:"completed_steps,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
FinishedAt string `json:"finished_at,omitempty"`
FailureKind string `json:"failure_kind,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
// Artifacts is the number of files recorded for the referenced step, so a
// client can surface artifact capture without reading the step.
Artifacts int `json:"artifacts,omitempty"`
+2
View File
@@ -187,6 +187,8 @@ type RunSummary struct {
CreatedAt string `json:"created_at"`
FinishedAt string `json:"finished_at"`
Diagnostic string `json:"diagnostic"`
FailureKind string `json:"failure_kind,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
ResultPreview string `json:"result_preview,omitempty"`
CompletedSteps int `json:"completed_steps"`
// Model and StageModels are the launch-time overrides this run records so it
+24
View File
@@ -0,0 +1,24 @@
package protocol
type SkillFile struct {
Path string `json:"path"`
Bytes []byte `json:"bytes"`
}
type SkillSummary struct {
Name string `json:"name"`
Description string `json:"description"`
LatestVersion int `json:"latest_version"`
Digest string `json:"digest"`
ImportedAt string `json:"imported_at"`
}
type SkillVersion struct {
SkillSummary
Version int `json:"version"`
SourcePath string `json:"source_path"`
Manifest []SkillFileMeta `json:"manifest"`
SkillMD string `json:"skill_md"`
}
type SkillFileMeta struct {
Path string `json:"path"`
Size int64 `json:"size"`
}
+11
View File
@@ -207,6 +207,9 @@ func (r *runner) notifyTerminalStep(id int64, status string) {
if err != nil || len(detail.Steps) == 0 {
return
}
if status == "failed" && detail.FailureKind == "expected" {
return
}
step := detail.Steps[len(detail.Steps)-1]
stepStatus, _, _, terminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic)
if !terminal || stepStatus != status {
@@ -375,6 +378,14 @@ func (r *runner) notifyRun(id int64, name, status string, sequence int, currentS
if event == "" {
return
}
if status == "failed" {
if detail, err := r.store.GetRun(r.ctx, id); err == nil && detail.FailureKind == "expected" {
settings, settingsErr := r.store.NotificationSettings(r.ctx)
if settingsErr != nil || (r.notifyMode(id) != "on" && !settings.RunFinished) {
return
}
}
}
// Failed or interrupted runs always notify; successful runs notify only when
// marked "on" or when the operator opted into every run end (run_finished).
if event == "succeeded" || (event != protocol.NotifyWaiting && event != "failed" && event != "interrupted") {
+12 -8
View File
@@ -158,13 +158,14 @@ func TestTerminalNotificationRecipe(t *testing.T) {
for index, test := range []struct {
name, stage, outcome, status string
executionError, deliveryError bool
notify bool
}{
{"success", "report", "success", "succeeded", false, false},
{"research blocked", "research", "blocked", "failed", false, false},
{"research execution error", "research", "error", "failed", true, false},
{"report blocked", "report", "blocked", "failed", false, false},
{"report execution error", "report", "error", "failed", true, false},
{"delivery error preserves success", "report", "success", "succeeded", false, true},
{"success", "report", "success", "succeeded", false, false, true},
{"research blocked", "research", "blocked", "failed", false, false, false},
{"research execution error", "research", "error", "failed", true, false, true},
{"report blocked", "report", "blocked", "failed", false, false, false},
{"report execution error", "report", "error", "failed", true, false, true},
{"delivery error preserves success", "report", "success", "succeeded", false, true, true},
} {
t.Run(test.name, func(t *testing.T) {
deliveryFailure.Store(test.deliveryError)
@@ -187,13 +188,16 @@ func TestTerminalNotificationRecipe(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if detail.Status != test.status || calls.Load()-before != 1 {
if detail.Status != test.status || (calls.Load()-before == 1) != test.notify {
t.Fatal("wrong verdict or duplicate/missing terminal alert", detail.Status, calls.Load()-before)
}
last := detail.Steps[len(detail.Steps)-1]
if last.Stage != test.stage || len(last.Notifications) != 1 {
if last.Stage != test.stage || (len(last.Notifications) == 1) != test.notify {
t.Fatal("notification not retained on terminal stage", last)
}
if !test.notify {
return
}
for _, step := range detail.Steps[:len(detail.Steps)-1] {
if len(step.Notifications) != 0 {
t.Fatal("intermediate success alerted", step)
+2
View File
@@ -568,6 +568,8 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner
CompletedSteps: summary.CompletedSteps,
CreatedAt: summary.CreatedAt,
FinishedAt: summary.FinishedAt,
FailureKind: summary.FailureKind,
FailureReason: summary.FailureReason,
CancelRequested: summary.CancelRequested,
CleanupUnconfirmed: summary.CleanupUnconfirmed,
ExportPendingSequence: summary.ExportPendingSequence,
+2
View File
@@ -1496,6 +1496,8 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
CurrentStage: currentStage,
CompletedSteps: completed,
FinishedAt: detail.FinishedAt,
FailureKind: detail.FailureKind,
FailureReason: detail.FailureReason,
SizeBytes: size,
}, true)
r.kickSizes()
+93
View File
@@ -0,0 +1,93 @@
package server
import (
"context"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/skills"
)
func TestSkillWebSocketHandlers(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "skills.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
handler := Handler(ctx, store)
srv := httptest.NewServer(handler)
defer srv.Close()
defer func() { cancel(); WaitRuns(handler) }()
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
defer conn.CloseNow()
var welcome protocol.Message
if err := wsjson.Read(ctx, conn, &welcome); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if err := writeSkillFixture(dir); err != nil {
t.Fatal(err)
}
bundle, err := skills.Validate(dir)
if err != nil {
t.Fatal(err)
}
files := make([]protocol.SkillFile, len(bundle.Files))
for i, file := range bundle.Files {
files[i] = protocol.SkillFile{Path: file.Path, Bytes: file.Bytes}
}
request := protocol.Message{Type: protocol.ImportSkill, ID: "import", Name: bundle.Name, Description: bundle.Description, Digest: bundle.Digest, SourcePath: dir, SkillFiles: files}
response := skillRequest(t, ctx, conn, request)
if response.Type != protocol.SkillImported || response.SkillVersion == nil || response.SkillVersion.Version != 1 {
t.Fatalf("import response = %+v", response)
}
response = skillRequest(t, ctx, conn, protocol.Message{Type: protocol.ListSkills, ID: "list"})
if response.Type != protocol.Skills || len(response.SkillSummaries) != 1 || response.SkillSummaries[0].Name != bundle.Name {
t.Fatalf("list response = %+v", response)
}
response = skillRequest(t, ctx, conn, protocol.Message{Type: protocol.ShowSkill, ID: "show", Name: bundle.Name})
if response.Type != protocol.Skill || response.SkillVersion == nil || response.SkillVersion.SkillMD == "" {
t.Fatalf("show response = %+v", response)
}
response = skillRequest(t, ctx, conn, protocol.Message{Type: protocol.ImportSkill, ID: "bad", Name: bundle.Name, SourcePath: dir, Digest: bundle.Digest, SkillFiles: []protocol.SkillFile{{Path: "../escape", Bytes: []byte("x")}}})
if response.Type != protocol.Error || response.Error == "" {
t.Fatalf("invalid import response = %+v", response)
}
}
func skillRequest(t *testing.T, ctx context.Context, conn *websocket.Conn, request protocol.Message) protocol.Message {
t.Helper()
if err := wsjson.Write(ctx, conn, request); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.ID != request.ID {
t.Fatalf("response ID = %q, want %q", response.ID, request.ID)
}
return response
}
func writeSkillFixture(dir string) error {
return os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: websocket-skill\ndescription: Handler test\n---\n\nDo not execute this.\n"), 0600)
}
+39
View File
@@ -461,6 +461,45 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
} else {
response.Pipelines = items
}
} else if request.Type == protocol.ImportSkill && len(stores) > 0 {
response.Type = protocol.SkillImported
if len(request.SkillFiles) == 0 || request.Name == "" || request.SourcePath == "" {
response.Type = protocol.Error
response.Error = "skill import requires name, source path and files"
} else {
for _, f := range request.SkillFiles {
if f.Path == "" || strings.HasPrefix(f.Path, "/") || strings.Contains(f.Path, "..") {
response.Type = protocol.Error
response.Error = "invalid skill file path"
break
}
}
if response.Type != protocol.Error {
var skill protocol.SkillVersion
skill, err = stores[0].ImportSkill(ctx, request.Name, request.Description, request.Digest, request.SourcePath, request.SkillFiles)
response.SkillVersion = &skill
}
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
}
}
} else if request.Type == protocol.ListSkills && len(stores) > 0 {
response.Type = protocol.Skills
response.SkillSummaries, err = stores[0].ListSkills(ctx)
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
}
} else if request.Type == protocol.ShowSkill && len(stores) > 0 {
response.Type = protocol.Skill
var skill protocol.SkillVersion
skill, err = stores[0].GetSkill(ctx, request.Name, request.Version)
response.SkillVersion = &skill
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
}
} else if (request.Type == protocol.ArchivePipeline || request.Type == protocol.UnarchivePipeline) && len(stores) > 0 {
detail, err := archivePipeline(ctx, stores[0], request)
response.Detail = detail
+173
View File
@@ -0,0 +1,173 @@
// Package skills validates and fingerprints Claude/Codex/OpenCode/Pi skill bundles.
package skills
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
const (
MaxFiles = 200
MaxTotalBytes = 5 * 1024 * 1024
MaxFileBytes = 1024 * 1024
)
var slug = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
// ValidateName checks the server-facing skill name before it is used in a
// filesystem path.
func ValidateName(name string) error {
if !slug.MatchString(name) {
return fmt.Errorf("skill name must be a lowercase slug")
}
return nil
}
type File struct {
Path string
Bytes []byte
}
type Bundle struct {
Name, Description, Digest string
Files []File
TotalBytes int64
}
func Validate(root string) (Bundle, error) {
root, err := filepath.Abs(root)
if err != nil {
return Bundle{}, err
}
st, err := os.Lstat(root)
if err != nil {
return Bundle{}, err
}
if st.Mode()&os.ModeSymlink != 0 {
return Bundle{}, fmt.Errorf("symlinks are not allowed: %s", root)
}
if !st.IsDir() {
return Bundle{}, fmt.Errorf("skill path is not a directory")
}
var files []File
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
rel, e := filepath.Rel(root, path)
if e != nil {
return e
}
if rel == "." {
return nil
}
if d.Type()&os.ModeSymlink != 0 {
return fmt.Errorf("symlinks are not allowed: %s", rel)
}
if d.IsDir() {
if filepath.Dir(rel) == "." && rel != "references" && rel != "scripts" && rel != "assets" {
return fmt.Errorf("unsupported top-level directory: %s", rel)
}
return nil
}
clean := filepath.ToSlash(rel)
if filepath.Dir(rel) == "." && clean != "SKILL.md" {
return fmt.Errorf("unsupported top-level file: %s", clean)
}
if filepath.IsAbs(rel) || strings.HasPrefix(clean, "../") || clean == ".." {
return fmt.Errorf("invalid path: %s", rel)
}
if filepath.Base(rel) == "SKILL.md" && filepath.Dir(rel) != "." {
return fmt.Errorf("nested SKILL.md is not allowed: %s", rel)
}
if len(files) >= MaxFiles {
return fmt.Errorf("skill has more than %d files", MaxFiles)
}
info, e := d.Info()
if e != nil {
return e
}
if info.Size() > MaxFileBytes {
return fmt.Errorf("file %s exceeds %d bytes", clean, MaxFileBytes)
}
b, e := os.ReadFile(path)
if e != nil {
return e
}
if info.Mode()&0111 != 0 && !strings.HasPrefix(clean, "scripts/") {
return fmt.Errorf("executable outside scripts/: %s", clean)
}
files = append(files, File{Path: clean, Bytes: b})
return nil
})
if err != nil {
return Bundle{}, err
}
sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path })
var md []byte
for _, f := range files {
if f.Path == "SKILL.md" {
md = f.Bytes
break
}
}
if md == nil {
return Bundle{}, fmt.Errorf("skill must contain exactly one top-level SKILL.md")
}
name, desc, err := frontmatter(md)
if err != nil {
return Bundle{}, err
}
if err := ValidateName(name); err != nil {
return Bundle{}, fmt.Errorf("frontmatter name must be a lowercase slug")
}
var total int64
h := sha256.New()
for _, f := range files {
total += int64(len(f.Bytes))
fmt.Fprintf(h, "%s\x00%d\x00", f.Path, len(f.Bytes))
h.Write(f.Bytes)
}
if total > MaxTotalBytes {
return Bundle{}, fmt.Errorf("skill exceeds %d total bytes", MaxTotalBytes)
}
return Bundle{Name: name, Description: desc, Digest: hex.EncodeToString(h.Sum(nil)), Files: files, TotalBytes: total}, nil
}
func frontmatter(b []byte) (string, string, error) {
s := strings.ReplaceAll(string(b), "\r\n", "\n")
lines := strings.Split(s, "\n")
if len(lines) < 3 || strings.TrimSpace(lines[0]) != "---" {
return "", "", fmt.Errorf("SKILL.md must begin with YAML frontmatter")
}
name, desc := "", ""
end := -1
for i := 1; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) == "---" {
end = i
break
}
k, v, ok := strings.Cut(lines[i], ":")
if !ok {
continue
}
v = strings.TrimSpace(v)
v = strings.Trim(v, "\"'")
switch strings.TrimSpace(k) {
case "name":
name = v
case "description":
desc = v
}
}
if end < 0 || name == "" || desc == "" {
return "", "", fmt.Errorf("SKILL.md frontmatter requires name and description")
}
return name, desc, nil
}
+56
View File
@@ -0,0 +1,56 @@
package skills
import (
"os"
"path/filepath"
"testing"
)
func TestValidateDigestStable(t *testing.T) {
for _, order := range [][]string{{"b.txt", "a.txt"}, {"a.txt", "b.txt"}} {
d := t.TempDir()
os.WriteFile(filepath.Join(d, "SKILL.md"), []byte("---\nname: demo-skill\ndescription: Demo\n---\n"), 0600)
os.Mkdir(filepath.Join(d, "references"), 0700)
for _, n := range order {
os.WriteFile(filepath.Join(d, "references", n), []byte(n), 0600)
}
b, e := Validate(d)
if e != nil {
t.Fatal(e)
}
if order[0] == "b.txt" {
t.Setenv("DIGEST", b.Digest)
} else if os.Getenv("DIGEST") != b.Digest {
t.Fatalf("digest changed")
}
}
}
func TestValidateRejectsNested(t *testing.T) {
d := t.TempDir()
os.WriteFile(filepath.Join(d, "SKILL.md"), []byte("---\nname: x\ndescription: y\n---"), 0600)
os.Mkdir(filepath.Join(d, "references"), 0700)
os.WriteFile(filepath.Join(d, "references", "SKILL.md"), []byte("x"), 0600)
if _, e := Validate(d); e == nil {
t.Fatal("expected nested rejection")
}
}
func TestValidateNameRejectsTraversal(t *testing.T) {
for _, name := range []string{"../outside", "../../outside", "Upper", "has space", ""} {
if err := ValidateName(name); err == nil {
t.Errorf("ValidateName(%q) accepted unsafe name", name)
}
}
}
func TestValidateRejectsSymlinkRoot(t *testing.T) {
target := t.TempDir()
os.WriteFile(filepath.Join(target, "SKILL.md"), []byte("---\nname: demo\ndescription: Demo\n---\n"), 0600)
link := filepath.Join(t.TempDir(), "skill-link")
if err := os.Symlink(target, link); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
if _, err := Validate(link); err == nil {
t.Fatal("expected symlink root rejection")
}
}