skill

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecidePublish added in v0.10.0

func DecidePublish(rep *scan.Report, o gate.OwnerState, floor float64, override bool) gate.Decision

DecidePublish is the one definition of "what does this scan report mean for this version" shared by every route that creates a version — publish and import alike. A version has no quality state yet by definition: the evaluation that could produce one runs against the bundle this call is creating, so q is always nil here. o carries the resolved ownership state; pass a zero OwnerState to skip the ownership dimension entirely (the CLI's local pre-scan does exactly that). floor and override are the resolved gate.Policy inputs; import has no interactive override and must always pass false.

func NewChiAPI

func NewChiAPI() (chi.Router, huma.API)

NewChiAPI creates a new Chi router and Huma API suitable for production and tests. Returns both so callers can mount additional middleware on the router or serve it directly.

func ParseFrontmatter

func ParseFrontmatter(content string) (map[string]interface{}, string, error)

ParseFrontmatter parses YAML frontmatter from content delimited by "---\n" blocks. It returns the frontmatter as a map, the body (content after the closing delimiter), and any error.

If no frontmatter is found (content does not start with "---\n"), it returns nil, content, nil.

func RegisterReviewQueueRoutes added in v0.10.0

func RegisterReviewQueueRoutes(api huma.API, store *Store, owners OwnerResolver)

RegisterReviewQueueRoutes wires the cross-skill held-version listing. Reading is open to any authenticated member: a hold that only its approver can see is a hold nobody discovers. Acting on one stays owner/admin, on POST /api/skills/{name}/versions/{version}/review.

owners hydrates RulePattern/Owners/Unowned per row, same as the publish and per-version review handlers. A nil owners leaves every row's ownership fields zero-valued, matching how a nil RouteOptions.Ownership behaves elsewhere — no resolver means ownership contributes nothing.

func RegisterRoutes

func RegisterRoutes(api huma.API, router chi.Router, store *Store, storage platform.Storage, opts RouteOptions)

RegisterRoutes wires up all skill-related HTTP endpoints onto the provided Huma API and Chi router. The router is needed for the two raw-response routes (download + scan) that stream bytes rather than returning JSON.

func Unpack

func Unpack(r io.Reader, destDir string) error

Unpack extracts a tar.gz archive from r into destDir. It rejects any archive entry whose resolved path would escape destDir (path traversal prevention), rejects symlinks and hardlinks, and enforces a 50 MB total extraction size limit.

Types

type Alias

type Alias struct {
	Alias     string    `json:"alias"`
	Canonical string    `json:"canonical"`
	CreatedAt time.Time `json:"created_at"`
}

type EvalJobRequest added in v0.10.0

type EvalJobRequest struct {
	SkillID     string
	SkillName   string
	Version     int
	SuiteRef    string
	Tier        string
	RequestedBy string
}

EvalJobRequest is what publish needs to enqueue an evaluation. It mirrors the fields of evalqueue.Job that publish sets, but is declared in this package rather than imported: internal/evalqueue imports internal/skill (for route wiring), so importing evalqueue back here would cycle. Callers adapt a real evalqueue.Executor to QueueSubmitter (see internal/server).

type Executor added in v0.10.0

type Executor interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}

Executor is the subset of *pgxpool.Pool that a gate transition needs. Declared here rather than reused from internal/quality to avoid a cycle.

type FileChange added in v0.10.0

type FileChange struct {
	Path   string `json:"path"`
	Status string `json:"status"` // "added", "removed", or "modified"
}

FileChange describes how a single file differs between the version being diffed and the currently-served baseline.

type FileEntry

type FileEntry struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
}

FileEntry describes a single file within a skill archive.

func Pack

func Pack(dir string) ([]byte, string, []FileEntry, error)

Pack creates a tar.gz archive of the directory at dir. It returns the archive bytes, a sha256 hex checksum, a file manifest, and any error encountered. Pack returns an error if SKILL.md is not present in dir.

type HeldVersion added in v0.10.0

type HeldVersion struct {
	SkillName    string          `json:"skill_name"`
	Version      int             `json:"version"`
	GateState    string          `json:"gate_state"`
	GateDecision json.RawMessage `json:"gate_decision,omitempty"`
	// ScanResult is included because the review screen shows the findings
	// beside the decision: the decision says what may clear the hold, and the
	// findings say what caused it. One request, both halves.
	ScanResult  json.RawMessage `json:"scan_result,omitempty"`
	PublishedBy string          `json:"published_by,omitempty"`
	GatedAt     *time.Time      `json:"gated_at,omitempty"`
	CreatedAt   time.Time       `json:"created_at"`
	// HoldReasons is every reason the version was held for, in the order
	// recorded at publish time. Outstanding is the subset with no approval
	// row yet — these can differ once one reason clears but the version
	// stays held on another, which is the case the review screen most needs
	// to render honestly.
	HoldReasons []string `json:"hold_reasons"`
	Outstanding []string `json:"outstanding"`
	// RulePattern, Owners and Unowned are hydrated per row from the
	// OwnerResolver after the query runs — the query has no way to resolve
	// ownership itself.
	RulePattern string          `json:"rule_pattern,omitempty"`
	Owners      []gate.OwnerRef `json:"owners"`
	Unowned     bool            `json:"unowned"`
}

HeldVersion is one version the publish gate is holding, joined to the name of the skill it belongs to. A held version has a number and an archive but is not pointed at by skills.latest_version, so it is servable by nothing — this listing is the only place it is visible.

type ListOptions added in v0.7.0

type ListOptions struct {
	Limit   int
	Offset  int
	Author  string
	Tag     string
	License string
}

ListOptions holds optional filter parameters for List.

type OwnerResolver added in v0.10.0

type OwnerResolver interface {
	ResolveForPublish(ctx context.Context, skillName string, user *auth.User) (gate.OwnerState, error)
	ClaimOnFirstPublish(ctx context.Context, skillName string, user *auth.User) error
}

OwnerResolver is the subset of the ownership store publish needs. It is declared here rather than imported because internal/ownership must stay free of internal/skill and the concrete wiring lives in internal/server — the same shape as QueueSubmitter and SuiteLookup.

ResolveForPublish folds instance privilege into IsOwner: an instance owner or admin is an implicit owner of everything, which is what makes O5's "admins are the reviewers of record" fall out without a special case.

type QualityEvidence added in v0.10.0

type QualityEvidence struct {
	Verified                 bool
	PanelComplete            bool
	Headline                 float64
	CriticalForbidViolations int
	// SuiteDerived: a machine-derived suite grades the skill against its own
	// claims and cannot clear a scan hold.
	SuiteDerived bool
}

QualityEvidence is the subset of quality.Record the gate depends on. Declared here to avoid a cycle with internal/quality.

type QueueSubmitter added in v0.10.0

type QueueSubmitter interface {
	Submit(ctx context.Context, job EvalJobRequest) (string, error)
}

QueueSubmitter is the subset of evalqueue.Executor that publish needs.

type Releaser added in v0.10.0

type Releaser struct {
	// contains filtered or unexported fields
}

Releaser re-runs the publish decision for a held version once a quality record exists.

func NewReleaser added in v0.10.0

func NewReleaser(store *Store) *Releaser

NewReleaser builds a Releaser over store.

func (*Releaser) Reconsider added in v0.10.0

func (r *Releaser) Reconsider(
	ctx context.Context,
	e Executor,
	skillName string,
	version int,
	rec QualityEvidence,
	floor float64,
) (gate.Decision, bool, error)

Reconsider re-decides one held version. A non-held version is a no-op.

type RouteOptions added in v0.10.0

type RouteOptions struct {
	// External is the opt-in external scanner (Phase 2); nil disables it.
	External *scan.ExternalScanner
	// Queue, when set together with Suites, lets publish enqueue an
	// evaluation for a skill that has a registered suite. A queue outage
	// must never fail a publish — see the enqueue step below.
	Queue QueueSubmitter
	// Suites looks up the latest registered eval suite for a skill by name.
	Suites SuiteLookup
	// QualityFloor is the minimum headline quality score a verified
	// evaluation must reach to clear a held version. It comes from
	// platform.Config.QualityFloor; the zero value means any verified,
	// complete, contract-clean report clears.
	QualityFloor float64
	// Ownership resolves and claims skill ownership for publish. A nil
	// resolver leaves the zero gate.OwnerState, which contributes nothing —
	// that is what keeps every test harness and the CLI's local pre-scan on
	// the pre-ownership behaviour.
	Ownership OwnerResolver
}

RouteOptions carries the optional collaborators RegisterRoutes wires into the publish (and related) handlers. Each is independently optional (nil disables the behavior it powers) so a caller — including tests — can opt into only what it needs.

type Skill

type Skill struct {
	ID             string          `json:"id"`
	Name           string          `json:"name"`
	DisplayName    string          `json:"display_name,omitempty"`
	Description    string          `json:"description"`
	Content        string          `json:"content,omitempty"`
	LatestVersion  int             `json:"latest_version"`
	Frontmatter    json.RawMessage `json:"frontmatter"`
	Author         string          `json:"author"`
	License        string          `json:"license"`
	Compatibility  string          `json:"compatibility"`
	Tags           []string        `json:"tags"`
	SpecCompliance string          `json:"spec_compliance"`
	CreatedAt      time.Time       `json:"created_at"`
	UpdatedAt      time.Time       `json:"updated_at"`
	ReviewedAt     *time.Time      `json:"reviewed_at"`
	ReviewedBy     string          `json:"reviewed_by"`
}

Skill represents a skill entry in the registry.

type SpecValidation added in v0.7.0

type SpecValidation struct {
	Compliance  string
	Author      string
	License     string
	Compat      string
	Tags        []string
	DisplayName string
	Warnings    []string
}

SpecValidation holds the result of validating a skill's frontmatter against the Agent Skills spec format.

func ValidateSpec added in v0.7.0

func ValidateSpec(fm map[string]interface{}, skillName string) *SpecValidation

ValidateSpec extracts spec-defined metadata from parsed frontmatter and computes a compliance level ("full", "partial", or "none").

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store handles Postgres persistence for skills and their versions.

func NewStore

func NewStore(pool *pgxpool.Pool) *Store

NewStore constructs a Store backed by the given connection pool.

func (*Store) ApproveReason added in v0.10.0

func (s *Store) ApproveReason(
	ctx context.Context,
	e Executor,
	name string,
	version int,
	reason string,
	actorID *string,
	actorEmail, note string,
) (bool, error)

ApproveReason records an approval for one hold reason and releases the version if that was the last one outstanding. It reports whether the version was released.

actorID is nil for an automated release — the verified-evaluation path — so "released by a score" and "released by a person" stay distinguishable forever. actorEmail is always written: it is an audit snapshot that survives the user being deleted.

It writes through e so a caller can compose the release with whatever justified it in one transaction. Report ingestion depends on that.

func (*Store) BulkSetReview

func (s *Store) BulkSetReview(ctx context.Context, names []string, reviewedBy string) (int, error)

BulkSetReview marks multiple skills as reviewed in a single UPDATE. Returns the number of rows actually updated.

func (*Store) ClearReview

func (s *Store) ClearReview(ctx context.Context, name string) error

ClearReview removes the review mark from a skill.

func (*Store) Create

func (s *Store) Create(ctx context.Context, name, displayName, description, content string, frontmatter json.RawMessage) (*Skill, error)

Create inserts a new skill row and returns the created record.

func (*Store) CreateAlias

func (s *Store) CreateAlias(ctx context.Context, alias, canonical string) error

func (*Store) CreateVersion

func (s *Store) CreateVersion(
	ctx context.Context,
	skillID, archivePath, checksum, changelog string,
	description, content string,
	frontmatter json.RawMessage,
	manifest []FileEntry,
	scanResult json.RawMessage,
	publishedBy string,
	decision gate.Decision,
) (*Version, error)

CreateVersion inserts a new skill_versions row, updates the parent skill's description/content/frontmatter, and advances skills.latest_version to the new version only when the gate decision releases it — all within a single transaction. A held version exists and is stored, but is not served.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, name string) error

Delete removes a skill (and its versions via CASCADE) by name.

func (*Store) DeleteAlias

func (s *Store) DeleteAlias(ctx context.Context, alias string) error

func (*Store) DiffAgainstServed added in v0.10.0

func (s *Store) DiffAgainstServed(ctx context.Context, name string, version int) (*VersionDiff, error)

DiffAgainstServed compares the given version of a skill against the version currently served (skills.latest_version). Returns nil, nil if the skill or the target version does not exist, matching GetByName/GetVersion.

When the skill has no served version yet (LatestVersion == 0 — this is the first version ever created for it), Against is 0, SkillMD is empty, and every file in the target version's manifest is reported as "added": there is no baseline to render a text diff against, and rendering one against an empty phantom version would be misleading, not just unhelpful.

func (*Store) GetByName

func (s *Store) GetByName(ctx context.Context, name string) (*Skill, error)

GetByName retrieves a skill by its unique name. Returns nil, nil when not found.

func (*Store) GetVersion

func (s *Store) GetVersion(ctx context.Context, skillName string, version int) (*Version, error)

GetVersion retrieves a specific version of a skill. Returns nil, nil if not found.

func (*Store) List

func (s *Store) List(ctx context.Context, opts ListOptions) ([]Skill, int, error)

List returns a paginated slice of skills along with the total row count. Filters are applied when the corresponding ListOptions fields are non-empty.

func (*Store) ListAliases

func (s *Store) ListAliases(ctx context.Context, canonical string) ([]Alias, error)

func (*Store) ListHeldVersions added in v0.10.0

func (s *Store) ListHeldVersions(ctx context.Context) ([]HeldVersion, error)

ListHeldVersions returns every version awaiting review, newest first. A SQL NULL in gate_decision or scan_result (neither of which is expected in practice, since CreateVersion always marshals a decision and a report) is scanned into a nil byte slice and wrapped as an empty json.RawMessage rather than erroring the whole listing — one row's missing detail must not hide every other hold.

func (*Store) ListVersions

func (s *Store) ListVersions(ctx context.Context, skillName string) ([]Version, error)

ListVersions returns all versions for a skill ordered by version DESC.

func (*Store) Merge

func (s *Store) Merge(ctx context.Context, sourceName, targetName string) (*Skill, error)

func (*Store) OutstandingReasons added in v0.10.0

func (s *Store) OutstandingReasons(ctx context.Context, name string, version int) ([]string, error)

OutstandingReasons returns the hold reasons on a version that have no approval row yet, in the order they were recorded.

func (*Store) Pool added in v0.10.0

func (s *Store) Pool() *pgxpool.Pool

Pool returns the underlying connection pool.

func (*Store) RejectReason added in v0.10.0

func (s *Store) RejectReason(
	ctx context.Context,
	name string,
	version int,
	reason, actorEmail, note string,
) error

RejectReason records a rejection for one reason and marks the version terminal. Rejecting any single reason rejects the version: there is no state in which a version is partly refused.

func (*Store) RejectVersion added in v0.10.0

func (s *Store) RejectVersion(ctx context.Context, name string, version int, by, note string) error

RejectVersion marks a held version terminal.

func (*Store) ReleaseVersion added in v0.10.0

func (s *Store) ReleaseVersion(ctx context.Context, e Executor, name string, version int, by, note string) error

ReleaseVersion moves a version to released. Uses the caller's Executor so ingestion can compose it with the quality upsert in one transaction. Re-releasing is a no-op, not an error.

func (*Store) ResolveAlias

func (s *Store) ResolveAlias(ctx context.Context, name string) (string, error)

func (*Store) Search

func (s *Store) Search(ctx context.Context, query string, limit int) ([]Skill, error)

Search returns skills matching the given query using a combination of Postgres full-text search (websearch_to_tsquery + ts_rank on search_vector) and pg_trgm fuzzy name matching (similarity()). Results are returned where either FTS matches OR name similarity exceeds 0.2, ordered by FTS rank then trigram rank. Limit caps the number of returned results.

func (*Store) SetReview

func (s *Store) SetReview(ctx context.Context, name, reviewedBy string) error

SetReview marks a skill as reviewed by the given reviewer.

func (*Store) UpdateSpecFields added in v0.7.0

func (s *Store) UpdateSpecFields(ctx context.Context, name, author, license, compat, compliance, displayName string, tags []string) error

UpdateSpecFields updates the spec-derived metadata columns on a skill row.

type SuiteLookup added in v0.10.0

type SuiteLookup interface {
	LatestForSkill(ctx context.Context, skillName string) (*SuiteRecord, error)
}

SuiteLookup is the subset of evalsuite.Registry that publish needs. It mirrors LatestForSkill's (nil, nil) contract: no error, nil record means no suite is registered for the skill.

type SuiteRecord added in v0.10.0

type SuiteRecord struct {
	Ref string
}

SuiteRecord is the subset of evalsuite.Record that publish needs to build an EvalJobRequest.

type Version

type Version struct {
	ID           string          `json:"id"`
	SkillID      string          `json:"skill_id"`
	Version      int             `json:"version"`
	ArchivePath  string          `json:"-"`
	Checksum     string          `json:"checksum"`
	Changelog    string          `json:"changelog"`
	Frontmatter  json.RawMessage `json:"frontmatter"`
	FileManifest []FileEntry     `json:"file_manifest"`

	// Description and Content are the rendered prose this version would
	// serve. They are carried on the version, not only on the skill row,
	// because a held version writes nothing to the skill row: releasing it
	// later has to get the prose from somewhere, and re-reading the archive
	// to recover text the database already saw would be the wrong place.
	//
	// Both are json:"-" on purpose. The wire shape of a version is unchanged,
	// and a version endpoint is not a second way to read a held version's
	// body — the gate withholds exactly that.
	Description string          `json:"-"`
	Content     string          `json:"-"`
	ScanResult  json.RawMessage `json:"scan_result,omitempty"`
	PublishedBy string          `json:"published_by"`
	CreatedAt   time.Time       `json:"created_at"`

	// GateState is one of "released", "needs_review", "rejected". Only a
	// released version is pointed at by skills.latest_version.
	GateState    string          `json:"gate_state"`
	GateDecision json.RawMessage `json:"gate_decision,omitempty"`
	GatedBy      string          `json:"gated_by,omitempty"`
	GatedAt      *time.Time      `json:"gated_at,omitempty"`
	GateNote     string          `json:"gate_note,omitempty"`

	// HoldReasons are the reason kinds still standing between this version
	// and release. Empty on a released or rejected version.
	HoldReasons []string `json:"hold_reasons"`
}

Version represents a specific published version of a skill.

type VersionDiff added in v0.10.0

type VersionDiff struct {
	// Against is the served version number this diff was computed against.
	// 0 means there is no baseline — this is the skill's first version, so
	// there is nothing to diff against rather than an empty phantom one.
	Against int          `json:"against"`
	SkillMD string       `json:"skill_md"`
	Files   []FileChange `json:"files"`
}

VersionDiff is what a reviewer sees when deciding whether to approve a version held for review: what changed in SKILL.md, and which files were added, removed, or modified relative to the version currently being served.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL