From a9641276e131a8c8edb0783c1ccf0c06ef130e76 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 22 Jul 2026 02:23:20 +1000 Subject: [PATCH] feat: parse SKILL.md frontmatter, inject skill body into agent context Adds internal/skill package with YAML frontmatter parsing and skill discovery from .agents/skills/ (agentskills.io spec convention). - Frontmatter struct with name, description, version, metadata.archie - Parse() extracts YAML frontmatter delimited by --- markers - Discover() scans .agents/skills/*/SKILL.md (follows wfeval pattern) - LoadBody() for single-skill lazy loading Skills moved from .archie/skills/ to .agents/skills/ per the agentskills.io specification. Wiring: TaskContext.SkillBody field, lazy-loaded on first agent stage from worktree. When non-empty, prepended to Mission as "Follow these project-specific guidelines" context. Hardcoded Mission templates stay (task-specific formatting). Backward compatible: empty when no skill found. --- .../skills/ecosystem-node/SKILL.md | 0 .../skills/ecosystem-python/SKILL.md | 0 .../skills/go-quality-gate/SKILL.md | 0 .../skills/security-audit/SKILL.md | 0 .../skills/tdd-bugfix/SKILL.md | 0 .scratch/explore-chunkC-missions.md | 345 ++++++++++++++++++ .scratch/explore-chunkC-patterns.md | 230 ++++++++++++ .scratch/explore-chunkC-skills.md | 342 +++++++++++++++++ go.mod | 1 + go.sum | 4 + internal/agentexec/inprocess.go | 2 +- internal/skill/skill.go | 116 ++++++ internal/skill/skill_test.go | 164 +++++++++ internal/skillscript/yaegi.go | 2 +- internal/workflow/agent.go | 35 +- internal/workflow/workflow.go | 4 + 16 files changed, 1242 insertions(+), 3 deletions(-) rename {.archie => .agents}/skills/ecosystem-node/SKILL.md (100%) rename {.archie => .agents}/skills/ecosystem-python/SKILL.md (100%) rename {.archie => .agents}/skills/go-quality-gate/SKILL.md (100%) rename {.archie => .agents}/skills/security-audit/SKILL.md (100%) rename {.archie => .agents}/skills/tdd-bugfix/SKILL.md (100%) create mode 100644 .scratch/explore-chunkC-missions.md create mode 100644 .scratch/explore-chunkC-patterns.md create mode 100644 .scratch/explore-chunkC-skills.md create mode 100644 internal/skill/skill.go create mode 100644 internal/skill/skill_test.go diff --git a/.archie/skills/ecosystem-node/SKILL.md b/.agents/skills/ecosystem-node/SKILL.md similarity index 100% rename from .archie/skills/ecosystem-node/SKILL.md rename to .agents/skills/ecosystem-node/SKILL.md diff --git a/.archie/skills/ecosystem-python/SKILL.md b/.agents/skills/ecosystem-python/SKILL.md similarity index 100% rename from .archie/skills/ecosystem-python/SKILL.md rename to .agents/skills/ecosystem-python/SKILL.md diff --git a/.archie/skills/go-quality-gate/SKILL.md b/.agents/skills/go-quality-gate/SKILL.md similarity index 100% rename from .archie/skills/go-quality-gate/SKILL.md rename to .agents/skills/go-quality-gate/SKILL.md diff --git a/.archie/skills/security-audit/SKILL.md b/.agents/skills/security-audit/SKILL.md similarity index 100% rename from .archie/skills/security-audit/SKILL.md rename to .agents/skills/security-audit/SKILL.md diff --git a/.archie/skills/tdd-bugfix/SKILL.md b/.agents/skills/tdd-bugfix/SKILL.md similarity index 100% rename from .archie/skills/tdd-bugfix/SKILL.md rename to .agents/skills/tdd-bugfix/SKILL.md diff --git a/.scratch/explore-chunkC-missions.md b/.scratch/explore-chunkC-missions.md new file mode 100644 index 000000000..ebb4b1932 --- /dev/null +++ b/.scratch/explore-chunkC-missions.md @@ -0,0 +1,345 @@ +# missions + +Here is the complete report. + +--- + +## 1. The `AgentStage` Struct (from `/work/apps/archie-core/internal/workflow/agent.go`) + +**Lines 16-44.** The struct has 10 fields: + +| Field | Type | Line | Purpose | +|---|---|---|---| +| `Name` | `string` | 17 | Stage name (e.g. `"plan"`, `"build"`) | +| `Role` | `string` | 20 | Model role key, looked up in `cfg.Models[Role]` — falls back to `cfg.Models["builder"]` | +| `ReadOnly` | `bool` | 21 | When true, disables write protection entirely | +| `Mission` | `func(*TaskContext) string` | 23 | Produces the task statement string sent to the agent | +| `Gate` | `func(*TaskContext) agentexec.Gate` | 26 | Returns the quality gate; nil = ungated | +| `ExtraRules` | `string` | 28 | Literal string appended to the agent's system prompt | +| `MaxSteps` | `int` | 31 | Overrides budget when > 0 | +| `ProtectGlobs` | `func(*TaskContext) []string` | 37 | Globs blocked from writes, combined with repo-configured suffix protection | +| `CaptureTools` | `func(*TaskContext) []agentexec.CaptureTool` | 40 | Structured-output tools whose calls return as data | +| `OnResult` | `func(*TaskContext, agentexec.Result) error` | 43 | Consumes a passed result | + +--- + +## 2. How `AgentStage.Stage()` Calls `Mission` and Builds the `Request` (from `/work/apps/archie-core/internal/workflow/agent.go`) + +**Lines 47-148.** The `Stage()` method is the adapter that converts an `AgentStage` into the engine's `Stage` type. + +### The Request Construction (lines 94-109) + +```go +req := agentexec.Request{ + Version: agentexec.ProtocolVersion, // 1 + TaskID: tc.Task.ID, + Attempt: tc.Task.Attempt, + Stage: a.Name, + Model: modelRef, + Mission: a.Mission(tc), // <-- Mission called HERE + ExtraRules: a.ExtraRules, // <-- ExtraRules passed directly + ReadOnly: a.ReadOnly, + Budget: budget, + Gate: gate, + Preflight: preflight, + Protection: protection, + Notes: tc.Task.Notes, + CaptureTools: captureTools, +} +``` + +Key observations: + +- **`a.Mission(tc)` is called at line 100** to produce the `Mission` string. It receives the full `*TaskContext`, giving it access to `tc.Task.Title`, `tc.Task.Body`, `tc.Task.Plan`, `tc.Repo.FullName()`, `tc.Task.IssueNumber`, and any other field on `TaskContext`. +- **`a.ExtraRules` is used directly as a static string** (line 101). It is never processed, templated, or constructed — it is literally the `string` field set at AgentStage construction time. +- The result string from `a.Mission(tc)` is placed verbatim into `req.Mission`. It is not combined with ExtraRules there. The agent runtime receives both as separate fields and presumably concatenates or places them into the system prompt. + +### The agent run (line 110) + +```go +res, err := tc.Agent.Run(ctx, tc.Dir, req) +``` + +The `Request` is passed to the agent runner. The response is validated (lines 114-116), persisted notes are saved (lines 117-124), and if the result status is not `"passed"`, it returns an error (lines 136-142). Otherwise `a.OnResult` is called if set (lines 143-145). + +--- + +## 3. Every `AgentStage` in Implement, TDD, and Feasibility + +### 3a. Implement (`/work/apps/archie-core/internal/workflow/implement.go`) + +**Stage: `"plan"` (lines 43-73)** + +| Field | Value | +|---|---| +| `Name` | `"plan"` | +| `Role` | `"planner"` | +| `ReadOnly` | `true` | +| `MaxSteps` | `15` | +| `Mission` | Lines 48-64. Produces a `fmt.Sprintf` string: | +| | `"Produce a concrete implementation plan for this GitHub issue on the repository %s.\n"+prd+"\n\n# %s\n\n%s\n\n\nExplore the codebase with your read-only tools, then call finish with status \"passed\" and the plan as the summary: files to touch, the approach, acceptance criteria, and what tests should prove it. Keep the plan tightly scoped to the issue — call finish with status \"blocked\" if the issue is too vague or too large for one PR."` | +| | If `tc.Task.Plan != ""` (from a feasibility PRD), it prefixes: `"\n\n" + tc.Task.Plan + "\n\n"` | +| `Gate` | `nil` (no gate — read-only) | +| `ExtraRules` | `""` (empty) | +| `ProtectGlobs` | `nil` | +| `CaptureTools` | `nil` | +| `OnResult` | Line 65-72: Sets `tc.Task.Plan = res.Summary`, posts a comment to the issue | +| *Full mission example when no PRD exists:* `"Produce a concrete implementation plan for this GitHub issue on the repository owner/repo.\n\n\n# Issue Title\n\nIssue body text\n\n\nExplore the codebase..."` | + +**Stage: `"build"` (lines 75-98)** + +| Field | Value | +|---|---| +| `Name` | `"build"` | +| `Role` | `"builder"` | +| `ReadOnly` | `false` | +| `MaxSteps` | `0` (uses default budget) | +| `Mission` | Lines 83-93. Template: | +| | `"Implement this GitHub issue on the repository %s, following the plan below.\n\n\n# %s\n\n%s\n\n\n\n%s\n\n\nMake the smallest change that satisfies the issue and the plan's acceptance criteria. Do not run git — the orchestrator commits and pushes for you. When done, call finish with status \"passed\" and a summary written for the human who will review the pull request: what changed, why, and how it was verified."` | +| `Gate` | Line 78-79: `GateFromRepo(tc.Repo, tc.Cfg.Budgets)` — full quality gate | +| `ExtraRules` | Lines 81-82: `"Files matching the repository's protected suffixes (e.g. generated code) are write-blocked — edit their sources instead; the gate regenerates them."` | +| `ProtectGlobs` | `nil` | +| `CaptureTools` | `nil` | +| `OnResult` | Line 94-97: Sets `tc.BuildSummary = res.Summary` | + +### 3b. TDD (`/work/apps/archie-core/internal/workflow/tdd.go`) + +**Stage: `"analyse"` (lines 26-46)** + +| Field | Value | +|---|---| +| `Name` | `"analyse"` | +| `Role` | `"planner"` | +| `ReadOnly` | `true` | +| `MaxSteps` | `15` | +| `Mission` | Lines 31-41. Template: | +| | `"Analyse this bug report for the repository %s and determine the problem surface.\n\n\n# %s\n\n%s\n\n\nExplore the code read-only and call finish with status \"passed\" and a summary containing: the root cause (file and function), the exact conditions that trigger it, the expected vs actual behaviour, and which test cases would prove the bug. Call finish with status \"blocked\" if you cannot locate a plausible cause."` | +| `Gate` | `nil` | +| `ExtraRules` | `""` | +| `ProtectGlobs` | `nil` | +| `CaptureTools` | `nil` | +| `OnResult` | Lines 42-45: Sets `tc.Task.Plan = res.Summary` | + +**Stage: `"repro-tests"` (lines 48-69)** + +| Field | Value | +|---|---| +| `Name` | `"repro-tests"` | +| `Role` | `"builder"` | +| `ReadOnly` | `false` | +| `MaxSteps` | `0` | +| `Mission` | Lines 57-68. Template: | +| | `"Write tests that REPRODUCE this bug in the repository %s. Do NOT fix the bug yet.\n\n\n# %s\n\n%s\n\n\n\n%s\n\n\nAdd tests that pass once the bug is fixed but FAIL today because of it. The gate is inverted for this stage: it requires the full gate to pass EXCEPT %s which is required to FAIL. Do not touch non-test files. Call finish with status \"passed\" once the failing repro is in place, summarising which tests capture the bug."` | +| | Note: `%s` at the end is `testCommand(tc.Repo)` — the last gate command (e.g. `go test ./...`). | +| `Gate` | Lines 54-56: `tddReproGate(tc.Repo, tc.Cfg.Budgets)` — inverted gate where the last command expects failure | +| `ExtraRules` | `""` | +| `ProtectGlobs` | `nil` | +| `CaptureTools` | `nil` | +| `OnResult` | `nil` | + +**Stage: `"fix"` (lines 92-123)** + +| Field | Value | +|---|---| +| `Name` | `"fix"` | +| `Role` | `"builder"` | +| `ReadOnly` | `false` | +| `MaxSteps` | `0` | +| `Mission` | Lines 109-118. Template: | +| | `"Fix the bug in the repository %s. Failing repro tests are already committed; make them pass.\n\n\n# %s\n\n%s\n\n\n\n%s\n\n\nThe full quality gate (including 'go test ./...') must pass. Make the smallest fix that makes the repro tests pass without changing them. Call finish with status \"passed\" and a summary for the PR reviewer: root cause, the fix, and verification."` | +| `Gate` | Lines 95-97: `GateFromRepo(tc.Repo, tc.Cfg.Budgets)` — normal gate | +| `ExtraRules` | Lines 107-108: `"The repro tests written in the previous stage are the bug's specification. Test files are write-protected in this stage — make them pass by fixing the code they exercise."` | +| `ProtectGlobs` | Lines 100-105: `tc.Repo.ResolvedTestGlob()` — protects test files | +| `CaptureTools` | `nil` | +| `OnResult` | Lines 119-122: Sets `tc.BuildSummary = res.Summary` | + +### 3c. Feasibility (`/work/apps/archie-core/internal/workflow/feasibility.go`) + +**Stage: `"assess"` (lines 28-73)** + +| Field | Value | +|---|---| +| `Name` | `"assess"` | +| `Role` | `"planner"` | +| `ReadOnly` | `true` | +| `MaxSteps` | `15` | +| `Mission` | Lines 34-44. Template: | +| | `"Assess whether this feature request fits the project %s.\n\n\n# %s\n\n%s\n\n\nRead the repository's AGENT.md, ROADMAP.md, and README (whichever exist) plus enough code to judge scope and architectural fit. Then call the decide tool EXACTLY ONCE with fit=true or fit=false and your reasons, and afterwards call finish with status \"passed\" summarising the assessment."` | +| `Gate` | `nil` | +| `ExtraRules` | `""` | +| `ProtectGlobs` | `nil` | +| `CaptureTools` | Lines 33, 123-136: `decideCaptureTools` — provides a `decide` structured-output tool with boolean `fit` and string `reasons` | +| `OnResult` | Lines 45-72: Decodes the `decide` capture, sets `tc.decision`. If not a fit, closes the issue with `Outcome{Status: store.StatusClosedWontDo}` | + +**Stage: `"prd"` (lines 75-95)** + +| Field | Value | +|---|---| +| `Name` | `"prd"` | +| `Role` | `"planner"` | +| `ReadOnly` | `true` | +| `MaxSteps` | `20` | +| `Mission` | Lines 80-90. Template: | +| | `"Write a PRD for this accepted feature request on %s.\n\n\n# %s\n\n%s\n\n\n\n%s\n\n\nExplore the affected code surface, then call finish with status \"passed\" and the PRD as the summary: problem, proposed solution, files/components affected, acceptance criteria, explicit non-goals, and estimated diff size. It will be read by a human deciding whether to green-light implementation."` | +| | The last `%s` is `tc.decision.Reasons` | +| `Gate` | `nil` | +| `ExtraRules` | `""` | +| `ProtectGlobs` | `nil` | +| `CaptureTools` | `nil` | +| `OnResult` | Lines 91-94: Sets `tc.Task.Plan = res.Summary` | + +--- + +## 4. The `Workflow` Struct, `Stage` Struct, `Registry` Type, and `Route()` + +### `Stage` (from `/work/apps/archie-core/internal/workflow/workflow.go`, lines 86-89) + +```go +type Stage struct { + Name string + Run func(ctx context.Context, tc *TaskContext) error +} +``` + +### `Workflow` (lines 92-95) + +```go +type Workflow struct { + Name string + Stages []Stage +} +``` + +### `Registry` (line 98) + +```go +type Registry map[string]Workflow +``` + +### `Route()` (lines 103-141) + +`Route(t *store.Task, reg Registry) Workflow`: + +1. If `t.Workflow` is pre-assigned (non-empty) and exists in the registry, return it immediately (line 104-108). +2. Otherwise, iterate over `t.Labels` (comma-separated): + - `"bug"` -> workflow `"tdd"` + - `"feature"` -> workflow `"feasibility"` + - `"bootstrap"` -> workflow `"bootstrap"` +3. No label match -> fall back to `"implement"`, then `"default"`. +4. If nothing found, returns a no-op "fail" workflow (lines 135-141). + +--- + +## 5. What Would Need to Change to Replace Hardcoded Mission Strings with SKILL.md Content + +This is a read-only analysis of the changes required. Here is the full scope: + +### 5a. Where the strings live today + +Every Mission is an inline `func(*TaskContext) string` closure that calls `fmt.Sprintf` with a hardcoded format string. The seven unique templates are: + +| Workflow | Stage | File | Lines | +|---|---|---|---| +| implement | plan | `implement.go` | 48-64 | +| implement | build | `implement.go` | 83-93 | +| tdd | analyse | `tdd.go` | 31-41 | +| tdd | repro-tests | `tdd.go` | 57-68 | +| tdd | fix | `tdd.go` | 109-118 | +| feasibility | assess | `feasibility.go` | 34-44 | +| feasibility | prd | `feasibility.go` | 80-90 | + +### 5b. The `ExtraRules` field is also hardcoded + +| Workflow | Stage | String | File:Line | +|---|---|---|---| +| implement | build | `"Files matching the repository's protected suffixes..."` | `implement.go:81-82` | +| tdd | fix | `"The repro tests written in the previous stage are the bug's specification..."` | `tdd.go:107-108` | + +### 5c. All the pieces that must change + +**Layer 1: `AgentStage` struct definition** (`agent.go`, lines 16-44) + +- The `Mission` field is currently `func(*TaskContext) string`. To source missions from a file, you have three options: + - **A)** Keep the same signature but have the function read a file at runtime (not great — makes the function impure and harder to test). + - **B)** Add a new field like `MissionSource string` (path to SKILL.md) and modify `Stage()` to load content from that path when `Mission` is nil. This cleanly separates inline missions from file-sourced ones. + - **C)** Replace `Mission` entirely with a `func(*TaskContext) string` that loads and templates from SKILL.md. But you still need per-stage sections within the file. + +**Layer 2: `Stage()` method** (`agent.go`, lines 94-109) + +- Currently line 100: `Mission: a.Mission(tc)` — the mission is called synchronously. +- If files are loaded at construction time or stage-run time, this call site needs to either: + - Use a pre-loaded template string (loaded during `Implement()`, `TDD()`, `Feasibility()` construction), or + - Load the file at runtime inside the closure (less efficient but avoids an init-time dependency on the filesystem). + +**Layer 3: `ExtraRules` sourcing** + +- Currently a plain `string` field. If it should also come from SKILL.md, you need the same treatment: either load it at construction time or add a load-on-use path. + +**Layer 4: How the template variables get injected** + +The current missions use Go `fmt.Sprintf` with arguments like: +- `tc.Repo.FullName()` (passed as `%s`) +- `tc.Task.IssueNumber` (passed as `%d`) +- `tc.Task.Title` (passed as `%s`) +- `tc.Task.Body` (passed as `%s`) +- `tc.Task.Plan` (passed as `%s` — for implement build and tdd fix) +- `tc.decision.Reasons` (passed as `%s` — for feasibility prd) +- `testCommand(tc.Repo)` (passed as `%s` — for tdd repro-tests) + +If you move to a SKILL.md file, you need a template language. Options: +- **Go `text/template`** — already in the stdlib, no dependency. You would pass `*TaskContext` as the data context. Templates like `{{.Repo.FullName}}`, `{{.Task.Title}}` replace the `%s` slots. +- **Keep `fmt.Sprintf`** with numbered placeholders — but then the SKILL.md author must know argument ordering, which is fragile. + +**Layer 5: The SKILL.md file format** + +You need a way to express multiple missions in one file. Options: +- **One SKILL.md per workflow** (e.g., `SKILL_implement.md`, `SKILL_tdd.md`, `SKILL_feasibility.md`) with YAML front-matter for per-stage sections. +- **One section per stage** delimited by headings (`## plan`, `## build`, etc.) and a convention for ExtraRules. +- **YAML front matter** with a `stages` map: each key is a stage name with `mission` and `extra_rules` fields. + +Example YAML-front-matter approach: +```yaml +--- +stages: + plan: + mission: | + Produce a concrete implementation plan for this GitHub issue on the repository {{.Repo.FullName}}. + ... + extra_rules: "" + build: + mission: | + Implement this GitHub issue on the repository {{.Repo.FullName}}... + extra_rules: "Files matching the protected suffixes..." +--- +``` + +**Layer 6: Where SKILL.md lives** + +You need a lookup strategy. Likely candidates: +- Repository root (e.g., `.archie/SKILL.md`) — repo-specific missions +- Config-defined path (`cfg.SkillFile` or similar) +- Embedded in the binary as a fallback + +**Layer 7: Loading and caching** + +- When does the file get read? Per `Run()` call (every stage loads it), once at workflow construction in `Implement()`/`TDD()`/`Feasibility()`, or on daemon startup? +- If per-workflow construction, add a `loadSkillMissions(dir string)` helper called at the top of each workflow factory. +- Caching: the file is small, so a simple `sync.Once` per path or an `fsnotify` watch is overkill unless performance is critical. + +**Layer 8: Fallback behavior** + +- If no SKILL.md exists (which is the default for all repos today), the workflow must fall back to the current hardcoded missions. The simplest approach: keep the existing `Mission` closures as the zero-config default, and only apply SKILL.md content when the file is present. + +### 5d. Concrete minimal change list + +1. **`internal/workflow/agent.go`**: Optionally add a `MissionLoader func(*TaskContext) (string, error)` field or modify `Stage()` to detect and load from a path. Keep backward compat with inline `Mission`. + +2. **`internal/workflow/workflow.go`**: Add a `SkillPath string` (or similar) to `TaskContext` so stage missions can locate the skill file from the worktree directory `tc.Dir`. + +3. **Each workflow factory** (`implement.go`, `tdd.go`, `feasibility.go`): At the top of `Implement()`/`TDD()`/`Feasibility()`, attempt to load `tc.Repo.Dir + "/.archie/SKILL.md"` (or wherever configured). Parse per-stage templates. If the file doesn't exist, keep the existing inline closures as-is. + +4. **Template parsing**: Introduce a package-level helper, e.g. `renderMission(tmpl string, tc *TaskContext) string`, that uses `text/template` against `*TaskContext`. + +5. **`ExtraRules`**: Same treatment — source from the SKILL.md per-stage front matter when present. + +6. **Test the fallback**: Every existing test must continue passing without a SKILL.md file present, proving backward compatibility. \ No newline at end of file diff --git a/.scratch/explore-chunkC-patterns.md b/.scratch/explore-chunkC-patterns.md new file mode 100644 index 000000000..c3c695059 --- /dev/null +++ b/.scratch/explore-chunkC-patterns.md @@ -0,0 +1,230 @@ +# patterns + +Here is the comprehensive report. + +--- + +## 1. Existing Skill-Loading and Frontmatter-Parsing Code + +**No existing frontmatter-parsing or SKILL.md-loading code exists in the Go codebase.** My searches confirm: + +- `grep -rn 'SKILL\.md' --include='*.go'` -- zero results. +- `grep -rn 'frontmatter\|front.matter\|front_matter' --include='*.go'` -- zero results. +- `grep -rn 'yaml\.' --include='*.go'` -- zero results. No YAML parsing of any kind exists yet. +- `grep -rn 'metadata\.archie\|archie-wf' --include='*.go'` -- zero results. +- `grep -rn 'ReadFile.*\.md\|os\.ReadFile.*skill' --include='*.go'` -- zero results. + +**What *does* reference "skill" in Go code are two packages, neither of which loads or parses SKILL.md:** + +- **`internal/skillscript/yaegi.go`** -- An interpreter helper that runs a Go script at a given filesystem path via Yaegi. It has no discovery logic, no directory scanning, no idea what a SKILL.md is. Its `Run(path string)` function just interprets a single `.go` file. +- **`internal/agentexec/inprocess.go`** -- Uses `internal/skillscript` to register a `run_go_script` tool that agents can call. It discovers nothing -- it takes a script path from the LLM's tool call arguments and delegates to `skillscript.Run()`. + +**The SKILL.md files that exist on disk** (5 total) are written by hand in the skills directory: + +| File | path | +|---|---| +| go-quality-gate | `.archie/skills/go-quality-gate/SKILL.md` | +| ecosystem-node | `.archie/skills/ecosystem-node/SKILL.md` | +| ecosystem-python | `.archie/skills/ecosystem-python/SKILL.md` | +| security-audit | `.archie/skills/security-audit/SKILL.md` | +| tdd-bugfix | `.archie/skills/tdd-bugfix/SKILL.md` | + +All five have identical frontmatter structure: +```yaml +--- +name: +description: > + +version: 1.0.0 +metadata: + archie: + tools: [] + engine: any +--- +``` + +This frontmatter is currently **dead content** -- no Go code reads or parses it. + +--- + +## 2. The Existing Directory-Discovery Pattern (wfeval.Discover) + +File: `/work/apps/archie-core/internal/workflow/wfeval/yaegi.go` + +This is the pattern to follow for any new skill-discovery code. Here is exactly how it works: + +### The constant +```go +const stagesDir = ".archie/stages" +``` + +### The function signature +```go +func Discover(dir string) ([]workflow.Stage, error) +``` + +### How it scans +1. `os.ReadDir(filepath.Join(dir, stagesDir))` -- reads the directory +2. If `os.IsNotExist(err)`, returns `(nil, nil)` -- **missing directory is not an error** +3. Any other read error is returned as a wrapped error +4. Iterates entries, filtering for `!e.IsDir() && filepath.Ext(e.Name()) == ".go"` +5. `sort.Strings(names)` -- **alphabetical order** is deterministic ordering +6. Calls `loadStage()` for each file, wrapping errors with the relative path +7. Returns the slice (or an empty slice if no `.go` files found) + +### How it loads a single stage +1. `os.ReadFile(path)` -- reads the entire Go source +2. Creates a Yaegi interpreter with `stdlib.Symbols` + `wfextract.Symbols` (the generated symbol table for `internal/workflow`) +3. `i.Eval(string(src))` -- interprets the Go source +4. `i.Eval("stages.Stage")` -- looks up the exported `Stage` function +5. Type-asserts it as `func() workflow.Stage` +6. Calls the factory function to get the `workflow.Stage` value + +### Error handling philosophy +- Missing directory: silent no-op (nil, nil) +- File-system errors: wrapped with the relative path context +- Panics in interpreted code: recovered via `defer`/`recover()`, returned as error +- Wrong function signature: clear error message +- A single bad file blocks the entire Discover call (fail-fast) + +### How it's wired in +In `internal/workflow/workflow.go`, the `TaskContext` struct has: +```go +CustomStages func(dir string) ([]Stage, error) +``` +This is injected by the composition root (`cmd/archied/`) to avoid a direct import cycle between `workflow` and its own generated Yaegi symbol table. + +--- + +## 3. Recommended YAML Dependency and Parsing Approach + +### Current state +- `go.mod` at `/work/apps/archie-core/go.mod` has **no YAML library**. +- The only markup parser is `github.com/BurntSushi/toml v1.6.0` for TOML config files. +- `gopkg.in/yaml.v3` is the standard Go YAML library and is **not** present. + +### Recommendation +**Add `gopkg.in/yaml.v3`** -- this is the de facto standard Go YAML library, maintained by the Go team, supports the full YAML 1.2 spec, and is what every major Go project uses. + +### Parsing approach for SKILL.md frontmatter +The SKILL.md files use standard YAML frontmatter between `---` delimiters. The parsing pattern would be: + +```go +import "gopkg.in/yaml.v3" + +type SkillFrontmatter 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"` + // future: plugins, budget_usd, etc. + } `yaml:"archie"` + } `yaml:"metadata"` +} + +// ParseFrontmatter extracts YAML frontmatter from a SKILL.md byte slice. +// Returns the frontmatter struct and the body content after the closing ---. +func ParseFrontmatter(src []byte) (*SkillFrontmatter, string, error) { + // 1. Split on "---\n" — first block is YAML, rest is body + // 2. yaml.Unmarshal() the YAML block into SkillFrontmatter + // 3. Return parsed metadata + body string +} +``` + +The TOML parsing pattern already in the codebase (file `/work/apps/archie-core/internal/config/config.go`) uses struct tags and straightforward `toml.DecodeFile()` -- the YAML equivalent would use `yaml.Unmarshal()` instead. + +--- + +## 4. What the agentskills.io Specification Says + +Source: https://agentskills.io/specification (fetched successfully) + +### Naming convention +- The spec defines the `name` field: 1-64 chars, lowercase alphanumeric + hyphens, must match the parent directory name. +- There is **no "archie-wf-" prefix** in the public agentskills.io spec. That prefix appears to be archie-core's own convention (possibly for workflow-specific skills), not a spec requirement. + +### Metadata block +- The `metadata` field is an **optional** key-value mapping (string to string). +- The spec does **not** define any `metadata.archie` sub-block. That block (`metadata.archie.tools`, `metadata.archie.engine`) is archie-core's own extension. + +### Full frontmatter fields defined by the spec + +| Field | Required | Description | +|---|---|---| +| `name` | Yes | 1-64 chars, lowercase+hyphens, matches dir name | +| `description` | Yes | 1-1024 chars, what + when to use | +| `license` | No | License name or reference | +| `compatibility` | No | Environment requirements (500 char max) | +| `metadata` | No | Arbitrary string-to-string map | +| `allowed-tools` | No | Space-separated pre-approved tools (experimental) | + +### SKILL.md structure +``` +--- + +--- + +``` + +### Directory structure +``` +skill-name/ + SKILL.md (required) + scripts/ (optional) + references/ (optional) + assets/ (optional) +``` + +### Progressive disclosure tiers +1. **Catalog** (~100 tokens/skill): `name` and `description` loaded at startup +2. **Instructions** (<5000 tokens): Full SKILL.md body when skill is activated +3. **Resources**: Scripts/references/assets loaded on demand + +### Scanning locations +- Project: `/./skills/` and `/.agents/skills/` +- User: `~/./skills/` and `~/.agents/skills/` +- `.claude/skills/` is mentioned as a pragmatic compatibility convention + +--- + +## 5. The Full .archie/ Directory Tree + +``` +.archie/ + skills/ + ecosystem-node/ + SKILL.md + ecosystem-python/ + SKILL.md + go-quality-gate/ + SKILL.md + security-audit/ + SKILL.md + tdd-bugfix/ + SKILL.md +``` + +**What does NOT exist yet:** +- No `.archie/stages/` directory (stage scripts are in the spec but none exist yet) +- No `.archie/config` or `.archie/config.toml` (configuration is in a top-level `config.toml`, not `.archie/`) +- No `scripts/` subdirectories inside any skill (all 5 skills have only `SKILL.md`) +- No `references/` or `assets/` subdirectories inside any skill + +--- + +### Summary of Key File Paths + +| File | Purpose | +|---|---| +| `/work/apps/archie-core/internal/workflow/wfeval/yaegi.go` | **The discovery pattern to follow** -- scans `.archie/stages/*.go`, sorts, loads via Yaegi | +| `/work/apps/archie-core/internal/workflow/wfeval/yaegi_test.go` | Tests showing the discovery pattern | +| `/work/apps/archie-core/internal/workflow/workflow.go` | Workflow engine, Stage struct, CustomStages injection pattern | +| `/work/apps/archie-core/internal/skillscript/yaegi.go` | Yaegi runner for skill Go scripts (no discovery, no SKILL.md parsing) | +| `/work/apps/archie-core/internal/agentexec/inprocess.go` | Registers `run_go_script` tool using skillscript.Run() (line 181-207) | +| `/work/apps/archie-core/internal/config/config.go` | Existing TOML config parsing pattern (reference for adding YAML) | +| `/work/apps/archie-core/go.mod` | Dependencies -- no YAML lib yet, BurntSushi/toml v1.6.0 present | +| `/work/apps/archie-core/.references/skills-implementation.md` | Research notes on implementing agentskills.io support in archie | +| `/work/apps/archie-core/.archie/skills/*/SKILL.md` | 5 hand-written skill files with YAML frontmatter (currently dead content) | \ No newline at end of file diff --git a/.scratch/explore-chunkC-skills.md b/.scratch/explore-chunkC-skills.md new file mode 100644 index 000000000..b18e8ba3e --- /dev/null +++ b/.scratch/explore-chunkC-skills.md @@ -0,0 +1,342 @@ +# skills + +Here is the complete analysis. + +--- + +## Complete Report: SKILL.md Files in archie-core + +### 1. Tally of files + +There are exactly **5 SKILL.md files** in the repository, all under `/work/apps/archie-core/.archie/skills/`. There are no others anywhere in the repo. + +--- + +### 2. Supporting directories + +There are **no `plugins/` or `scripts/` subdirectories** inside any skill directory. The `scripts/` feature described in the agentskills.io spec and the Yaoi interpreter (`internal/skillscript/yaegi.go`) exist in the Go code but have no content in the actual skill directories. The `run_go_script` tool in `internal/agentexec/inprocess.go` (lines 181-207) references scripts at `.archie/skills//scripts/*.go`, but no such files exist. + +--- + +### 3. Per-file analysis + +--- + +#### 3.1 tdd-bugfix/SKILL.md + +**File:** `/work/apps/archie-core/.archie/skills/tdd-bugfix/SKILL.md` + +**Complete YAML frontmatter:** + +```yaml +name: tdd-bugfix +description: > + Fix bugs using test-driven development. Write a failing repro test first, prove + it captures the bug, then fix the code without touching the tests. archie-core + routes issues labelled "bug" through this workflow automatically. +version: 1.0.0 +metadata: + archie: + tools: [go, golangci-lint] + engine: any +``` + +Key-value pairs extracted: +- `name`: "tdd-bugfix" +- `description`: Multiline string (about TDD bugfix) +- `version`: "1.0.0" +- `metadata.archie.tools`: [go, golangci-lint] +- `metadata.archie.engine`: "any" + +**Body content structure:** + +The body has 6 sections: +1. `## When this runs` (1 paragraph: describes that archie-core routes "bug" labelled issues through this workflow; mentions the 5 stages) +2. `## Stage 1: Analyse (read-only planner)` (prose: what the planner produces, no-code constraint) +3. `## Stage 2: Repro Tests (write failing tests only)` (prose with bullet constraints: don't touch non-test files, gate inverted, make failure explicit) +4. `## Stage 3: Capture Proof (deterministic)` (prose: archie-core runs the test command directly) +5. `## Stage 4: Fix (code only)` (prose with bullet constraints: test files write-protected, full gate runs, smallest fix) +6. `## Stage 5: Deliver` (numbered list: commits, push, PR, comment with proof) +7. `## Common pitfalls` with 3 sub-pitfalls (each with prose and checklist) + +**Mapping to hardcoded Go code:** + +This skill documents the exact workflow that is hardcoded in `internal/workflow/tdd.go` lines 18-149. The 5 stages correspond directly: +- "analyse" -> `AgentStage{Name: "analyse", ...}` (line 27) +- "repro-tests" -> `AgentStage{Name: "repro-tests", ...}` (line 48) +- "capture-proof" -> `Stage{Name: "capture-proof", Run: ...}` (line 73) +- "fix" -> `AgentStage{Name: "fix", ...}` (line 92) +- "deliver" -> Stage `open-pr` (line 133) plus the two commit stages (lines 88, 125) + +Every constraint in the SKILL.md body (inverted gate, test file write-protection, smallest fix, two-commit history) is reflected as code in `tdd.go` and `agent.go`. + +--- + +#### 3.2 go-quality-gate/SKILL.md + +**File:** `/work/apps/archie-core/.archie/skills/go-quality-gate/SKILL.md` + +**Complete YAML frontmatter:** + +```yaml +name: go-quality-gate +description: > + Run the full Go quality pipeline: gofumpt, go fix, golangci-lint, go test -race, + and task deadcode. Use before any commit in a Go project. Triggered automatically + by archie-core's implement and tdd workflows via the per-repo gate config. +version: 1.0.0 +metadata: + archie: + tools: [go, golangci-lint, gofumpt, task] + engine: any +``` + +Key-value pairs extracted: +- `name`: "go-quality-gate" +- `description`: Multiline string (about Go quality pipeline) +- `version`: "1.0.0" +- `metadata.archie.tools`: [go, golangci-lint, gofumpt, task] +- `metadata.archie.engine`: "any" + +**Body content structure:** + +5 sections with mixed content: +1. `## When this runs` (prose: gate is enforced after every builder stage; commands come from repo config) +2. `## Standard gate (Tau and similar Go projects)` (TOML examples showing gate commands, plus convention about last command being test runner) +3. `## Diagnosing gate failures` with 4 subsections (each with prose and common fixes): + - `### gofumpt / go fix` + - `### golangci-lint` (bullet list of common linters and fixes) + - `### go test -race` (numbered diagnostic steps) + - `### task deadcode` (bash example for scoping) +4. `## When the TDD workflow runs` (prose about inverted gate during repro-tests) + +**Mapping to hardcoded Go code:** + +- The gate mechanism is implemented in `internal/workflow/agent.go` lines 152-161 (`GateFromRepo()`) and `internal/workflow/tdd.go` lines 155-174 (`tddReproGate()`). +- The `tools` list maps conceptually to `config.Repo.Gate` in `internal/config/config.go` lines 37-43 (a `[][]string` of commands). +- The skill documents conventions, not code that loads the SKILL.md. + +--- + +#### 3.3 security-audit/SKILL.md + +**File:** `/work/apps/archie-core/.archie/skills/security-audit/SKILL.md` + +**Complete YAML frontmatter:** + +```yaml +name: security-audit +description: > + Scan code for security vulnerabilities: hardcoded secrets, injection vectors, + unsafe deserialization, missing auth checks, and path traversal. Use on PRs + touching auth, API endpoints, or data handling code. +version: 1.0.0 +metadata: + archie: + tools: [golangci-lint, trivy, gitleaks] + engine: any +``` + +Key-value pairs extracted: +- `name`: "security-audit" +- `description`: Multiline string (about security scanning triggers) +- `version`: "1.0.0" +- `metadata.archie.tools`: [golangci-lint, trivy, gitleaks] +- `metadata.archie.engine`: "any" + +**Body content structure:** + +4 top-level sections: +1. `## When to use` (bullet list of trigger conditions: PR touches auth, new API endpoints, db queries, dependency updates) +2. `## What to check` with 5 numbered subsections: + - `### 1. Hardcoded secrets` (bullet list of scan targets + `gitleaks` example) + - `### 2. Injection vectors` (SQL, Command, Path sub-bullets with specific Go tools) + - `### 3. Unsafe deserialization` (bullet list of Go-specific patterns) + - `### 4. Missing auth checks` (bullet list of endpoint/token issues) + - `### 5. Dependency CVEs` (`trivy` command example + report format) +3. `## Reporting` (numbered list of 5 report fields: Severity, Location, Description, Fix, Prevention) +4. Closing line: "If nothing is found, report clean. Never fabricate findings." + +**Mapping to hardcoded Go code:** + +- **No hardcoded workflow exists** for security-audit in the Go codebase. This skill is purely informational/documentation. +- It is not registered as a workflow in `cmd/archied/main.go` lines 163-169. +- There is no label routing for security tasks in `internal/workflow/workflow.go` lines 100-141. +- It exists as a skill that could be invoked manually or through future orchestration. + +--- + +#### 3.4 ecosystem-node/SKILL.md + +**File:** `/work/apps/archie-core/.archie/skills/ecosystem-node/SKILL.md` + +**Complete YAML frontmatter:** + +```yaml +name: ecosystem-node +description: > + Node.js/TypeScript project conventions for archie-core: npm/pnpm, eslint, + prettier, tsc, vitest. Use when working on Node repositories with archie-core. +version: 1.0.0 +metadata: + archie: + tools: [node, npm, pnpm, vitest, eslint, prettier] + engine: any +``` + +Key-value pairs extracted: +- `name`: "ecosystem-node" +- `description`: Multiline string (about Node/TS project conventions) +- `version`: "1.0.0" +- `metadata.archie.tools`: [node, npm, pnpm, vitest, eslint, prettier] +- `metadata.archie.engine`: "any" + +**Body content structure:** + +7 sections: +1. `## Preflight` (prose + mention of `node --version`) +2. `## Recommended gate configuration` (TOML example blocks for pnpm and npm) +3. `## Test glob` (prose: default `*.test.ts`, override config examples) +4. `## Package management` (prose + bash: lockfile detection, install command) +5. `## Common tools` (markdown table: Tool, Purpose, Config file — 5 rows) +6. `## Common gate failures` with 3 subsections: + - `### eslint` (bullet list) + - `### tsc / typecheck` (bullet list) + - `### vitest / jest` (bullet list) + +**Mapping to hardcoded Go code:** + +The content maps directly to `internal/config/ecosystem.go` lines 22-25: +```go +"node": { + Preflight: [][]string{{"node", "--version"}}, + TestGlob: "*.test.ts", +}, +``` +The preflight check and default test glob are hardcoded. Lockfile detection logic is referenced in prose but not implemented in the Go code shown. + +--- + +#### 3.5 ecosystem-python/SKILL.md + +**File:** `/work/apps/archie-core/.archie/skills/ecosystem-python/SKILL.md` + +**Complete YAML frontmatter:** + +```yaml +name: ecosystem-python +description: > + Python project conventions for archie-core: venv, pytest, ruff, mypy, pip-audit. + Use when working on Python repositories with archie-core. +version: 1.0.0 +metadata: + archie: + tools: [python, pytest, ruff, mypy, pip-audit] + engine: any +``` + +Key-value pairs extracted: +- `name`: "ecosystem-python" +- `description`: Multiline string (about Python project conventions) +- `version`: "1.0.0" +- `metadata.archie.tools`: [python, pytest, ruff, mypy, pip-audit] +- `metadata.archie.engine`: "any" + +**Body content structure:** + +7 sections: +1. `## Preflight` (prose + `python --version`) +2. `## Recommended gate configuration` (TOML example) +3. `## Test glob` (prose: default `test_*.py`, override example) +4. `## Package management` (bullet list of assumptions) +5. `## Virtual environment` (bash examples for venv setup) +6. `## Common gate failures` with 3 subsections: + - `### ruff` (bullet list) + - `### mypy` (bullet list) + - `### pytest` (bullet list) + +**Mapping to hardcoded Go code:** + +Maps directly to `internal/config/ecosystem.go` lines 18-21: +```go +"python": { + Preflight: [][]string{{"python", "--version"}}, + TestGlob: "test_*.py", +}, +``` + +--- + +### 4. The agentskills.io Specification + +The specification at `https://agentskills.io/specification` defines these fields: + +| Field | Required | Notes | +|---|---|---| +| `name` | Yes | 1-64 chars, lowercase + hyphens, matches directory name | +| `description` | Yes | 1-1024 chars, describes what and when | +| `license` | No | Short license name or reference | +| `compatibility` | No | Environment requirements (product, packages, network) | +| `metadata` | No | Arbitrary key-value map for additional properties | +| `allowed-tools` | No | Space-separated string of pre-approved tools (experimental) | + +The spec also defines optional subdirectories: `scripts/`, `references/`, `assets/`. + +**Contrast with current archie-core format:** + +- `version: 1.0.0` exists in all 5 skills but is **not an agentskills.io field** -- it is custom archie-core metadata inside `metadata.archie`. The spec would expect `metadata.version` or simply omitting version from the spec-level fields. +- `metadata.archie.tools` is a custom archie extension. The spec has `allowed-tools` (string format, experimental) which serves a similar purpose but with different semantics (pre-approval for tool use vs. listing required tools). +- `metadata.archie.engine: any` is custom archie metadata with no spec equivalent. +- None of the current skills use `license`, `compatibility`, or `allowed-tools` from the spec. + +--- + +### 5. Analysis: Which fields would be useful as machine-readable skill configuration + +Based on how the Go code currently consumes configuration and how the workflow engine works (`internal/workflow/workflow.go`, `internal/workflow/agent.go`, `internal/config/config.go`), the following would benefit from machine parsing: + +**A. `tools` / `allowed-tools` (pre-approval list)** +- Currently hardcoded per skill in `metadata.archie.tools` but not parsed by any Go code. +- Would enable the agent runtime to pre-authorize external tool calls (golangci-lint, trivy, gitleaks, etc.) without prompting, matching the agentskills.io experimental `allowed-tools` concept. +- The TDD workflow's gate mechanism already runs these tools via `config.Repo.Gate` -- a parsed tools list could validate the gate commands against the skill's declared toolset. + +**B. `ecosystem` (language/runtime constraint)** +- Currently configured per-repo in TOML as `config.Repo.Ecosystem` (via `internal/config/ecosystem.go`), not per-skill. +- The ecosystem-node and ecosystem-python skills document conventions that overlap with the Go hardcodes. A machine-readable ecosystem field on a skill would let the skill declare its language affinity. +- No skill currently has this as a top-level field. + +**C. `engine` constraint (e.g., any, archied v1, ...)** +- Currently `metadata.archie.engine: any` in every skill, not parsed. +- Could gate skill activation to specific engine versions (`archie-core >= 0.5`, `claude-code >= 1.0`). + +**D. `budget` (max steps, max tokens, wall clock)** +- Currently hardcoded per workflow in Go: `internal/workflow/agent.go` lines 60-67 reads from `config.Budgets` with per-AgentStage overrides (e.g., MaxSteps=15 for planner, 20 for feasiability PRD stage). +- A machine-readable budget field could let the skill declare its expected resource needs, overriding global defaults when appropriate. + +**E. `plugins` (extension scripts)** +- Not present in any current skill. The `internal/skillscript/yaegi.go` infrastructure supports running `.go` scripts from a skill's `scripts/` directory, but no skill has one. +- Could declare scripts that the agent runtime should load and expose as tools. + +**F. Stage/workflow structure** +- The body text of tdd-bugfix describes a 5-stage workflow with named stages, but this is natural language only. +- The Go workflows are hardcoded in `internal/workflow/tdd.go`, `implement.go`, `feasibility.go`, and `steps.go`. +- A machine-readable stages list in the frontmatter or a companion YAML file would allow the workflow engine to load workflows from skills without recompilation. Currently, new workflows require Go code changes in `cmd/archied/main.go` lines 163-169. + +**G. Gate configuration** +- The quality gate is documented in `go-quality-gate/SKILL.md` as TOML examples but configured per-repo in the daemon's TOML config. A skill-declared gate skeleton would let the skill say "I need these commands to verify correctness." + +--- + +### 6. Summary of the gap + +The current system has **no Go code that reads SKILL.md files programmatically**. The files exist purely as human-readable documentation. All workflow logic is hardcoded in Go: + +- `internal/workflow/implement.go` -- plan + build stages +- `internal/workflow/tdd.go` -- analyse + repro-tests + capture-proof + fix + deliver +- `internal/workflow/feasibility.go` -- assess + prd + deliver +- `internal/workflow/steps.go` -- shared steps (prepare, commit, push, gate, diff cap, PR) +- `internal/workflow/agent.go` -- AgentStage adapter that turns workflow config into `agentexec.Request` + +The only code that touches skill directories is `/work/apps/archie-core/internal/skillscript/yaegi.go` (interprets `scripts/*.go` files) and the `scriptToolSet` in `/work/apps/archie-core/internal/agentexec/inprocess.go` lines 181-207 (exposes the `run_go_script` tool to agents). Both of these are unused since no skill has any `scripts/` content. + +To make skills machine-parseable, the frontmatter would need to adopt the agentskills.io standard fields plus archie-specific extensions (tools list as per spec's `allowed-tools` or a custom `metadata.archie` block, plus possibly a declarative stage/workflow scheme in the frontmatter or a companion YAML file). \ No newline at end of file diff --git a/go.mod b/go.mod index 3a1b1adaf..4c53ed27f 100644 --- a/go.mod +++ b/go.mod @@ -36,6 +36,7 @@ require ( github.com/nats-io/nats.go v1.52.0 github.com/samcharles93/ai-sdk v0.1.17 github.com/traefik/yaegi v0.16.1 + gopkg.in/yaml.v3 v3.0.1 ) replace github.com/samcharles93/ai-sdk => /work/projects/ai-sdk diff --git a/go.sum b/go.sum index 93ff558e3..3f7bdffce 100644 --- a/go.sum +++ b/go.sum @@ -59,6 +59,10 @@ golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc= modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= diff --git a/internal/agentexec/inprocess.go b/internal/agentexec/inprocess.go index 8f90794ca..a952aae1c 100644 --- a/internal/agentexec/inprocess.go +++ b/internal/agentexec/inprocess.go @@ -173,7 +173,7 @@ func captureToolSet(specs []CaptureTool, captures map[string][]json.RawMessage) } // scriptToolSet exposes run_go_script: interpreting a Yaegi Go script -// bundled with a skill (.archie/skills//scripts/*.go) or living +// bundled with a skill (.agents/skills//scripts/*.go) or living // anywhere else in the workspace, and returning what it printed. This is // how an agent following a skill's instructions ("run scripts/gitleaks.go // to scan for secrets") actually executes a .go helper without a Go diff --git a/internal/skill/skill.go b/internal/skill/skill.go new file mode 100644 index 000000000..faf2ee8f0 --- /dev/null +++ b/internal/skill/skill.go @@ -0,0 +1,116 @@ +// 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"` + } `yaml:"archie"` + } `yaml:"metadata"` +} + +// Skill is a parsed SKILL.md file with its frontmatter and body. +type Skill struct { + Frontmatter Frontmatter + Body string + Dir string // skill directory name (e.g. "tdd-bugfix") +} + +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) + } + out[name] = Skill{Frontmatter: *fm, Body: body, Dir: name} + } + 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) +} diff --git a/internal/skill/skill_test.go b/internal/skill/skill_test.go new file mode 100644 index 000000000..b0efdbf1f --- /dev/null +++ b/internal/skill/skill_test.go @@ -0,0 +1,164 @@ +package skill + +import ( + "os" + "path/filepath" + "testing" +) + +func TestParse(t *testing.T) { + src := []byte(`--- +name: tdd-bugfix +description: Fix bugs with TDD +version: 1.0.0 +metadata: + archie: + tools: [go, golangci-lint] + engine: any +--- + +## Stage 1: Analyse + +Read the code and find the bug. +`) + fm, body, err := Parse(src) + if err != nil { + t.Fatal(err) + } + if fm.Name != "tdd-bugfix" { + t.Errorf("Name: got %q, want tdd-bugfix", fm.Name) + } + if fm.Version != "1.0.0" { + t.Errorf("Version: got %q, want 1.0.0", fm.Version) + } + if fm.Metadata.Archie == nil { + t.Fatal("Metadata.Archie is nil") + } + if len(fm.Metadata.Archie.Tools) != 2 || fm.Metadata.Archie.Tools[0] != "go" { + t.Errorf("Tools: got %v", fm.Metadata.Archie.Tools) + } + if fm.Metadata.Archie.Engine != "any" { + t.Errorf("Engine: got %q, want any", fm.Metadata.Archie.Engine) + } + if body != "## Stage 1: Analyse\n\nRead the code and find the bug." { + t.Errorf("Body: got %q", body) + } +} + +func TestParseNoFrontmatter(t *testing.T) { + src := []byte(`# Just markdown + +No YAML frontmatter here. +`) + fm, body, err := Parse(src) + if err != nil { + t.Fatal(err) + } + if fm.Name != "" { + t.Errorf("Name should be empty, got %q", fm.Name) + } + if body != string(src) { + t.Errorf("Body should be the full content") + } +} + +func TestDiscover(t *testing.T) { + dir := t.TempDir() + skillsDir := filepath.Join(dir, ".agents", "skills") + + // Create tdd-bugfix skill. + tddDir := filepath.Join(skillsDir, "tdd-bugfix") + if err := os.MkdirAll(tddDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(tddDir, "SKILL.md"), []byte(`--- +name: tdd-bugfix +description: TDD bugfix workflow +version: 1.0.0 +metadata: + archie: + tools: [go] + engine: any +--- + +Body content here. +`), 0o644); err != nil { + t.Fatal(err) + } + + // Create ecosystem-node skill. + nodeDir := filepath.Join(skillsDir, "ecosystem-node") + if err := os.MkdirAll(nodeDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(nodeDir, "SKILL.md"), []byte(`--- +name: ecosystem-node +description: Node conventions +version: 1.0.0 +metadata: + archie: + tools: [node, npm] + engine: any +--- + +Node stuff. +`), 0o644); err != nil { + t.Fatal(err) + } + + skills, err := Discover(dir) + if err != nil { + t.Fatal(err) + } + if len(skills) != 2 { + t.Fatalf("got %d skills, want 2", len(skills)) + } + if _, ok := skills["tdd-bugfix"]; !ok { + t.Error("missing tdd-bugfix") + } + if _, ok := skills["ecosystem-node"]; !ok { + t.Error("missing ecosystem-node") + } + if skills["tdd-bugfix"].Body != "Body content here." { + t.Errorf("tdd body: got %q", skills["tdd-bugfix"].Body) + } +} + +func TestDiscoverMissing(t *testing.T) { + dir := t.TempDir() + skills, err := Discover(dir) + if err != nil { + t.Fatal(err) + } + if skills != nil { + t.Errorf("expected nil map for missing dir, got %v", skills) + } +} + +func TestLoadBody(t *testing.T) { + dir := t.TempDir() + skillsDir := filepath.Join(dir, ".agents", "skills", "tdd-bugfix") + if err := os.MkdirAll(skillsDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(skillsDir, "SKILL.md"), []byte(`--- +name: tdd-bugfix +description: desc +version: 1.0.0 +--- +Body content. +`), 0o644); err != nil { + t.Fatal(err) + } + + body := LoadBody(dir, "tdd-bugfix") + if body != "Body content." { + t.Errorf("got %q, want 'Body content.'", body) + } + + // Non-existent skill returns empty. + body = LoadBody(dir, "nonexistent") + if body != "" { + t.Errorf("expected empty, got %q", body) + } +} diff --git a/internal/skillscript/yaegi.go b/internal/skillscript/yaegi.go index 9049e3194..2983ef473 100644 --- a/internal/skillscript/yaegi.go +++ b/internal/skillscript/yaegi.go @@ -1,4 +1,4 @@ -// Package skillscript runs skill-bundled Go scripts (.archie/skills//scripts/*.go) +// Package skillscript runs skill-bundled Go scripts (.agents/skills//scripts/*.go) // via Yaegi. Unlike the gate and workflow-stage extension surfaces, these // scripts only need the Go standard library — they wrap external tools // (gitleaks, trivy, ...) the way a shell script would — so no diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index 109daa2f3..f941a9edf 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -6,6 +6,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/skill" ) // AgentStage is the reusable bridge from a workflow stage to an @@ -46,6 +47,12 @@ type AgentStage struct { // Stage adapts the AgentStage to the engine. func (a AgentStage) Stage() Stage { return Stage{Name: a.Name, Run: func(ctx context.Context, tc *TaskContext) error { + // Lazy-load the skill body from the worktree (dir is set by the + // prepare stage, which runs before any agent stage). If the body + // was already loaded by the daemon, this is a no-op. + if tc.SkillBody == "" && tc.Dir != "" { + tc.SkillBody = loadSkillBody(tc) + } if tc.Agent == nil { return fmt.Errorf("no LLM runtime configured (missing [providers] in config?)") } @@ -97,7 +104,7 @@ func (a AgentStage) Stage() Stage { Attempt: tc.Task.Attempt, Stage: a.Name, Model: modelRef, - Mission: a.Mission(tc), + Mission: missionWithSkill(tc, a.Mission(tc)), ExtraRules: a.ExtraRules, ReadOnly: a.ReadOnly, Budget: budget, @@ -159,3 +166,29 @@ func GateFromRepo(repo config.Repo, budgets config.Budgets) agentexec.Gate { } return agentexec.Gate{Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures} } + +// missionWithSkill prepends the skill body (loaded from SKILL.md) to the +// stage's mission. When no skill is loaded, the mission is returned unchanged. +func missionWithSkill(tc *TaskContext, mission string) string { + if tc.SkillBody == "" { + return mission + } + return "Follow these project-specific guidelines:\n\n" + tc.SkillBody + "\n\n---\n\n" + mission +} + +// workflowToSkill maps a workflow name to the skill directory name. +var workflowToSkill = map[string]string{ + "tdd": "tdd-bugfix", + "implement": "implement", + "feasibility": "feasibility", +} + +// loadSkillBody attempts to load the SKILL.md body for the current workflow +// from the worktree's .agents/skills/ directory. Returns "" if not found. +func loadSkillBody(tc *TaskContext) string { + skillDir, ok := workflowToSkill[tc.Task.Workflow] + if !ok { + return "" + } + return skill.LoadBody(tc.Dir, skillDir) +} diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 2781233cf..2238fd0d1 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -42,6 +42,10 @@ type TaskContext struct { // generated Yaegi symbol table (an import cycle). CustomStages func(dir string) ([]Stage, error) + // SkillBody is the Markdown body of the loaded SKILL.md for this + // workflow's matching skill, injected into agent context. Empty + // when no skill is found (backward compatible). + SkillBody string // Dir/Branch are set by the prepare step. Dir string Branch string