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
@@ -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
}