feat: add Yaegi-based plugin system (gates, custom stages, skill scripts)
Implements the full PRD (docs/prds/yaegi-plugin-system.md): repos can now define .archie/gate.go for diff-inspecting quality rules shell commands can't express, .archie/stages/*.go for custom pipeline steps, and skills can ship Go scripts run via a new run_go_script agent tool — all interpreted in-process with Yaegi, with panics recovered so a bad script can't take down the daemon. Hot reload (phase 4) needed no code: every loader reads from disk per call and every task gets a fresh clone, so nothing is ever cached to go stale.
This commit is contained in:
1 parent
5fc61e0bad
commit
c0d108a5d0
25 files changed
+1191
-30
No files matched your search
+3
-1
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/workflow/wfeval"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
@@ -143,7 +144,8 @@ func run() int {
|
||||
"feasibility": workflow.Feasibility(),
|
||||
"default": workflow.Implement(),
|
||||
},
|
||||
Log: log,
|
||||
Log: log,
|
||||
CustomStages: wfeval.Discover,
|
||||
}
|
||||
|
||||
if err := d.Startup(ctx); err != nil {
|
||||
|
||||
@@ -229,27 +229,32 @@ func NewReportable() Reportable { return &MyGate{} }
|
||||
|
||||
## Implementation phases
|
||||
|
||||
### Phase 1: Gate functions
|
||||
- Add `yaegi` as a dependency (`go get github.com/traefik/yaegi`)
|
||||
- Build symbol tables for `GateContext`, `Finding` via `yaegi extract`
|
||||
- Add `internal/gate/yaegi.go`: load `.archie/gate.go`, compile, call `Check()`
|
||||
- Wire into the gate stage — runs after shell-based gate commands
|
||||
- Error findings park the task; warn findings are logged
|
||||
### Phase 1: Gate functions — implemented
|
||||
- `yaegi` added as a dependency
|
||||
- Symbol table for `GateContext`, `Finding` generated via `yaegi extract` into `internal/gate/gateextract` (a separate package from `internal/gate` itself, avoiding the self-import cycle extracting a package's own symbols creates)
|
||||
- `internal/gate/gateeval.Evaluate`: loads `.archie/gate.go` from the worktree, interprets it, calls `Check()`; panics are recovered
|
||||
- Wired in as `workflow.StageYaegiGate`, run after the final commit in both the `implement` and `tdd` workflows
|
||||
- Error findings park the task; warn findings are logged only
|
||||
|
||||
### Phase 2: Custom stages
|
||||
- Build symbol tables for `workflow.Stage`, `workflow.TaskContext`
|
||||
- Add stage discovery: scan `.archie/stages/*.go` and register each `Stage()` function
|
||||
- Allow `config.toml` to reference custom stages in workflow definitions
|
||||
### Phase 2: Custom stages — implemented
|
||||
- Symbol table for `workflow.Stage`/`TaskContext`/`Outcome` generated into `internal/workflow/wfextract`
|
||||
- `internal/workflow/wfeval.Discover` scans `.archie/stages/*.go` in filename order and calls each file's exported `Stage()` function
|
||||
- `TaskContext.CustomStages` is an injected `func(dir string) ([]Stage, error)` — the composition root (`cmd/archied`) wires it to `wfeval.Discover`, keeping `internal/workflow` decoupled from its own generated symbol table
|
||||
- `workflow.StageRepoStages` runs discovered stages in order right after the worktree is prepared, in both `implement` and `tdd`
|
||||
- Simplification vs. the original sketch: stages are auto-discovered and always run (like `.archie/gate.go`) rather than referenced by name from `config.toml` — the workflow engine has no data-driven stage graph today, so wiring arbitrary named stages into arbitrary positions would need a larger config-driven rework. Auto-run-in-order covers the PRD's actual use case (a repo-defined pre-flight/setup hook) without it.
|
||||
|
||||
### Phase 3: Skill scripts
|
||||
- Skills can ship `scripts/*.go` alongside shell scripts
|
||||
- archie-core evaluates them via Yaegi when a skill's instructions reference them
|
||||
- Stdout from the script is returned to the agent as tool output
|
||||
### Phase 3: Skill scripts — implemented
|
||||
- `internal/skillscript.Run` interprets a `.go` file via `i.EvalPath`, which (like `go run`) evaluates and calls its `main()`; stdout/stderr are captured via `interp.Options`
|
||||
- Uses `stdlib.Symbols` + `stdlib/unrestricted.Symbols` (not just `stdlib`) — `os/exec` lives in the unrestricted set, and the PRD's own example script shells out via `os/exec`
|
||||
- No archie-core-specific symbol table needed here — skill scripts only touch the Go standard library
|
||||
- Exposed to the agent loop as a new `run_go_script` tool (`internal/agentexec/inprocess.go`), available in every agent stage; path is validated to stay inside the workspace
|
||||
- This is how "the skill's instructions reference a script" cashes out concretely: the agent calls `run_go_script` with the path instead of needing a Go toolchain in the sandbox
|
||||
|
||||
### Phase 4: Hot reload
|
||||
- Watch `.archie/` for changes during daemon runtime
|
||||
- Reload gate functions without restarting the daemon
|
||||
- (Only matters for long-running daemons — archie-core currently fresh-clones per task, so phase 1 covers the common case)
|
||||
### Phase 4: Hot reload — not needed, by construction
|
||||
- All three loaders (`gate.Evaluate`, `wfeval.Discover`, `skillscript.Run`) read their `.go` source from disk on every call — no in-memory cache exists anywhere in the implementation
|
||||
- Every task additionally gets a fresh `git clone` (`worktree.Manager.Prepare` removes and re-clones the worktree directory per task)
|
||||
- Consequently every stage already re-reads `.archie/gate.go`, `.archie/stages/*.go`, and skill scripts fresh, every run — there is no stale state a file watcher would ever need to invalidate
|
||||
- A file-watching daemon-runtime reload mechanism would add machinery with nothing to do given this architecture; revisit only if the daemon starts reusing long-lived worktrees across tasks
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ require (
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
require github.com/samcharles93/ai-sdk v0.1.17
|
||||
require (
|
||||
github.com/samcharles93/ai-sdk v0.1.17
|
||||
github.com/traefik/yaegi v0.16.1
|
||||
)
|
||||
|
||||
replace github.com/samcharles93/ai-sdk => /work/projects/ai-sdk
|
||||
@@ -23,6 +23,8 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
|
||||
@@ -5,12 +5,15 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agentloop"
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/skillscript"
|
||||
)
|
||||
|
||||
// Runner executes one autonomous stage against an already prepared workspace.
|
||||
@@ -58,7 +61,7 @@ func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request
|
||||
Budget: agentloop.Budget(req.Budget),
|
||||
ReadOnly: req.ReadOnly,
|
||||
ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly),
|
||||
Extra: captureToolSet(req.CaptureTools, captures),
|
||||
Extra: mergeToolSets(captureToolSet(req.CaptureTools, captures), scriptToolSet(workspace)),
|
||||
Logger: r.logger(req),
|
||||
})
|
||||
result := Result{
|
||||
@@ -169,6 +172,50 @@ func captureToolSet(specs []CaptureTool, captures map[string][]json.RawMessage)
|
||||
return tools
|
||||
}
|
||||
|
||||
// scriptToolSet exposes run_go_script: interpreting a Yaegi Go script
|
||||
// bundled with a skill (.archie/skills/<skill>/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
|
||||
// toolchain in the sandbox.
|
||||
func scriptToolSet(workspace string) core.ToolSet {
|
||||
const params = `{"type":"object","properties":{"path":{"type":"string","description":"Path to the .go script, relative to the workspace root."}},"required":["path"]}`
|
||||
return core.ToolSet{
|
||||
"run_go_script": core.NewTool(
|
||||
"run_go_script",
|
||||
"Run a Yaegi-interpreted Go script (e.g. a skill's bundled scripts/*.go helper) and return everything it printed.",
|
||||
json.RawMessage(params),
|
||||
func(_ context.Context, input string) (string, error) {
|
||||
var args struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(input), &args); err != nil || strings.TrimSpace(args.Path) == "" {
|
||||
return "run_go_script rejected: arguments must be a JSON object with a non-empty path field", nil
|
||||
}
|
||||
full := filepath.Join(workspace, args.Path)
|
||||
if rel, err := filepath.Rel(workspace, full); err != nil || strings.HasPrefix(rel, "..") {
|
||||
return "run_go_script rejected: path escapes the workspace", nil
|
||||
}
|
||||
out, err := skillscript.Run(full)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("run_go_script failed: %v\n%s", err, out), nil
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// mergeToolSets combines tool sets into one; later sets win on name
|
||||
// collisions.
|
||||
func mergeToolSets(sets ...core.ToolSet) core.ToolSet {
|
||||
merged := core.ToolSet{}
|
||||
for _, set := range sets {
|
||||
maps.Copy(merged, set)
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
type memoryNotes struct {
|
||||
initial string
|
||||
appended []string
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agentloop"
|
||||
@@ -94,6 +96,65 @@ func TestCaptureToolRejectsWrongFieldTypeBeforeRecording(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptToolRunsAGoScriptAndReturnsItsOutput(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(workspace, "scripts"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := "package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"hi from a script\") }\n"
|
||||
if err := os.WriteFile(filepath.Join(workspace, "scripts", "hello.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tool := scriptToolSet(workspace)["run_go_script"]
|
||||
out, err := tool.Execute(context.Background(), `{"path":"scripts/hello.go"}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "hi from a script\n" {
|
||||
t.Fatalf("run_go_script output = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptToolRejectsPathsEscapingTheWorkspace(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
tool := scriptToolSet(workspace)["run_go_script"]
|
||||
out, err := tool.Execute(context.Background(), `{"path":"../outside.go"}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "run_go_script rejected: path escapes the workspace" {
|
||||
t.Fatalf("run_go_script output = %q, want a workspace-escape rejection", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScriptToolRejectsMissingPath(t *testing.T) {
|
||||
tool := scriptToolSet(t.TempDir())["run_go_script"]
|
||||
out, err := tool.Execute(context.Background(), `{}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "run_go_script rejected: arguments must be a JSON object with a non-empty path field" {
|
||||
t.Fatalf("run_go_script output = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeToolSetsLaterWinsOnCollision(t *testing.T) {
|
||||
first := scriptToolSet(t.TempDir())
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
second := captureToolSet([]CaptureTool{{Name: "run_go_script"}}, captures)
|
||||
merged := mergeToolSets(first, second)
|
||||
if len(merged) != 1 {
|
||||
t.Fatalf("merged = %v, want exactly one tool", merged)
|
||||
}
|
||||
if _, err := merged["run_go_script"].Execute(context.Background(), `{}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(captures["run_go_script"]) != 1 {
|
||||
t.Fatalf("expected the capture tool (second set) to win, captures = %v", captures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
@@ -34,6 +34,11 @@ type Daemon struct {
|
||||
Bus *events.Bus
|
||||
Workflows workflow.Registry
|
||||
Log *slog.Logger
|
||||
// CustomStages discovers a repo's per-repo Yaegi custom stages
|
||||
// (.archie/stages/*.go) from its prepared worktree. Set by the
|
||||
// composition root (cmd/archied) to wfeval.Discover; nil disables
|
||||
// discovery.
|
||||
CustomStages func(dir string) ([]workflow.Stage, error)
|
||||
}
|
||||
|
||||
// emit publishes an observability event; safe on a nil bus.
|
||||
@@ -358,15 +363,16 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
d.Log.Info("processing task", "repo", repo.FullName(), "issue", task.IssueNumber, "workflow", wf.Name, "attempt", task.Attempt)
|
||||
d.Forge.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues())
|
||||
workflow.Run(ctx, wf, &workflow.TaskContext{
|
||||
Task: task,
|
||||
Repo: repo,
|
||||
Cfg: d.Cfg,
|
||||
Forge: d.Forge,
|
||||
Store: d.Store,
|
||||
Trees: d.Trees,
|
||||
Agent: d.Agent,
|
||||
Bus: d.Bus,
|
||||
Log: d.Log,
|
||||
Task: task,
|
||||
Repo: repo,
|
||||
Cfg: d.Cfg,
|
||||
Forge: d.Forge,
|
||||
Store: d.Store,
|
||||
Trees: d.Trees,
|
||||
Agent: d.Agent,
|
||||
Bus: d.Bus,
|
||||
Log: d.Log,
|
||||
CustomStages: d.CustomStages,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Package gate defines the runtime-evaluated custom gate surface: a
|
||||
// per-repo .archie/gate.go, interpreted via Yaegi after the shell-based
|
||||
// gate passes, that inspects the diff and worktree for project-specific
|
||||
// rules shell commands can't express (AST checks, diff scanning, and
|
||||
// the like).
|
||||
package gate
|
||||
|
||||
// GateContext carries everything a custom gate function can inspect.
|
||||
type GateContext struct {
|
||||
// Diff is the unified diff of all changes against BaseRef.
|
||||
Diff string
|
||||
// ChangedFiles lists changed file paths, repo-relative.
|
||||
ChangedFiles []string
|
||||
// Dir is the absolute worktree path.
|
||||
Dir string
|
||||
// BaseRef is the base branch the diff is against (e.g. "origin/main").
|
||||
BaseRef string
|
||||
// Repo is "owner/name".
|
||||
Repo string
|
||||
}
|
||||
|
||||
// Finding is one gate violation.
|
||||
type Finding struct {
|
||||
// Level is "error" (blocks the gate) or "warn" (advisory, logged only).
|
||||
Level string
|
||||
// File is the optional file path the finding applies to.
|
||||
File string
|
||||
// Line is the optional line number within File.
|
||||
Line int
|
||||
Message string
|
||||
}
|
||||
|
||||
// Blocking reports whether any finding has Level "error".
|
||||
func Blocking(findings []Finding) bool {
|
||||
for _, f := range findings {
|
||||
if f.Level == "error" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Package gateeval evaluates a repo's .archie/gate.go via Yaegi. Split
|
||||
// from internal/gate (which only declares the GateContext/Finding types)
|
||||
// because the generated symbol table in gateextract imports internal/gate —
|
||||
// this package sits above both to avoid the resulting import cycle.
|
||||
package gateeval
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
"github.com/samcharles93/archie-core/internal/gate/gateextract"
|
||||
)
|
||||
|
||||
// scriptPath is the per-repo custom gate script, relative to the
|
||||
// worktree root.
|
||||
const scriptPath = ".archie/gate.go"
|
||||
|
||||
// Evaluate loads and runs the repo's .archie/gate.go against gctx. A
|
||||
// missing script is not an error — it returns (nil, nil), meaning no
|
||||
// custom gate is configured for this repo. The script runs in-process
|
||||
// (interpreted, not sandboxed), so a panic inside it — nil dereference,
|
||||
// out-of-range index — is recovered and returned as an error rather than
|
||||
// taking down the daemon.
|
||||
func Evaluate(gctx gate.GateContext) (findings []gate.Finding, err error) {
|
||||
src, err := os.ReadFile(filepath.Join(gctx.Dir, scriptPath))
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("read %s: %w", scriptPath, err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
findings, err = nil, fmt.Errorf("yaegi: %s panicked: %v", scriptPath, r)
|
||||
}
|
||||
}()
|
||||
|
||||
i := interp.New(interp.Options{})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
if err := i.Use(gateextract.Symbols); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: load gate symbols: %w", err)
|
||||
}
|
||||
|
||||
if _, err := i.Eval(string(src)); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: evaluate %s: %w", scriptPath, err)
|
||||
}
|
||||
|
||||
v, err := i.Eval("gate.Check")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("yaegi: %s does not export func Check(GateContext) []Finding: %w", scriptPath, err)
|
||||
}
|
||||
check, ok := v.Interface().(func(gate.GateContext) []gate.Finding)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("yaegi: %s Check has the wrong signature (want func(gate.GateContext) []gate.Finding)", scriptPath)
|
||||
}
|
||||
|
||||
return check(gctx), nil
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package gateeval
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
)
|
||||
|
||||
func writeGateScript(t *testing.T, dir, src string) {
|
||||
t.Helper()
|
||||
archieDir := filepath.Join(dir, ".archie")
|
||||
if err := os.MkdirAll(archieDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(archieDir, "gate.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateNoScript(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
findings, err := Evaluate(gate.GateContext{Dir: dir})
|
||||
if err != nil {
|
||||
t.Fatalf("Evaluate() error = %v, want nil (no script configured)", err)
|
||||
}
|
||||
if findings != nil {
|
||||
t.Fatalf("Evaluate() findings = %v, want nil", findings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateFindings(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeGateScript(t, dir, `package gate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
)
|
||||
|
||||
func Check(ctx gate.GateContext) []gate.Finding {
|
||||
var findings []gate.Finding
|
||||
for _, line := range strings.Split(ctx.Diff, "\n") {
|
||||
if strings.HasPrefix(line, "+") && strings.Contains(line, "panic(") {
|
||||
findings = append(findings, gate.Finding{Level: "error", Message: "new panic() call"})
|
||||
}
|
||||
}
|
||||
for _, f := range ctx.ChangedFiles {
|
||||
if strings.HasSuffix(f, ".md") {
|
||||
findings = append(findings, gate.Finding{Level: "warn", File: f, Message: "markdown change — no build impact"})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
`)
|
||||
|
||||
findings, err := Evaluate(gate.GateContext{
|
||||
Dir: dir,
|
||||
Diff: "+panic(\"boom\")\n",
|
||||
ChangedFiles: []string{"README.md"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Evaluate() error = %v", err)
|
||||
}
|
||||
if len(findings) != 2 {
|
||||
t.Fatalf("Evaluate() findings = %#v, want 2 findings", findings)
|
||||
}
|
||||
if findings[0].Level != "error" || findings[0].Message != "new panic() call" {
|
||||
t.Errorf("findings[0] = %#v, want the panic error finding", findings[0])
|
||||
}
|
||||
if findings[1].Level != "warn" || findings[1].File != "README.md" {
|
||||
t.Errorf("findings[1] = %#v, want the markdown warn finding", findings[1])
|
||||
}
|
||||
if !gate.Blocking(findings) {
|
||||
t.Error("Blocking(findings) = false, want true (an error-level finding is present)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateClean(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeGateScript(t, dir, `package gate
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/gate"
|
||||
|
||||
func Check(ctx gate.GateContext) []gate.Finding {
|
||||
return nil
|
||||
}
|
||||
`)
|
||||
|
||||
findings, err := Evaluate(gate.GateContext{Dir: dir})
|
||||
if err != nil {
|
||||
t.Fatalf("Evaluate() error = %v", err)
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
t.Fatalf("Evaluate() findings = %#v, want none", findings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluatePanicRecovered(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeGateScript(t, dir, `package gate
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/gate"
|
||||
|
||||
func Check(ctx gate.GateContext) []gate.Finding {
|
||||
var files []string
|
||||
return []gate.Finding{{Message: files[5]}}
|
||||
}
|
||||
`)
|
||||
|
||||
_, err := Evaluate(gate.GateContext{Dir: dir})
|
||||
if err == nil {
|
||||
t.Fatal("Evaluate() error = nil, want a recovered-panic error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateBadSignature(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeGateScript(t, dir, `package gate
|
||||
|
||||
func Check(s string) string {
|
||||
return s
|
||||
}
|
||||
`)
|
||||
|
||||
_, err := Evaluate(gate.GateContext{Dir: dir})
|
||||
if err == nil {
|
||||
t.Fatal("Evaluate() error = nil, want a signature mismatch error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateSyntaxError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeGateScript(t, dir, `package gate
|
||||
|
||||
func Check( {{{
|
||||
`)
|
||||
|
||||
_, err := Evaluate(gate.GateContext{Dir: dir})
|
||||
if err == nil {
|
||||
t.Fatal("Evaluate() error = nil, want a parse error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Package gateextract holds the Yaegi symbol table for internal/gate,
|
||||
// generated by `go generate`. Kept separate from internal/gate itself so
|
||||
// the generated file can import it without a self-import cycle.
|
||||
package gateextract
|
||||
|
||||
import "reflect"
|
||||
|
||||
//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name gateextract github.com/samcharles93/archie-core/internal/gate
|
||||
|
||||
var Symbols = map[string]map[string]reflect.Value{}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Code generated by 'yaegi extract github.com/samcharles93/archie-core/internal/gate'. DO NOT EDIT.
|
||||
|
||||
package gateextract
|
||||
|
||||
import (
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Symbols["github.com/samcharles93/archie-core/internal/gate/gate"] = map[string]reflect.Value{
|
||||
// function, constant and variable definitions
|
||||
"Blocking": reflect.ValueOf(gate.Blocking),
|
||||
|
||||
// type definitions
|
||||
"Finding": reflect.ValueOf((*gate.Finding)(nil)),
|
||||
"GateContext": reflect.ValueOf((*gate.GateContext)(nil)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package skillscript runs skill-bundled Go scripts (.archie/skills/<skill>/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
|
||||
// archie-core-specific symbol table is required here.
|
||||
package skillscript
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
"github.com/traefik/yaegi/stdlib/unrestricted"
|
||||
)
|
||||
|
||||
// Run interprets the Go script at path and executes its main function,
|
||||
// returning everything it wrote to stdout and stderr. The script runs
|
||||
// in-process (interpreted, not sandboxed) with unrestricted symbols
|
||||
// (os/exec included — these scripts wrap external tools the way a shell
|
||||
// script would), so a panic inside it is recovered and returned as an
|
||||
// error rather than taking down the daemon.
|
||||
func Run(path string) (output string, err error) {
|
||||
if _, statErr := os.Stat(path); statErr != nil {
|
||||
return "", statErr
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("yaegi: %s panicked: %v", path, r)
|
||||
}
|
||||
}()
|
||||
|
||||
var buf bytes.Buffer
|
||||
i := interp.New(interp.Options{Stdout: &buf, Stderr: &buf})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return "", fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
if err := i.Use(unrestricted.Symbols); err != nil {
|
||||
return "", fmt.Errorf("yaegi: load unrestricted symbols: %w", err)
|
||||
}
|
||||
|
||||
// EvalPath treats a package-main source file the way `go run` does:
|
||||
// evaluating it executes its main() directly. Unlike `go build`, it
|
||||
// does not complain about a missing main() — such a script simply
|
||||
// produces no output.
|
||||
if _, err := i.EvalPath(path); err != nil {
|
||||
return "", fmt.Errorf("yaegi: run %s: %w", path, err)
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package skillscript
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeScript(t *testing.T, src string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "script.go")
|
||||
if err := os.WriteFile(path, []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestRunCapturesStdout(t *testing.T) {
|
||||
path := writeScript(t, `package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("hello from a skill script")
|
||||
}
|
||||
`)
|
||||
out, err := Run(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
if out != "hello from a skill script\n" {
|
||||
t.Fatalf("Run() = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunWrapsExternalCommand(t *testing.T) {
|
||||
path := writeScript(t, `package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func main() {
|
||||
out, _ := exec.Command("echo", "wrapped").CombinedOutput()
|
||||
fmt.Print(string(out))
|
||||
}
|
||||
`)
|
||||
out, err := Run(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
if out != "wrapped\n" {
|
||||
t.Fatalf("Run() = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPanicRecovered(t *testing.T) {
|
||||
path := writeScript(t, `package main
|
||||
|
||||
func main() {
|
||||
var files []string
|
||||
_ = files[5]
|
||||
}
|
||||
`)
|
||||
if _, err := Run(path); err == nil {
|
||||
t.Fatal("Run() error = nil, want a recovered-panic error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunMissingMain(t *testing.T) {
|
||||
// Yaegi's EvalPath, like `go build` without `go run`, doesn't
|
||||
// complain about a missing main() — it just never gets called.
|
||||
path := writeScript(t, `package main
|
||||
|
||||
func notMain() {}
|
||||
`)
|
||||
out, err := Run(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
if out != "" {
|
||||
t.Fatalf("Run() = %q, want empty output (main was never called)", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunMissingFile(t *testing.T) {
|
||||
if _, err := Run(filepath.Join(t.TempDir(), "missing.go")); err == nil {
|
||||
t.Fatal("Run() error = nil, want an error for a missing file")
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ func Implement() Workflow {
|
||||
Name: "implement",
|
||||
Stages: []Stage{
|
||||
StagePrepareWorktree(),
|
||||
StageRepoStages(),
|
||||
StageBaselineGate(),
|
||||
|
||||
AgentStage{
|
||||
@@ -99,6 +100,7 @@ func Implement() Workflow {
|
||||
StageCommitPush(func(tc *TaskContext) string {
|
||||
return fmt.Sprintf("%s (archie)\n\nImplements #%d", tc.Task.Title, tc.Task.IssueNumber)
|
||||
}),
|
||||
StageYaegiGate(),
|
||||
StageDiffCap(),
|
||||
StageOpenPR(func(tc *TaskContext) string {
|
||||
return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %d tokens*\n\nCloses #%d",
|
||||
|
||||
@@ -5,8 +5,11 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
"github.com/samcharles93/archie-core/internal/gate/gateeval"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
@@ -73,6 +76,80 @@ func StageDiffCap() Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
// StageRepoStages runs every custom stage the repo defines under
|
||||
// .archie/stages/*.go (Yaegi-interpreted via TaskContext.CustomStages),
|
||||
// in the order the loader returns them — a no-op when no loader is wired
|
||||
// up or the repo defines none. A custom stage that sets tc.Outcome ends
|
||||
// the workflow there, same as any built-in stage.
|
||||
func StageRepoStages() Stage {
|
||||
return Stage{Name: "repo-stages", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.CustomStages == nil {
|
||||
return nil
|
||||
}
|
||||
stages, err := tc.CustomStages(tc.Dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("repo stages: %w", err)
|
||||
}
|
||||
for _, s := range stages {
|
||||
tc.Log.Info("repo stage starting", "stage", s.Name)
|
||||
if err := s.Run(ctx, tc); err != nil {
|
||||
return fmt.Errorf("repo stage %s: %w", s.Name, err)
|
||||
}
|
||||
if tc.Outcome.Status != "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// StageYaegiGate evaluates the repo's optional .archie/gate.go — a
|
||||
// Yaegi-interpreted Go file inspecting the committed diff for
|
||||
// project-specific rules shell gate commands can't express (AST checks,
|
||||
// diff scanning). A missing script is a no-op. Error-level findings
|
||||
// park the task; warn-level findings are logged only.
|
||||
func StageYaegiGate() Stage {
|
||||
return Stage{Name: "custom-gate", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
base := tc.Repo.BaseBranch()
|
||||
diff, err := tc.Trees.Diff(ctx, tc.Dir, base)
|
||||
if err != nil {
|
||||
return fmt.Errorf("custom gate: diff against %s: %w", base, err)
|
||||
}
|
||||
files, err := tc.Trees.ChangedFiles(ctx, tc.Dir, base)
|
||||
if err != nil {
|
||||
return fmt.Errorf("custom gate: changed files against %s: %w", base, err)
|
||||
}
|
||||
|
||||
findings, err := gateeval.Evaluate(gate.GateContext{
|
||||
Diff: diff,
|
||||
ChangedFiles: files,
|
||||
Dir: tc.Dir,
|
||||
BaseRef: "origin/" + base,
|
||||
Repo: tc.Repo.FullName(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("custom gate: %w", err)
|
||||
}
|
||||
|
||||
var blocking []string
|
||||
for _, f := range findings {
|
||||
loc := f.File
|
||||
if f.Line > 0 {
|
||||
loc = fmt.Sprintf("%s:%d", f.File, f.Line)
|
||||
}
|
||||
msg := strings.TrimSpace(loc + ": " + f.Message)
|
||||
if f.Level == "error" {
|
||||
blocking = append(blocking, msg)
|
||||
}
|
||||
tc.Log.Info("custom gate finding", "level", f.Level, "file", f.File, "line", f.Line, "message", f.Message)
|
||||
}
|
||||
if len(blocking) > 0 {
|
||||
return fmt.Errorf("custom gate: %s", strings.Join(blocking, "; "))
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
|
||||
// OpenPR opens the task's pull request, records its number, and sets
|
||||
// the terminal pr_open outcome. Stages that need to act after the PR
|
||||
// exists (e.g. posting evidence comments) call this and then do so in
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
// runGit runs git in dir, failing the test on error.
|
||||
func runGit(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// gitRepoWithOriginRef creates a repo with a base commit, then labels
|
||||
// that commit "origin/<base>" (a plain local branch standing in for a
|
||||
// remote-tracking ref) so Manager.Diff/ChangedFiles — which always diff
|
||||
// against "origin/<base>" — resolve without a real clone/push round trip.
|
||||
func gitRepoWithOriginRef(t *testing.T, base string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
runGit(t, dir, "init", "-b", base)
|
||||
runGit(t, dir, "config", "user.name", "archie-bot")
|
||||
runGit(t, dir, "config", "user.email", "archie-bot@example.com")
|
||||
if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("seed\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, dir, "add", "-A")
|
||||
runGit(t, dir, "commit", "-m", "seed")
|
||||
runGit(t, dir, "branch", "origin/"+base, base)
|
||||
return dir
|
||||
}
|
||||
|
||||
func newYaegiGateTaskContext(t *testing.T, dir string) *TaskContext {
|
||||
t.Helper()
|
||||
return &TaskContext{
|
||||
Task: &store.Task{ID: 1, Owner: "sam", Repo: "todo", IssueNumber: 42},
|
||||
Repo: config.Repo{Owner: "sam", Name: "todo", Base: "main"},
|
||||
Trees: &worktree.Manager{WorkDir: t.TempDir()},
|
||||
Dir: dir,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
}
|
||||
|
||||
func writeGateGo(t *testing.T, dir, src string) {
|
||||
t.Helper()
|
||||
archieDir := filepath.Join(dir, ".archie")
|
||||
if err := os.MkdirAll(archieDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(archieDir, "gate.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageYaegiGateNoScriptIsNoop(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
dir := gitRepoWithOriginRef(t, "main")
|
||||
tc := newYaegiGateTaskContext(t, dir)
|
||||
|
||||
if err := StageYaegiGate().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("StageYaegiGate() = %v, want nil (no .archie/gate.go)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageYaegiGateBlocksOnErrorFinding(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
dir := gitRepoWithOriginRef(t, "main")
|
||||
writeGateGo(t, dir, `package gate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
)
|
||||
|
||||
func Check(ctx gate.GateContext) []gate.Finding {
|
||||
var findings []gate.Finding
|
||||
for _, line := range strings.Split(ctx.Diff, "\n") {
|
||||
if strings.HasPrefix(line, "+") && strings.Contains(line, "panic(") {
|
||||
findings = append(findings, gate.Finding{Level: "error", Message: "new panic() call"})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
}
|
||||
`)
|
||||
if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main\n\nfunc main() { panic(\"boom\") }\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, dir, "add", "-A")
|
||||
runGit(t, dir, "commit", "-m", "add panic")
|
||||
|
||||
tc := newYaegiGateTaskContext(t, dir)
|
||||
err := StageYaegiGate().Run(context.Background(), tc)
|
||||
if err == nil {
|
||||
t.Fatal("StageYaegiGate() = nil, want an error for the blocking finding")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageYaegiGateAllowsWarnFinding(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
dir := gitRepoWithOriginRef(t, "main")
|
||||
writeGateGo(t, dir, `package gate
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/gate"
|
||||
|
||||
func Check(ctx gate.GateContext) []gate.Finding {
|
||||
return []gate.Finding{{Level: "warn", Message: "advisory only"}}
|
||||
}
|
||||
`)
|
||||
if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("hi\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, dir, "add", "-A")
|
||||
runGit(t, dir, "commit", "-m", "add notes")
|
||||
|
||||
tc := newYaegiGateTaskContext(t, dir)
|
||||
if err := StageYaegiGate().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("StageYaegiGate() = %v, want nil (warn findings don't block)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRepoStagesNilLoaderIsNoop(t *testing.T) {
|
||||
tc := &TaskContext{Log: slog.New(slog.DiscardHandler)}
|
||||
if err := StageRepoStages().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("StageRepoStages() = %v, want nil (no loader wired up)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRepoStagesRunsAllInOrder(t *testing.T) {
|
||||
var ran []string
|
||||
tc := &TaskContext{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
CustomStages: func(string) ([]Stage, error) {
|
||||
return []Stage{
|
||||
{Name: "first", Run: func(context.Context, *TaskContext) error { ran = append(ran, "first"); return nil }},
|
||||
{Name: "second", Run: func(context.Context, *TaskContext) error { ran = append(ran, "second"); return nil }},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
if err := StageRepoStages().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("StageRepoStages() = %v", err)
|
||||
}
|
||||
if len(ran) != 2 || ran[0] != "first" || ran[1] != "second" {
|
||||
t.Fatalf("ran = %v, want [first second]", ran)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRepoStagesStopsOnOutcome(t *testing.T) {
|
||||
var ran []string
|
||||
tc := &TaskContext{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
CustomStages: func(string) ([]Stage, error) {
|
||||
return []Stage{
|
||||
{Name: "first", Run: func(_ context.Context, tc *TaskContext) error {
|
||||
ran = append(ran, "first")
|
||||
tc.Outcome = Outcome{Status: "parked", Detail: "stop here"}
|
||||
return nil
|
||||
}},
|
||||
{Name: "second", Run: func(context.Context, *TaskContext) error { ran = append(ran, "second"); return nil }},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
if err := StageRepoStages().Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("StageRepoStages() = %v", err)
|
||||
}
|
||||
if len(ran) != 1 || ran[0] != "first" {
|
||||
t.Fatalf("ran = %v, want only [first] (second stage should not run after an outcome is set)", ran)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageRepoStagesPropagatesLoaderError(t *testing.T) {
|
||||
tc := &TaskContext{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
CustomStages: func(string) ([]Stage, error) {
|
||||
return nil, errors.New("boom")
|
||||
},
|
||||
}
|
||||
if err := StageRepoStages().Run(context.Background(), tc); err == nil {
|
||||
t.Fatal("StageRepoStages() = nil, want the loader's error propagated")
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ func TDD() Workflow {
|
||||
Name: "tdd",
|
||||
Stages: []Stage{
|
||||
StagePrepareWorktree(),
|
||||
StageRepoStages(),
|
||||
StageBaselineGate(),
|
||||
|
||||
AgentStage{
|
||||
@@ -124,6 +125,7 @@ func TDD() Workflow {
|
||||
StageCommitPush(func(tc *TaskContext) string {
|
||||
return fmt.Sprintf("fix: %s (archie)\n\nFixes #%d", tc.Task.Title, tc.Task.IssueNumber)
|
||||
}),
|
||||
StageYaegiGate(),
|
||||
StageDiffCap(),
|
||||
|
||||
// Open the PR, then post the captured failing-test output as
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// Package wfeval discovers and interprets a repo's custom workflow
|
||||
// stages: .archie/stages/*.go files, each exporting a Stage() function
|
||||
// that returns a workflow.Stage. Split from internal/workflow (and its
|
||||
// generated symbol table in wfextract) to avoid the import cycle that
|
||||
// would result from workflow depending on its own extracted symbols.
|
||||
package wfeval
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/workflow/wfextract"
|
||||
)
|
||||
|
||||
// stagesDir is where a repo's custom stage scripts live, relative to
|
||||
// the worktree root.
|
||||
const stagesDir = ".archie/stages"
|
||||
|
||||
// Discover loads every .archie/stages/*.go file in dir and returns the
|
||||
// workflow.Stage each exports, in filename order. A missing directory is
|
||||
// not an error — it returns (nil, nil), meaning no custom stages are
|
||||
// configured for this repo.
|
||||
func Discover(dir string) ([]workflow.Stage, error) {
|
||||
entries, err := os.ReadDir(filepath.Join(dir, stagesDir))
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("read %s: %w", stagesDir, err)
|
||||
}
|
||||
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && filepath.Ext(e.Name()) == ".go" {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
stages := make([]workflow.Stage, 0, len(names))
|
||||
for _, name := range names {
|
||||
stage, err := loadStage(filepath.Join(dir, stagesDir, name))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", filepath.Join(stagesDir, name), err)
|
||||
}
|
||||
stages = append(stages, stage)
|
||||
}
|
||||
return stages, nil
|
||||
}
|
||||
|
||||
// loadStage interprets one custom stage script and calls its exported
|
||||
// Stage() function. The script runs in-process (interpreted, not
|
||||
// sandboxed), so a panic inside it is recovered and returned as an error
|
||||
// rather than taking down the daemon.
|
||||
func loadStage(path string) (stage workflow.Stage, err error) {
|
||||
src, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return workflow.Stage{}, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
stage, err = workflow.Stage{}, fmt.Errorf("panicked: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
i := interp.New(interp.Options{})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
if err := i.Use(wfextract.Symbols); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: load workflow symbols: %w", err)
|
||||
}
|
||||
|
||||
if _, err := i.Eval(string(src)); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: evaluate: %w", err)
|
||||
}
|
||||
|
||||
v, err := i.Eval("stages.Stage")
|
||||
if err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: does not export func Stage() workflow.Stage: %w", err)
|
||||
}
|
||||
factory, ok := v.Interface().(func() workflow.Stage)
|
||||
if !ok {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: Stage has the wrong signature (want func() workflow.Stage)")
|
||||
}
|
||||
|
||||
return factory(), nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package wfeval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
)
|
||||
|
||||
func writeStageScript(t *testing.T, dir, name, src string) {
|
||||
t.Helper()
|
||||
stagesDir := filepath.Join(dir, ".archie", "stages")
|
||||
if err := os.MkdirAll(stagesDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(stagesDir, name), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverNoStagesDir(t *testing.T) {
|
||||
stages, err := Discover(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("Discover() error = %v, want nil (no .archie/stages)", err)
|
||||
}
|
||||
if stages != nil {
|
||||
t.Fatalf("Discover() = %v, want nil", stages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverRunsStagesInFilenameOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeStageScript(t, dir, "b-second.go", `package stages
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
)
|
||||
|
||||
func Stage() workflow.Stage {
|
||||
return workflow.Stage{Name: "second", Run: func(ctx context.Context, tc *workflow.TaskContext) error {
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
`)
|
||||
writeStageScript(t, dir, "a-first.go", `package stages
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
)
|
||||
|
||||
func Stage() workflow.Stage {
|
||||
return workflow.Stage{Name: "first", Run: func(ctx context.Context, tc *workflow.TaskContext) error {
|
||||
return nil
|
||||
}}
|
||||
}
|
||||
`)
|
||||
|
||||
stages, err := Discover(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Discover() error = %v", err)
|
||||
}
|
||||
if len(stages) != 2 {
|
||||
t.Fatalf("Discover() = %#v, want 2 stages", stages)
|
||||
}
|
||||
if stages[0].Name != "first" || stages[1].Name != "second" {
|
||||
t.Fatalf("Discover() order = [%s, %s], want [first, second]", stages[0].Name, stages[1].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverStageRuns(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeStageScript(t, dir, "touch.go", `package stages
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
)
|
||||
|
||||
func Stage() workflow.Stage {
|
||||
return workflow.Stage{Name: "touch", Run: func(ctx context.Context, tc *workflow.TaskContext) error {
|
||||
return os.WriteFile(filepath.Join(tc.Dir, "touched.txt"), []byte("hi\n"), 0o644)
|
||||
}}
|
||||
}
|
||||
`)
|
||||
stages, err := Discover(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("Discover() error = %v", err)
|
||||
}
|
||||
if len(stages) != 1 {
|
||||
t.Fatalf("Discover() = %#v, want 1 stage", stages)
|
||||
}
|
||||
|
||||
tc := &workflow.TaskContext{Dir: dir}
|
||||
if err := stages[0].Run(context.Background(), tc); err != nil {
|
||||
t.Fatalf("stage.Run() error = %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "touched.txt")); err != nil {
|
||||
t.Fatalf("stage did not run: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverBadSignature(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeStageScript(t, dir, "bad.go", `package stages
|
||||
|
||||
func Stage() string {
|
||||
return "not a workflow.Stage"
|
||||
}
|
||||
`)
|
||||
if _, err := Discover(dir); err == nil {
|
||||
t.Fatal("Discover() error = nil, want a signature mismatch error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverPanicRecovered(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeStageScript(t, dir, "panics.go", `package stages
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/workflow"
|
||||
|
||||
func Stage() workflow.Stage {
|
||||
var files []string
|
||||
_ = files[5]
|
||||
return workflow.Stage{}
|
||||
}
|
||||
`)
|
||||
if _, err := Discover(dir); err == nil {
|
||||
t.Fatal("Discover() error = nil, want a recovered-panic error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Code generated by 'yaegi extract github.com/samcharles93/archie-core/internal/workflow'. DO NOT EDIT.
|
||||
|
||||
package wfextract
|
||||
|
||||
import (
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Symbols["github.com/samcharles93/archie-core/internal/workflow/workflow"] = map[string]reflect.Value{
|
||||
// function, constant and variable definitions
|
||||
"Bootstrap": reflect.ValueOf(workflow.Bootstrap),
|
||||
"Feasibility": reflect.ValueOf(workflow.Feasibility),
|
||||
"GateFromRepo": reflect.ValueOf(workflow.GateFromRepo),
|
||||
"Implement": reflect.ValueOf(workflow.Implement),
|
||||
"OpenPR": reflect.ValueOf(workflow.OpenPR),
|
||||
"Route": reflect.ValueOf(workflow.Route),
|
||||
"Run": reflect.ValueOf(workflow.Run),
|
||||
"StageBaselineGate": reflect.ValueOf(workflow.StageBaselineGate),
|
||||
"StageCommit": reflect.ValueOf(workflow.StageCommit),
|
||||
"StageCommitPush": reflect.ValueOf(workflow.StageCommitPush),
|
||||
"StageDiffCap": reflect.ValueOf(workflow.StageDiffCap),
|
||||
"StageOpenPR": reflect.ValueOf(workflow.StageOpenPR),
|
||||
"StagePrepareWorktree": reflect.ValueOf(workflow.StagePrepareWorktree),
|
||||
"StageRepoStages": reflect.ValueOf(workflow.StageRepoStages),
|
||||
"StageYaegiGate": reflect.ValueOf(workflow.StageYaegiGate),
|
||||
"TDD": reflect.ValueOf(workflow.TDD),
|
||||
|
||||
// type definitions
|
||||
"AgentStage": reflect.ValueOf((*workflow.AgentStage)(nil)),
|
||||
"Outcome": reflect.ValueOf((*workflow.Outcome)(nil)),
|
||||
"Registry": reflect.ValueOf((*workflow.Registry)(nil)),
|
||||
"Stage": reflect.ValueOf((*workflow.Stage)(nil)),
|
||||
"TaskContext": reflect.ValueOf((*workflow.TaskContext)(nil)),
|
||||
"Workflow": reflect.ValueOf((*workflow.Workflow)(nil)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Package wfextract holds the Yaegi symbol table for internal/workflow,
|
||||
// generated by `go generate`. Kept separate from internal/workflow itself
|
||||
// so the generated file can import it without a self-import cycle.
|
||||
package wfextract
|
||||
|
||||
import "reflect"
|
||||
|
||||
//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name wfextract github.com/samcharles93/archie-core/internal/workflow
|
||||
|
||||
var Symbols = map[string]map[string]reflect.Value{}
|
||||
@@ -33,6 +33,14 @@ type TaskContext struct {
|
||||
Agent agentexec.Runner
|
||||
Bus *events.Bus // nil-safe via Emit
|
||||
Log *slog.Logger
|
||||
// CustomStages discovers a repo's per-repo custom stages (Yaegi-
|
||||
// interpreted from .archie/stages/*.go in the given worktree
|
||||
// directory), returning them in the order they should run. Wired up
|
||||
// by the composition root (cmd/archied) — nil disables discovery, so
|
||||
// StageRepoStages is a no-op. Kept as an injected function rather
|
||||
// than a direct import to avoid workflow depending on its own
|
||||
// generated Yaegi symbol table (an import cycle).
|
||||
CustomStages func(dir string) ([]Stage, error)
|
||||
|
||||
// Dir/Branch are set by the prepare step.
|
||||
Dir string
|
||||
|
||||
@@ -149,6 +149,26 @@ func (m *Manager) ChangedLines(ctx context.Context, dir, base string) (int, erro
|
||||
return total - files, nil
|
||||
}
|
||||
|
||||
// Diff returns the unified diff of all committed changes against base.
|
||||
func (m *Manager) Diff(ctx context.Context, dir, base string) (string, error) {
|
||||
return m.git(ctx, dir, "diff", "origin/"+base+"...HEAD")
|
||||
}
|
||||
|
||||
// ChangedFiles lists the repo-relative paths changed against base.
|
||||
func (m *Manager) ChangedFiles(ctx context.Context, dir, base string) ([]string, error) {
|
||||
out, err := m.git(ctx, dir, "diff", "--name-only", "origin/"+base+"...HEAD")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var files []string
|
||||
for line := range strings.SplitSeq(out, "\n") {
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
files = append(files, line)
|
||||
}
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// Cleanup removes a task's worktree (merged/rejected); parked worktrees
|
||||
// are kept for post-mortems.
|
||||
func (m *Manager) Cleanup(owner, repo string, issue int) error {
|
||||
|
||||
@@ -93,6 +93,22 @@ func TestPrepareCommitPushRoundTrip(t *testing.T) {
|
||||
t.Fatalf("ChangedLines = %d, want 2", lines)
|
||||
}
|
||||
|
||||
files, err := m.ChangedFiles(ctx, dir, "main")
|
||||
if err != nil {
|
||||
t.Fatalf("ChangedFiles: %v", err)
|
||||
}
|
||||
if len(files) != 1 || files[0] != "hello.txt" {
|
||||
t.Fatalf("ChangedFiles = %v, want [hello.txt]", files)
|
||||
}
|
||||
|
||||
diff, err := m.Diff(ctx, dir, "main")
|
||||
if err != nil {
|
||||
t.Fatalf("Diff: %v", err)
|
||||
}
|
||||
if !strings.Contains(diff, "+one") || !strings.Contains(diff, "hello.txt") {
|
||||
t.Fatalf("Diff missing expected content: %q", diff)
|
||||
}
|
||||
|
||||
if err := m.Push(ctx, dir, branch); err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user