Files
archie/internal/skill/skill.go
T
sam 170fe0250b fix: close the duplicate-work loop and the dead paths around it
Applies the four-reviewer pass over the forge/dashboard-actions work.
The through-line is that several capabilities were wired but inert, and
one of them could cost real work.

DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of
LinkBranch, which is sidebar linkage on Gitea and a no-op stub on
GitHub -- neither closes anything, and nothing else did either. So a
merged task left its issue open, labelled and assigned; the next poll
re-enqueued it, and once the dashboard's Clear removed the task row that
became a second implementation and a second PR for work already merged.
reconcilePRs now closes the issue on merge, and a rejected task closes
its issue too. A PR closed without merging deliberately leaves the issue
open: that usually means "try again".

MAX RETRIES. Configured, defaulted and reported by /api/config, and
enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had
no callers, so the dashboard's retry incremented retry_count forever.
The retry action now retires a task to dead at the cap.

DEAD ON ARRIVAL. Tasks() never selected plan or source, so the
"Decision required" panel could not render and chat tasks -- whose issue
number is synthetic -- linked to forge issues that do not exist.

COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when
LinkBranch errored, so the pull request was never opened and the task
parked; a retry re-links the same branch, which Gitea answers with a
conflict, so every retry parked again. It is best-effort now.

INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing
else, so the timeline and activity stream never showed that a human had
intervened. They emit events now.

Also: store write failures answer 500 rather than 409; the dashboard
surfaces the server's actual reason instead of "409 Conflict"; action
buttons stop propagation (acting on a task no longer also expands it),
disable in flight, keep per-task errors instead of one shared string,
and confirm before rejecting.

Removed: the maybeRetryParked shim and markDead with their now-vacuous
tests, WaitingTasks (no consumers; its tests were rewritten to assert
the same routing through TaskByID), write-only Daemon.Runtime, and
dir/dirs response bloat from /api/skills. skillSource checked workDir
before sharedDir, mislabelling every shared skill when the two are equal.
DefaultRoots now dedupes roots differing only by a trailing separator.

The air build rule claiming to keep ui/dist current never ran -- it
required one file to satisfy include_dir and include_file together, and
ui/ is excluded from the walk. Deleted with the comment that promised it.
task test:ui joins task check and CI; it ran nowhere before, so the
dashboard suite could rot silently.

Docs corrected where they described behaviour that no longer exists:
parks no longer comment on the issue, state labels no longer drive
retries, and forgerpc's doc claimed four proxied methods while listing
three of five.
2026-08-05 03:54:25 +10:00

261 lines
7.7 KiB
Go

// Package skill parses agentskills.io SKILL.md files and discovers skills
// from the .agents/skills/ directory convention. It follows the same discovery
// pattern as internal/workflow/wfeval (missing directory is not an error).
package skill
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// Frontmatter is the parsed YAML frontmatter of a SKILL.md file.
type Frontmatter struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Version string `yaml:"version"`
Metadata struct {
Archie *struct {
Tools []string `yaml:"tools"`
Engine string `yaml:"engine"`
Plugins []string `yaml:"plugins,omitempty"`
Workflow string `yaml:"workflow,omitempty"`
} `yaml:"archie"`
} `yaml:"metadata"`
}
// CatalogEntry is a lightweight skill reference -- name + description
// only (~100 tokens). Loaded at daemon startup for skill discovery.
// The full body is loaded on activation via LoadBody. agentskills.io
// progressive disclosure Tier 1.
type CatalogEntry struct {
Name string
Description string
Workflow string // from metadata.archie.workflow -- which workflow this skill handles
Dir string // skill directory name
Root string // catalog root containing .agents/skills
}
// Catalog scans dir/.agents/skills/*/SKILL.md and returns catalog entries
// (Tier 1: name + description + workflow only). Only the frontmatter is
// parsed -- full bodies are not loaded. Missing directory or a file at the
// skills path returns nil (no error) -- the caller treats this as "no skills."
func Catalog(dir string) ([]CatalogEntry, error) {
skillsPath := filepath.Join(dir, skillsDir)
entries, err := os.ReadDir(skillsPath)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
// A file at .agents/skills (ENOTDIR) is not fatal -- treat as no skills.
// Same for permission errors and other non-fatal ReadDir failures.
return nil, nil //nolint:nilerr // documented above: a non-directory or unreadable skills path means no skills, not a fatal error
}
var names []string
for _, e := range entries {
if e.IsDir() {
names = append(names, e.Name())
}
}
sort.Strings(names)
var out []CatalogEntry
for _, name := range names {
skillPath := filepath.Join(skillsPath, name, "SKILL.md")
data, err := os.ReadFile(skillPath)
if err != nil {
continue
}
fm, _, err := Parse(data)
if err != nil || fm == nil {
continue
}
wf := ""
if fm.Metadata.Archie != nil {
wf = fm.Metadata.Archie.Workflow
}
out = append(out, CatalogEntry{
Name: fm.Name,
Description: fm.Description,
Workflow: wf,
Dir: name,
Root: dir,
})
}
return out, nil
}
// CatalogRoots merges catalogues from roots in precedence order. The first
// root containing a skill name wins, so callers can layer project skills over
// shared and user-global skills deterministically.
func CatalogRoots(roots ...string) ([]CatalogEntry, error) {
seen := make(map[string]struct{})
var out []CatalogEntry
for _, root := range roots {
entries, err := Catalog(root)
if err != nil {
return nil, err
}
for _, entry := range entries {
if _, ok := seen[entry.Name]; ok {
continue
}
seen[entry.Name] = struct{}{}
out = append(out, entry)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out, nil
}
// DefaultRoots returns the discovery roots for a daemon. Explicit project and
// shared roots take precedence over the user's global skills directory.
func DefaultRoots(workDir, sharedDir string) []string {
var roots []string
for _, root := range []string{workDir, sharedDir} {
if root != "" && !containsRoot(roots, root) {
roots = append(roots, root)
}
}
if home, err := os.UserHomeDir(); err == nil && home != "" && !containsRoot(roots, home) {
roots = append(roots, home)
}
return roots
}
// containsRoot compares roots after normalising trailing separators, so
// "/srv/skills" and "/srv/skills/" are one root rather than two -- otherwise
// the same directory is scanned twice and every skill in it appears twice.
func containsRoot(roots []string, root string) bool {
target := normaliseRoot(root)
for _, existing := range roots {
if normaliseRoot(existing) == target {
return true
}
}
return false
}
func normaliseRoot(root string) string {
if root == "" {
return root
}
return filepath.Clean(root)
}
// SkillForWorkflow returns the catalog entry whose Workflow field matches
// the given workflow name, or nil if no skill declares that workflow.
// Replaces hardcoded workflow→skill lookup tables.
func SkillForWorkflow(catalog []CatalogEntry, workflow string) *CatalogEntry {
for i := range catalog {
if catalog[i].Workflow == workflow {
return &catalog[i]
}
}
return nil
}
// Skill is a parsed SKILL.md file with its frontmatter, body, and any
// bundled Yaegi plugins found in the skill's plugins/ directory.
type Skill struct {
Frontmatter Frontmatter
Body string
Dir string // skill directory name (e.g. "tdd-bugfix")
Plugins []Plugin // bundled Yaegi plugins from plugins/*.go
}
const skillsDir = ".agents/skills"
// Parse extracts YAML frontmatter and body from SKILL.md content.
// The frontmatter is delimited by "---" lines. If no frontmatter is found,
// the entire content is returned as the body with a zero Frontmatter.
func Parse(src []byte) (*Frontmatter, string, error) {
text := string(src)
if !strings.HasPrefix(text, "---\n") {
return &Frontmatter{}, text, nil
}
// Find the closing "---".
end := strings.Index(text[4:], "\n---\n")
if end == -1 {
// Malformed: starts with --- but no closing delimiter.
return &Frontmatter{}, text, nil
}
end += 4 // adjust for the initial 4-byte skip
var fm Frontmatter
if err := yaml.Unmarshal([]byte(text[4:end]), &fm); err != nil {
return nil, "", fmt.Errorf("yaml frontmatter: %w", err)
}
body := strings.TrimSpace(text[end+5:]) // skip "\n---\n"
return &fm, body, nil
}
// Discover scans dir/.agents/skills/*/SKILL.md and returns a map of skill
// directory name to parsed Skill. Missing directory returns an empty map.
func Discover(dir string) (map[string]Skill, error) {
skillsPath := filepath.Join(dir, skillsDir)
entries, err := os.ReadDir(skillsPath)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("read skills dir %s: %w", skillsPath, err)
}
names := make([]string, 0, len(entries))
for _, e := range entries {
if e.IsDir() {
names = append(names, e.Name())
}
}
sort.Strings(names)
out := make(map[string]Skill, len(names))
for _, name := range names {
skillPath := filepath.Join(skillsPath, name, "SKILL.md")
data, err := os.ReadFile(skillPath)
if err != nil {
if os.IsNotExist(err) {
continue // directory exists but no SKILL.md
}
return nil, fmt.Errorf("read %s: %w", skillPath, err)
}
fm, body, err := Parse(data)
if err != nil {
return nil, fmt.Errorf("parse %s: %w", skillPath, err)
}
var pluginNames []string
if fm.Metadata.Archie != nil {
pluginNames = fm.Metadata.Archie.Plugins
}
plugins, err := LoadPlugins(dir, name, pluginNames)
if err != nil {
return nil, fmt.Errorf("plugins %s: %w", name, err)
}
out[name] = Skill{Frontmatter: *fm, Body: body, Dir: name, Plugins: plugins}
}
return out, nil
}
// LoadBody loads the raw SKILL.md body for a specific skill directory name.
// Returns "" if the skill directory or SKILL.md does not exist.
func LoadBody(dir, skillDirName string) string {
skillPath := filepath.Join(dir, skillsDir, skillDirName, "SKILL.md")
data, err := os.ReadFile(skillPath)
if err != nil {
return ""
}
_, body, err := Parse(data)
if err != nil {
return ""
}
return strings.TrimSpace(body)
}