feat(logging,workflow): daemon log feed and executable workflow registry
Add internal/logging.Feed, a logging-owned bounded replay buffer separate from the persisted task-lifecycle event stream, with a live SSE endpoint. Expose the executable workflow registry (skillbuild.Catalog) including zero-run definitions and their origin (builtin vs. installed skill), not just historical run statistics. Route() now returns an explicit failure workflow for an unknown pre-assigned workflow name instead of silently falling through to label-based routing. Fixes #54
This commit is contained in:
1 parent
472d8d717c
commit
a27d430215
15 files changed
+636
-91
No files matched your search
@@ -0,0 +1,15 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func TestRouteDoesNotSilentlyReplaceAnAdmittedWorkflow(t *testing.T) {
|
||||
task := &store.Task{Workflow: "skill-review"}
|
||||
wf := Route(task, Registry{"implement": Implement()})
|
||||
if wf.Name != "none" || len(wf.Stages) != 1 || wf.Stages[0].Name != "fail" {
|
||||
t.Fatalf("Route() = %#v, want explicit failure workflow", wf)
|
||||
}
|
||||
}
|
||||
@@ -39,11 +39,33 @@ func builtins() workflow.Registry {
|
||||
//
|
||||
// Skills define workflows. Plugins define stages. The daemon composes them.
|
||||
func BuildRegistry(worktree string) (workflow.Registry, error) {
|
||||
reg := builtins()
|
||||
if err := mergeSkillWorkflows(worktree, reg); err != nil {
|
||||
catalog, err := BuildCatalog(worktree)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reg, nil
|
||||
return catalog.Registry, nil
|
||||
}
|
||||
|
||||
// Catalog is the executable workflow registry together with the source that
|
||||
// supplied each definition. The source remains separate from Workflow so
|
||||
// executable stages stay free of dashboard-facing metadata.
|
||||
type Catalog struct {
|
||||
Registry workflow.Registry
|
||||
Origins map[string]string
|
||||
}
|
||||
|
||||
// BuildCatalog constructs the executable registry and records whether each
|
||||
// definition remains bundled or was overridden by an installed skill.
|
||||
func BuildCatalog(worktree string) (Catalog, error) {
|
||||
reg := builtins()
|
||||
origins := make(map[string]string, len(reg))
|
||||
for id := range reg {
|
||||
origins[id] = "builtin"
|
||||
}
|
||||
if err := mergeSkillWorkflows(worktree, reg, origins); err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
return Catalog{Registry: reg, Origins: origins}, nil
|
||||
}
|
||||
|
||||
// SkillWorkflow is the subset of a catalog entry needed to build a
|
||||
@@ -67,7 +89,7 @@ func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry
|
||||
// Copy base -- never mutate the caller's registry.
|
||||
reg := make(workflow.Registry, len(base))
|
||||
maps.Copy(reg, base)
|
||||
if err := mergeSkillWorkflows(worktree, reg); err != nil {
|
||||
if err := mergeSkillWorkflows(worktree, reg, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reg, nil
|
||||
@@ -78,7 +100,7 @@ func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry
|
||||
// result into reg in place. A skill whose workflow has no stages yet
|
||||
// (declared intent, no plugins/ directory) leaves reg's existing entry
|
||||
// (built-in or base) untouched.
|
||||
func mergeSkillWorkflows(worktree string, reg workflow.Registry) error {
|
||||
func mergeSkillWorkflows(worktree string, reg workflow.Registry, origins map[string]string) error {
|
||||
catalog, err := skill.Catalog(worktree)
|
||||
if err != nil {
|
||||
return fmt.Errorf("skill catalog: %w", err)
|
||||
@@ -112,6 +134,9 @@ func mergeSkillWorkflows(worktree string, reg workflow.Registry) error {
|
||||
}
|
||||
seenFromSkill[entry.Workflow] = entry.Dir
|
||||
reg[entry.Workflow] = wf
|
||||
if origins != nil {
|
||||
origins[entry.Workflow] = "skill:" + entry.Dir
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,16 @@ func TestBuildWorkflowMissingSkillReturnsEmptyWorkflow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCatalogMarksBuiltinWorkflowOrigins(t *testing.T) {
|
||||
catalog, err := BuildCatalog(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := catalog.Origins["implement"]; got != "builtin" {
|
||||
t.Errorf("implement origin = %q, want builtin", got)
|
||||
}
|
||||
}
|
||||
|
||||
// ── registry built from skill catalog ────────────────────────────────
|
||||
|
||||
func TestBuildRegistryFromSkillCatalog(t *testing.T) {
|
||||
@@ -192,10 +202,11 @@ Custom implementation workflow.
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reg, err := BuildRegistry(dir)
|
||||
catalog, err := BuildCatalog(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg := catalog.Registry
|
||||
|
||||
// Skill-defined workflows must be present.
|
||||
t.Run("skill-defined workflow is registered", func(t *testing.T) {
|
||||
@@ -220,6 +231,9 @@ Custom implementation workflow.
|
||||
t.Errorf("BuildSummary = %q, want 'greet-plugin-ran'", tc.BuildSummary)
|
||||
}
|
||||
})
|
||||
if got := catalog.Origins["greet"]; got != "skill:archie-wf-greet" {
|
||||
t.Errorf("greet origin = %q, want skill:archie-wf-greet", got)
|
||||
}
|
||||
|
||||
// Skill override of built-in must take precedence.
|
||||
t.Run("skill overrides built-in workflow", func(t *testing.T) {
|
||||
@@ -920,7 +934,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
capture := setSlogCapture(t)
|
||||
|
||||
reg := builtins()
|
||||
if err := mergeSkillWorkflows(dir, reg); err != nil {
|
||||
if err := mergeSkillWorkflows(dir, reg, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1023,7 +1037,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
capture := setSlogCapture(t)
|
||||
|
||||
reg := make(workflow.Registry)
|
||||
if err := mergeSkillWorkflows(dir, reg); err != nil {
|
||||
if err := mergeSkillWorkflows(dir, reg, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
@@ -140,6 +141,47 @@ type Workflow struct {
|
||||
// Registry maps workflow names to definitions.
|
||||
type Registry map[string]Workflow
|
||||
|
||||
// Definition is the operator-safe snapshot of an executable workflow. It
|
||||
// contains only identity and stage order, never executable function values.
|
||||
type Definition struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Origin string `json:"origin"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Stages []string `json:"stages"`
|
||||
}
|
||||
|
||||
// Definitions snapshots a registry deterministically so installed workflows
|
||||
// remain visible even when they have not produced persisted run statistics.
|
||||
func Definitions(reg Registry) []Definition {
|
||||
return DefinitionsWithOrigins(reg, nil)
|
||||
}
|
||||
|
||||
// DefinitionsWithOrigins snapshots a registry with composition-supplied
|
||||
// provenance. Entries absent from origins are conservatively labelled
|
||||
// "registry", which keeps the helper useful for tests and non-catalog callers.
|
||||
func DefinitionsWithOrigins(reg Registry, origins map[string]string) []Definition {
|
||||
ids := make([]string, 0, len(reg))
|
||||
for id := range reg {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
definitions := make([]Definition, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
wf := reg[id]
|
||||
stages := make([]string, 0, len(wf.Stages))
|
||||
for _, stage := range wf.Stages {
|
||||
stages = append(stages, stage.Name)
|
||||
}
|
||||
origin := origins[id]
|
||||
if origin == "" {
|
||||
origin = "registry"
|
||||
}
|
||||
definitions = append(definitions, Definition{ID: id, Name: wf.Name, Origin: origin, Enabled: true, Stages: stages})
|
||||
}
|
||||
return definitions
|
||||
}
|
||||
|
||||
// Route picks the workflow for a task. A pre-assigned workflow wins
|
||||
// (the waiting_human → approved handoff requeues under "implement");
|
||||
// otherwise labels decide, then the default.
|
||||
@@ -148,6 +190,12 @@ func Route(t *store.Task, reg Registry) Workflow {
|
||||
if wf, ok := reg[t.Workflow]; ok {
|
||||
return wf
|
||||
}
|
||||
return Workflow{Name: "none", Stages: []Stage{{
|
||||
Name: "fail",
|
||||
Run: func(context.Context, *TaskContext) error {
|
||||
return fmt.Errorf("requested workflow %q is unavailable", t.Workflow)
|
||||
},
|
||||
}}}
|
||||
}
|
||||
if wf, ok := workflowForLabels(reg, t.Labels); ok {
|
||||
return wf
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// Feed is a logging-owned bounded replay buffer. It is intentionally separate
|
||||
// from task activity: daemon diagnostics are not lifecycle events.
|
||||
type Feed struct {
|
||||
mu sync.RWMutex
|
||||
entries []Entry
|
||||
limit int
|
||||
nextID atomic.Int64
|
||||
subs map[chan Entry]struct{}
|
||||
}
|
||||
|
||||
func NewFeed(limit int) *Feed {
|
||||
if limit <= 0 {
|
||||
limit = 500
|
||||
}
|
||||
return &Feed{limit: limit, subs: make(map[chan Entry]struct{})}
|
||||
}
|
||||
|
||||
func (f *Feed) Snapshot() []Entry {
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
f.mu.RLock()
|
||||
defer f.mu.RUnlock()
|
||||
return append([]Entry(nil), f.entries...)
|
||||
}
|
||||
|
||||
func (f *Feed) Subscribe(ctx context.Context) <-chan Entry {
|
||||
ch := make(chan Entry, 64)
|
||||
if f == nil {
|
||||
close(ch)
|
||||
return ch
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.subs[ch] = struct{}{}
|
||||
f.mu.Unlock()
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
f.mu.Lock()
|
||||
if _, ok := f.subs[ch]; ok {
|
||||
delete(f.subs, ch)
|
||||
close(ch)
|
||||
}
|
||||
f.mu.Unlock()
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (f *Feed) append(entry Entry) {
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
entry.ID = f.nextID.Add(1)
|
||||
f.mu.Lock()
|
||||
if len(f.entries) == f.limit {
|
||||
copy(f.entries, f.entries[1:])
|
||||
f.entries[len(f.entries)-1] = entry
|
||||
} else {
|
||||
f.entries = append(f.entries, entry)
|
||||
}
|
||||
for ch := range f.subs {
|
||||
select {
|
||||
case ch <- entry:
|
||||
default:
|
||||
}
|
||||
}
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// FeedHandler writes to the wrapped slog handler and copies the same record to
|
||||
// a bounded live feed. The dashboard never parses slog JSON itself.
|
||||
type FeedHandler struct {
|
||||
next slog.Handler
|
||||
feed *Feed
|
||||
attrs []slog.Attr
|
||||
groups []string
|
||||
}
|
||||
|
||||
func NewFeedHandler(next slog.Handler, feed *Feed) *FeedHandler {
|
||||
return &FeedHandler{next: next, feed: feed}
|
||||
}
|
||||
|
||||
func (h *FeedHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return h.next.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h *FeedHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||
fields := map[string]any{}
|
||||
for _, attr := range h.attrs {
|
||||
addAttr(fields, h.groups, attr)
|
||||
}
|
||||
record.Attrs(func(attr slog.Attr) bool { addAttr(fields, h.groups, attr); return true })
|
||||
if len(fields) == 0 {
|
||||
fields = nil
|
||||
}
|
||||
h.feed.append(Entry{Time: record.Time, Level: record.Level.String(), Message: record.Message, Fields: fields})
|
||||
return h.next.Handle(ctx, record)
|
||||
}
|
||||
|
||||
func (h *FeedHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
clone := *h
|
||||
clone.attrs = append(append([]slog.Attr(nil), h.attrs...), attrs...)
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (h *FeedHandler) WithGroup(name string) slog.Handler {
|
||||
clone := *h
|
||||
clone.groups = append(append([]string(nil), h.groups...), name)
|
||||
return &clone
|
||||
}
|
||||
|
||||
func addAttr(fields map[string]any, groups []string, attr slog.Attr) {
|
||||
if attr.Equal(slog.Attr{}) {
|
||||
return
|
||||
}
|
||||
key := attr.Key
|
||||
for _, group := range groups {
|
||||
if group != "" {
|
||||
key = group + "." + key
|
||||
}
|
||||
}
|
||||
fields[key] = attr.Value.Any()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFeedCapturesStructuredSlogEntriesInOrder(t *testing.T) {
|
||||
feed := NewFeed(2)
|
||||
logger := slog.New(NewFeedHandler(slog.NewJSONHandler(testWriter{}, nil), feed))
|
||||
logger.Info("started", "component", "daemon")
|
||||
logger.Warn("slow", "component", "worker")
|
||||
|
||||
entries := feed.Snapshot()
|
||||
if len(entries) != 2 || entries[0].ID == 0 || entries[1].ID <= entries[0].ID {
|
||||
t.Fatalf("entries = %#v", entries)
|
||||
}
|
||||
if entries[0].Message != "started" || entries[0].Fields["component"] != "daemon" {
|
||||
t.Fatalf("first entry = %#v", entries[0])
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
updates := feed.Subscribe(ctx)
|
||||
logger.Error("failed", "component", "worker")
|
||||
if got := <-updates; got.Message != "failed" || got.Level != "ERROR" {
|
||||
t.Fatalf("live entry = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
type testWriter struct{}
|
||||
|
||||
func (testWriter) Write(p []byte) (int, error) { return len(p), nil }
|
||||
@@ -19,6 +19,8 @@ import (
|
||||
// Options configures the logger. The zero value is a stderr-only JSON logger
|
||||
// at info level, which is what archied did before file logging existed.
|
||||
type Options struct {
|
||||
// Feed receives structured live entries in addition to configured sinks.
|
||||
Feed *Feed
|
||||
// File is the log file path. Empty disables file logging.
|
||||
File string
|
||||
// MaxSizeMB rotates the file once it exceeds this size. Zero selects
|
||||
@@ -51,12 +53,12 @@ func New(opts Options) (*slog.Logger, io.Closer, error) {
|
||||
handlerOpts := &slog.HandlerOptions{Level: level}
|
||||
|
||||
if opts.File == "" {
|
||||
return slog.New(slog.NewJSONHandler(os.Stderr, handlerOpts)), noopCloser{}, nil
|
||||
return slog.New(withFeed(slog.NewJSONHandler(os.Stderr, handlerOpts), opts.Feed)), noopCloser{}, nil
|
||||
}
|
||||
|
||||
w, err := newRotatingFile(opts.File, opts.MaxSizeMB, opts.Keep)
|
||||
if err != nil {
|
||||
return slog.New(slog.NewJSONHandler(os.Stderr, handlerOpts)), noopCloser{},
|
||||
return slog.New(withFeed(slog.NewJSONHandler(os.Stderr, handlerOpts), opts.Feed)), noopCloser{},
|
||||
fmt.Errorf("logging: open %s: %w", opts.File, err)
|
||||
}
|
||||
|
||||
@@ -64,7 +66,14 @@ func New(opts Options) (*slog.Logger, io.Closer, error) {
|
||||
if opts.Stderr {
|
||||
sink = io.MultiWriter(os.Stderr, w)
|
||||
}
|
||||
return slog.New(slog.NewJSONHandler(sink, handlerOpts)), w, nil
|
||||
return slog.New(withFeed(slog.NewJSONHandler(sink, handlerOpts), opts.Feed)), w, nil
|
||||
}
|
||||
|
||||
func withFeed(handler slog.Handler, feed *Feed) slog.Handler {
|
||||
if feed == nil {
|
||||
return handler
|
||||
}
|
||||
return NewFeedHandler(handler, feed)
|
||||
}
|
||||
|
||||
func parseLevel(s string) slog.Level {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
// changes with them in the same file, and no consumer has to know slog wrote
|
||||
// JSON with a "msg" key.
|
||||
type Entry struct {
|
||||
ID int64 `json:"id,omitempty"`
|
||||
Time time.Time `json:"time"`
|
||||
Level string `json:"level"`
|
||||
Message string `json:"msg"`
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -21,9 +23,10 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
// Not an error: file logging is optional. Say so plainly so the UI can
|
||||
// explain how to turn it on rather than showing an empty table.
|
||||
writeJSON(w, map[string]any{
|
||||
"entries": []any{},
|
||||
"file": "",
|
||||
"disabled": true,
|
||||
"entries": s.LogFeed.Snapshot(),
|
||||
"file": "",
|
||||
"disabled": true,
|
||||
"components": mergeComponents(nil, s.LogFeed.Snapshot()),
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -48,15 +51,66 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
s.Log.Warn("log components unavailable", "err", err)
|
||||
components = []string{}
|
||||
}
|
||||
liveEntries := s.LogFeed.Snapshot()
|
||||
components = mergeComponents(components, liveEntries)
|
||||
|
||||
writeJSON(w, map[string]any{
|
||||
"entries": result.Entries,
|
||||
"entries": append(result.Entries, liveEntries...),
|
||||
"truncated": result.Truncated,
|
||||
"file": result.File,
|
||||
"components": components,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
|
||||
if s.LogFeed == nil {
|
||||
http.Error(w, "live daemon log feed unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
entries := s.LogFeed.Subscribe(r.Context())
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case entry, ok := <-entries:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
_, _ = w.Write([]byte("id: " + strconv.FormatInt(entry.ID, 10) + "\ndata: " + string(data) + "\n\n"))
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mergeComponents(history []string, live []logging.Entry) []string {
|
||||
seen := make(map[string]struct{}, len(history))
|
||||
for _, component := range history {
|
||||
seen[component] = struct{}{}
|
||||
}
|
||||
for _, entry := range live {
|
||||
if component, ok := entry.Fields["component"].(string); ok && component != "" {
|
||||
seen[component] = struct{}{}
|
||||
}
|
||||
}
|
||||
components := make([]string, 0, len(seen))
|
||||
for component := range seen {
|
||||
components = append(components, component)
|
||||
}
|
||||
slices.Sort(components)
|
||||
return components
|
||||
}
|
||||
|
||||
// logFile reports the configured log path, or "" when file logging is off.
|
||||
func (s *Server) logFile() string {
|
||||
if s.Cfg == nil {
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
package webui
|
||||
|
||||
import "net/http"
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// handleWorkflows returns per-workflow and per-stage statistics: run counts,
|
||||
// outcome breakdowns and spend per workflow, plus duration and failure counts
|
||||
@@ -18,7 +27,76 @@ func (s *Server) handleWorkflows(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{
|
||||
"workflows": workflows,
|
||||
"stages": stages,
|
||||
"workflows": workflows,
|
||||
"stages": stages,
|
||||
"definitions": s.Workflows,
|
||||
})
|
||||
}
|
||||
|
||||
type workRequest struct {
|
||||
Identity string `json:"identity"`
|
||||
Repository string `json:"repository"`
|
||||
Workflow string `json:"workflow"`
|
||||
Title string `json:"title"`
|
||||
Instructions string `json:"instructions"`
|
||||
}
|
||||
|
||||
func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if !authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.WorkRequests == nil {
|
||||
http.Error(w, "work intake unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 32<<10)
|
||||
var request workRequest
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
http.Error(w, "work request body too large", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
http.Error(w, "invalid work request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
http.Error(w, "invalid work request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
request.Identity = strings.TrimSpace(request.Identity)
|
||||
request.Repository = strings.TrimSpace(request.Repository)
|
||||
request.Workflow = strings.TrimSpace(request.Workflow)
|
||||
request.Title = strings.TrimSpace(request.Title)
|
||||
request.Instructions = strings.TrimSpace(request.Instructions)
|
||||
if request.Identity == "" || request.Repository == "" || request.Workflow == "" || request.Title == "" || request.Instructions == "" {
|
||||
http.Error(w, "identity, repository, workflow, title, and instructions are required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.hasWorkflow(request.Workflow) {
|
||||
http.Error(w, "workflow is not enabled", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
taskID, err := s.WorkRequests.CreateTask(r.Context(), gateway.SpawnRequest{
|
||||
Identity: request.Identity, Repo: request.Repository, Workflow: request.Workflow,
|
||||
Title: request.Title, Body: request.Instructions,
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, "work request rejected", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.emit(r.Context(), events.Event{Kind: events.KindWorkRequestSubmitted, TaskID: taskID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title})
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, map[string]any{"ok": true, "task_id": taskID})
|
||||
}
|
||||
|
||||
func (s *Server) hasWorkflow(id string) bool {
|
||||
for _, workflow := range s.Workflows {
|
||||
if workflow.ID == id && workflow.Enabled {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
type recordingWorkRequestCreator struct{ request gateway.SpawnRequest }
|
||||
|
||||
func (c *recordingWorkRequestCreator) CreateTask(_ context.Context, request gateway.SpawnRequest) (int64, error) {
|
||||
c.request = request
|
||||
return 42, nil
|
||||
}
|
||||
|
||||
func TestWorkflowsIncludeInstalledZeroRunDefinitions(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Workflows = []workflow.Definition{{ID: "implement", Name: "Implement", Origin: "builtin", Enabled: true, Stages: []string{"prepare", "plan"}}}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/workflows", nil))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var response struct {
|
||||
Definitions []workflow.Definition `json:"definitions"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Definitions) != 1 || response.Definitions[0].ID != "implement" || len(response.Definitions[0].Stages) != 2 {
|
||||
t.Fatalf("definitions = %#v", response.Definitions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkRequestUsesNormalTaskAdmission(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.Workflows = []workflow.Definition{{ID: "implement", Name: "Implement", Enabled: true}}
|
||||
|
||||
body := `{"identity":"archie","repository":"acme/widget","workflow":"implement","title":"Fix login","instructions":"Reproduce and fix it."}`
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/work-requests", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if got := creator.request; got.Identity != "archie" || got.Repo != "acme/widget" || got.Workflow != "implement" || got.Title != "Fix login" || got.Body != "Reproduce and fix it." {
|
||||
t.Fatalf("request = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkRequestRejectsDisabledWorkflow(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
creator := &recordingWorkRequestCreator{}
|
||||
srv.WorkRequests = creator
|
||||
srv.Workflows = []workflow.Definition{{ID: "implement", Enabled: false}}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/work-requests", strings.NewReader(`{"identity":"archie","repository":"acme/widget","workflow":"implement","title":"Fix","instructions":"Do it"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if creator.request != (gateway.SpawnRequest{}) {
|
||||
t.Fatalf("creator called with %#v", creator.request)
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,19 @@
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.setup-complete-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.setup-dismiss {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
font-size: var(--text-lg);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.setup-done .setup-pct {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import { ago, compact, el, empty, mount, pill, statusKind } from "../base/dom.js
|
||||
import { statTile } from "../base/statTile.js";
|
||||
import { gauge, segmentBar } from "../base/gauge.js";
|
||||
import { icon } from "../base/icons.js";
|
||||
import { dismissSetupComplete, setupPanelState } from "./setup-preference.js";
|
||||
import { dashboardTaskTargets } from "./task-targets.js";
|
||||
|
||||
/**
|
||||
* The control room. Answers, in order: is anything wrong, what is Archie doing
|
||||
@@ -80,25 +82,25 @@ export function dashboardPage() {
|
||||
el("h2.dash-section-title", "Right now"),
|
||||
),
|
||||
el(
|
||||
"div.dash-split",
|
||||
forecastSlot,
|
||||
el(
|
||||
"div.card",
|
||||
"div.dash-split",
|
||||
forecastSlot,
|
||||
el(
|
||||
"div.card-head",
|
||||
el("div", el("h2.card-title", "Live activity"), el("p.card-sub", "Last 50, newest first")),
|
||||
streamState,
|
||||
),
|
||||
el(
|
||||
"div.table-scroll",
|
||||
"div.card",
|
||||
el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Event", "Task", "Detail", "When"].map((h) => el("th", h)))),
|
||||
runs,
|
||||
"div.card-head",
|
||||
el("div", el("h2.card-title", "Live activity"), el("p.card-sub", "Last 50, newest first")),
|
||||
streamState,
|
||||
),
|
||||
el(
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Event", "Task", "Detail", "When"].map((h) => el("th", h)))),
|
||||
runs,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
renderActivity();
|
||||
@@ -127,7 +129,7 @@ export function dashboardPage() {
|
||||
}
|
||||
}
|
||||
renderActivity();
|
||||
renderActions(summary);
|
||||
renderActions(tasks);
|
||||
// The greeting is only personalised when the deployment says who it
|
||||
// assists; an unconfigured instance greets without a name rather than
|
||||
// inventing one.
|
||||
@@ -151,22 +153,22 @@ export function dashboardPage() {
|
||||
// Actions follow state: what needs you comes first, and the generic ones
|
||||
// only fill the space when nothing does. A row of buttons that is identical
|
||||
// whatever is happening teaches nobody anything.
|
||||
function renderActions(summary) {
|
||||
const counts = summary?.statuses || {};
|
||||
const blocked = (counts.parked || 0) + (counts.waiting_human || 0);
|
||||
const running = counts.running || 0;
|
||||
function renderActions(tasks) {
|
||||
const targets = dashboardTaskTargets(tasks);
|
||||
const blocked = targets.attention.count;
|
||||
const running = targets.running.count;
|
||||
|
||||
mount(
|
||||
actions,
|
||||
blocked > 0 &&
|
||||
el(
|
||||
"a.btn.btn-attention",
|
||||
{ href: "#/tasks" },
|
||||
{ href: targets.attention.href },
|
||||
icon("tasks", { size: 15 }),
|
||||
`${blocked} need${blocked === 1 ? "s" : ""} you`,
|
||||
),
|
||||
running > 0 &&
|
||||
el("a.btn", { href: "#/tasks" }, icon("workflows", { size: 15 }), `${running} running`),
|
||||
el("a.btn", { href: targets.running.href }, icon("workflows", { size: 15 }), `${running} running`),
|
||||
el("a.btn", { href: "#/logs" }, icon("logs", { size: 15 }), "Logs"),
|
||||
el("button.btn.btn-primary", { onclick: load }, icon("refresh", { size: 15 }), "Refresh"),
|
||||
);
|
||||
@@ -213,14 +215,11 @@ export function dashboardPage() {
|
||||
// Unknown setup (endpoint unreachable) or no checklist configured: omit
|
||||
// the panel and let the gate pulse take the full row, so the Health row
|
||||
// never shows an empty half beside the pulse.
|
||||
// One place decides this class, reconciled from the data on every render.
|
||||
// A second rule elsewhere in this function used to clear it again, which
|
||||
// reads as two sources of truth for one bit of layout state even though
|
||||
// the toggle above had already settled it.
|
||||
const omit = !setup?.steps?.length;
|
||||
const state = setupPanelState(setup);
|
||||
const omit = state.kind === "omit" || state.kind === "dismissed";
|
||||
topRow.classList.toggle("dash-top-standalone", omit);
|
||||
if (omit) return mount(setupSlot);
|
||||
const remaining = setup.steps.filter((s) => !s.done);
|
||||
const remaining = state.remaining;
|
||||
if (remaining.length) {
|
||||
const pct = Math.round(((setup.steps.length - remaining.length) / setup.steps.length) * 100);
|
||||
mount(
|
||||
@@ -255,7 +254,23 @@ export function dashboardPage() {
|
||||
el("h2.card-title", "Setup complete"),
|
||||
el("p.card-sub", "Archie is configured and ready to work."),
|
||||
),
|
||||
el("span.setup-pct", icon("check", { size: 16 })),
|
||||
el(
|
||||
"div.setup-complete-actions",
|
||||
el("span.setup-pct", icon("check", { size: 16 })),
|
||||
el(
|
||||
"button.icon-btn.setup-dismiss",
|
||||
{
|
||||
type: "button",
|
||||
title: "Dismiss setup complete",
|
||||
"aria-label": "Dismiss setup complete",
|
||||
onclick: () => {
|
||||
dismissSetupComplete();
|
||||
renderSetup(setup);
|
||||
},
|
||||
},
|
||||
"×",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
+33
-40
@@ -1,5 +1,5 @@
|
||||
import "./logs.css";
|
||||
import { api, subscribeEvents } from "../base/api.js";
|
||||
import { api, subscribeLogs } from "../base/api.js";
|
||||
import { el, empty, mount, pill } from "../base/dom.js";
|
||||
|
||||
/**
|
||||
@@ -42,6 +42,9 @@ export function logsPage() {
|
||||
let filters = { level: "", component: "", q: "" };
|
||||
let paused = false;
|
||||
let componentOptions = [];
|
||||
let historyEntries = [];
|
||||
const liveEntries = new Map();
|
||||
let durableUnavailable = false;
|
||||
|
||||
const levelSelect = el(
|
||||
"select.log-select",
|
||||
@@ -59,9 +62,8 @@ export function logsPage() {
|
||||
const pauseBtn = el("button.btn", { onclick: togglePause }, "Pause");
|
||||
|
||||
render();
|
||||
load();
|
||||
|
||||
const unsubscribe = subscribeEvents(
|
||||
const unsubscribe = subscribeLogs(
|
||||
(event) => appendLive(event),
|
||||
(state) => {
|
||||
streamState.className = `pill pill-${state === "live" ? "ok" : "warn"}`;
|
||||
@@ -69,6 +71,7 @@ export function logsPage() {
|
||||
},
|
||||
);
|
||||
root.addEventListener("archie:teardown", unsubscribe);
|
||||
load();
|
||||
|
||||
function set(patch) {
|
||||
filters = { ...filters, ...patch };
|
||||
@@ -106,7 +109,7 @@ export function logsPage() {
|
||||
}
|
||||
|
||||
async function load() {
|
||||
mount(list, el("div.log-loading", "Loading…"));
|
||||
meta.textContent = "Refreshing…";
|
||||
try {
|
||||
const res = await api.logs({
|
||||
level: filters.level,
|
||||
@@ -115,30 +118,13 @@ export function logsPage() {
|
||||
limit: 500,
|
||||
});
|
||||
|
||||
if (res.disabled) {
|
||||
mount(
|
||||
list,
|
||||
empty(
|
||||
"File logging is off",
|
||||
"Set [log] file in your config to keep a durable record. Live lines below still stream while this page is open.",
|
||||
),
|
||||
);
|
||||
meta.textContent = "";
|
||||
return;
|
||||
}
|
||||
|
||||
syncComponents(res.components || []);
|
||||
meta.textContent = res.truncated
|
||||
durableUnavailable = !!res.disabled;
|
||||
meta.textContent = res.disabled ? "Durable history unavailable; live daemon logs continue." : res.truncated
|
||||
? `showing the most recent matches from ${res.file}`
|
||||
: res.file || "";
|
||||
|
||||
const entries = res.entries || [];
|
||||
if (!entries.length) {
|
||||
mount(list, empty("Nothing matches", "Try a wider level or clear the search."));
|
||||
return;
|
||||
}
|
||||
mount(list, ...entries.map(row));
|
||||
list.scrollTop = list.scrollHeight;
|
||||
historyEntries = res.entries || [];
|
||||
renderEntries();
|
||||
} catch (err) {
|
||||
mount(list, empty("Cannot read logs", String(err.message || err)));
|
||||
}
|
||||
@@ -160,23 +146,26 @@ export function logsPage() {
|
||||
|
||||
function appendLive(event) {
|
||||
if (paused) return;
|
||||
const entry = {
|
||||
time: event.at || new Date().toISOString(),
|
||||
level: event.level || "INFO",
|
||||
msg: event.detail || event.message || event.kind || "event",
|
||||
fields: event.task_id ? { task: event.task_id } : null,
|
||||
};
|
||||
const entry = event;
|
||||
if (!matchesLocally(entry)) return;
|
||||
|
||||
// Only auto-scroll when already at the bottom, so reading history is not
|
||||
// yanked away by an arriving line.
|
||||
const atBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 40;
|
||||
if (list.querySelector(".empty, .log-loading")) list.replaceChildren();
|
||||
list.append(row({ ...entry, message: entry.msg }));
|
||||
while (list.children.length > 1000) list.firstElementChild.remove();
|
||||
if (atBottom) list.scrollTop = list.scrollHeight;
|
||||
liveEntries.set(entryKey(entry), entry);
|
||||
if (entry.fields?.component) syncComponents([...componentOptions, entry.fields.component]);
|
||||
renderEntries();
|
||||
}
|
||||
|
||||
function renderEntries() {
|
||||
const byID = new Map();
|
||||
for (const entry of historyEntries) byID.set(entryKey(entry), entry);
|
||||
for (const [id, entry] of liveEntries) byID.set(id, entry);
|
||||
const entries = [...byID.values()].filter(matchesLocally).slice(-1000);
|
||||
if (!entries.length) {
|
||||
mount(list, empty(durableUnavailable ? "Durable history unavailable" : "Nothing matches", durableUnavailable ? "Live daemon logs will appear here while this page is open." : "Try a wider level or clear the search."));
|
||||
return;
|
||||
}
|
||||
mount(list, ...entries.map(row));
|
||||
list.scrollTop = list.scrollHeight;
|
||||
}
|
||||
|
||||
function matchesLocally(entry) {
|
||||
if (filters.level && !filters.level.split(",").includes((entry.level || "").toUpperCase())) {
|
||||
return false;
|
||||
@@ -184,7 +173,7 @@ export function logsPage() {
|
||||
if (filters.component && entry.fields?.component !== filters.component) return false;
|
||||
if (filters.q) {
|
||||
const needle = filters.q.toLowerCase();
|
||||
const hay = `${entry.msg} ${JSON.stringify(entry.fields || {})}`.toLowerCase();
|
||||
const hay = `${entry.message || entry.msg || ""} ${JSON.stringify(entry.fields || {})}`.toLowerCase();
|
||||
if (!hay.includes(needle)) return false;
|
||||
}
|
||||
return true;
|
||||
@@ -193,6 +182,10 @@ export function logsPage() {
|
||||
return root;
|
||||
}
|
||||
|
||||
function entryKey(entry) {
|
||||
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
|
||||
}
|
||||
|
||||
function row(entry) {
|
||||
const fields = entry.fields || {};
|
||||
return el(
|
||||
|
||||
@@ -50,6 +50,7 @@ export function workflowsPage() {
|
||||
const root = el("div");
|
||||
const workflowSlot = el("div");
|
||||
const stageSlot = el("div");
|
||||
const startSlot = el("div");
|
||||
|
||||
render();
|
||||
load();
|
||||
@@ -66,6 +67,7 @@ export function workflowsPage() {
|
||||
),
|
||||
el("div.page-actions", el("button.btn", { onclick: load }, "Refresh")),
|
||||
),
|
||||
startSlot,
|
||||
workflowSlot,
|
||||
stageSlot,
|
||||
);
|
||||
@@ -74,7 +76,8 @@ export function workflowsPage() {
|
||||
async function load() {
|
||||
try {
|
||||
const data = await api.workflows();
|
||||
renderWorkflows(data?.workflows || []);
|
||||
renderStartWork(data?.definitions || []);
|
||||
renderWorkflows(data?.workflows || [], data?.definitions || []);
|
||||
renderStages(data?.stages || []);
|
||||
} catch (err) {
|
||||
mount(workflowSlot, el("div.card", empty("Cannot reach archied", String(err.message || err))));
|
||||
@@ -82,8 +85,40 @@ export function workflowsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
function renderWorkflows(workflows) {
|
||||
if (!workflows.length) {
|
||||
function renderStartWork(definitions) {
|
||||
if (!definitions.length) {
|
||||
mount(startSlot);
|
||||
return;
|
||||
}
|
||||
const identity = el("input", { placeholder: "Identity", required: true });
|
||||
const repository = el("input", { placeholder: "owner/repository", required: true });
|
||||
const workflow = el("select", { required: true }, ...definitions.filter((d) => d.enabled).map((d) => el("option", { value: d.id }, workflowLabel(d.name || d.id))));
|
||||
const title = el("input", { placeholder: "Short task title", required: true });
|
||||
const instructions = el("textarea", { placeholder: "Instructions for the work", required: true, rows: 3 });
|
||||
const notice = el("p.card-sub");
|
||||
const submit = el("button.btn", { type: "submit" }, "Start work");
|
||||
const form = el("form.cfg-rows", {
|
||||
onsubmit: async (event) => {
|
||||
event.preventDefault();
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const result = await api.workRequest({ identity: identity.value, repository: repository.value, workflow: workflow.value, title: title.value, instructions: instructions.value });
|
||||
notice.textContent = `Queued task #${result.task_id}.`;
|
||||
form.reset();
|
||||
} catch (err) {
|
||||
notice.textContent = String(err.message || err);
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
}
|
||||
},
|
||||
}, identity, repository, workflow, title, instructions, submit, notice);
|
||||
mount(startSlot, el("div.card", el("div.card-head", el("div", el("h2.card-title", "Start work"), el("p.card-sub", "This enters Archie’s normal admitted task queue."))), form));
|
||||
}
|
||||
|
||||
function renderWorkflows(workflows, definitions) {
|
||||
const byID = new Map(workflows.map((workflow) => [workflow.workflow, workflow]));
|
||||
const rows = definitions.map((definition) => ({ ...definition, ...(byID.get(definition.id) || { workflow: definition.id, runs: 0, merged: 0 }) }));
|
||||
if (!rows.length) {
|
||||
mount(
|
||||
workflowSlot,
|
||||
el(
|
||||
@@ -115,16 +150,17 @@ export function workflowsPage() {
|
||||
"thead",
|
||||
el(
|
||||
"tr",
|
||||
...["Workflow", "Runs", "Success rate", "Avg tokens", "Avg steps"].map((h) => el("th", h)),
|
||||
...["Workflow", "Origin", "Runs", "Success rate", "Avg tokens", "Avg steps"].map((h) => el("th", h)),
|
||||
),
|
||||
),
|
||||
el(
|
||||
"tbody",
|
||||
...workflows.map((w) => {
|
||||
...rows.map((w) => {
|
||||
const rate = pct(w.merged, w.runs);
|
||||
return el(
|
||||
"tr",
|
||||
el("td.strong", workflowLabel(w.workflow)),
|
||||
el("td.mono", w.origin || "registry"),
|
||||
el("td", `${w.runs} run${w.runs === 1 ? "" : "s"}`),
|
||||
el(
|
||||
"td",
|
||||
|
||||
Reference in new issue
Block a user