fix: harden task and chat execution
Task runs now preserve real model context limits, provider usage, baseline-repair spend, commit identity, durable agent-finish telemetry, and useful timeline details without imposing a token cap. Dashboard forge links are canonical per owning GitHub or Gitea identity. Chat turn claims acquire SQLite writer intent before reading, eliminating the concurrent SQLITE_BUSY snapshot race.
This commit is contained in:
1 parent
1740bd12d8
commit
4b340d2b56
36 files changed
+874
-286
No files matched your search
@@ -11,15 +11,19 @@ import (
|
||||
|
||||
func applyModelCatalog(cfg *config.Config, snapshot modelcatalog.Snapshot) []string {
|
||||
discovered := make(map[string]config.Provider, len(snapshot.Providers))
|
||||
limits := make(map[string]config.ModelLimits)
|
||||
var models []string
|
||||
for _, provider := range snapshot.Providers {
|
||||
discovered[provider.ID] = config.Provider{
|
||||
Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, BaseURL: provider.BaseURL,
|
||||
}
|
||||
for _, model := range provider.Models {
|
||||
models = append(models, provider.ID+"/"+model.ID)
|
||||
ref := provider.ID + "/" + model.ID
|
||||
models = append(models, ref)
|
||||
limits[ref] = config.ModelLimits{ContextWindow: model.ContextWindow, MaxOutputTokens: model.MaxOutputTokens}
|
||||
}
|
||||
}
|
||||
cfg.ModelLimits = limits
|
||||
cfg.Providers = mergeProviders(discovered, cfg.Providers)
|
||||
for i := range cfg.Identities {
|
||||
cfg.Identities[i].Providers = mergeProviders(discovered, cfg.Identities[i].Providers)
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) {
|
||||
{
|
||||
ID: "openai", Class: "openai", APIKeyEnv: "OPENAI_API_KEY",
|
||||
BaseURL: "https://api.openai.test/v1",
|
||||
Models: []modelcatalog.Model{{ID: "gpt-tool"}},
|
||||
Models: []modelcatalog.Model{{ID: "gpt-tool", ContextWindow: 128_000, MaxOutputTokens: 16_000}},
|
||||
},
|
||||
{
|
||||
ID: "anthropic", Class: "anthropic", APIKeyEnv: "ANTHROPIC_API_KEY",
|
||||
@@ -49,4 +49,7 @@ func TestApplyModelCatalogNormalizesEveryExecutionScope(t *testing.T) {
|
||||
if !reflect.DeepEqual(models, wantModels) {
|
||||
t.Fatalf("models = %v, want %v", models, wantModels)
|
||||
}
|
||||
if got := cfg.ModelLimits["openai/gpt-tool"]; got.ContextWindow != 128_000 || got.MaxOutputTokens != 16_000 {
|
||||
t.Fatalf("model limits = %+v, want catalog capacity", got)
|
||||
}
|
||||
}
|
||||
+16
-4
@@ -145,11 +145,23 @@ var reloadableFields = map[string]bool{
|
||||
"Budgets": true,
|
||||
"Dispatch": true,
|
||||
"Models": true,
|
||||
"ModelLimits": true,
|
||||
"Notify": true,
|
||||
// Per-poll reads off the live config in pollIssuesWithConfig:
|
||||
// cfg.Label feeds IssuesWithLabel (daemon.go:359,390), cfg.BotUser
|
||||
// feeds AssignedIssues (:368,381). Not carried by ForTask, so
|
||||
// pinned by hand in TestReloadableFieldsCoverForTaskSnapshot.
|
||||
// BotUser/BotEmail used to be poll-path only; ForTask now carries both
|
||||
// into the task snapshot as well, because the sandboxed worker builds
|
||||
// its own worktree.Manager and signs its own commits (agentworker
|
||||
// task_execution.go, config.go ForTask). The commit identity is
|
||||
// therefore per-dispatch and does reload. The startup-built daemon
|
||||
// trees (bootstrap.go:654) still capture both, but only to record
|
||||
// user.name/user.email in the clone's own .git/config
|
||||
// (worktree.go setIdentity) -- cosmetic, not the signature go-git
|
||||
// commits with -- so a reload applies where it counts and this stays
|
||||
// reloadable rather than requires-restart.
|
||||
"BotEmail": true,
|
||||
// cfg.Label additionally feeds IssuesWithLabel per poll cycle
|
||||
// (daemon.go:359,390) and cfg.BotUser feeds AssignedIssues (:364,377).
|
||||
// Label is not carried by ForTask, so it is pinned by hand in
|
||||
// TestReloadableFieldsCoverForTaskSnapshot.
|
||||
"Label": true,
|
||||
"BotUser": true,
|
||||
// Worked example of the every-consumer criterion above: the sole
|
||||
|
||||
@@ -287,9 +287,11 @@ func TestReloadableFieldsCoverForTaskSnapshot(t *testing.T) {
|
||||
t.Errorf("ForTask field %s is not allowlisted as reloadable", name)
|
||||
}
|
||||
}
|
||||
// The poll-path fields (Label, BotUser) are not carried by ForTask;
|
||||
// pin them explicitly so a refactor that moves their read site does
|
||||
// not silently drop the allowlist entry.
|
||||
// Label is not carried by ForTask; BotUser now is, but it is also read
|
||||
// on the poll path independently of the task snapshot. Pin both by hand
|
||||
// so a refactor that moves either read site -- including one that drops
|
||||
// BotUser from ForTask again -- does not silently drop the allowlist
|
||||
// entry the poll path still depends on.
|
||||
for _, name := range []string{"Label", "BotUser"} {
|
||||
if !reloadableFields[name] {
|
||||
t.Errorf("poll-path field %s is not allowlisted as reloadable", name)
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"context_window": {
|
||||
"type": "integer"
|
||||
},
|
||||
"extra_rules": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -127,6 +130,9 @@
|
||||
"tokens_used": {
|
||||
"type": "integer"
|
||||
},
|
||||
"usage": {
|
||||
"$ref": "#/schemas/Usage"
|
||||
},
|
||||
"version": {
|
||||
"type": "integer"
|
||||
}
|
||||
@@ -258,6 +264,10 @@
|
||||
"description": "MIMEType is the content type (e.g. \"image/png\", \"audio/ogg\").",
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"description": "Path is a local filesystem path on the host that produced the\nattachment. It is the alternative to URL for outbound delivery: a\nURL is fetched by the platform, a Path is uploaded by us. A file the\nagent wrote has no URL and never gets one -- publishing it would\ntrade a delivery problem for a hosting and access-control one -- so\nsenders that support upload must read this.\n\nExactly one of URL and Path is meaningful for an outbound send.",
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"description": "Type is \"image\", \"video\", \"audio\", or \"document\".",
|
||||
"type": "string"
|
||||
@@ -392,6 +402,28 @@
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"Usage": {
|
||||
"additionalProperties": false,
|
||||
"description": "Usage preserves provider-reported token economics for evaluation.",
|
||||
"properties": {
|
||||
"cache_creation_tokens": {
|
||||
"type": "integer"
|
||||
},
|
||||
"cached_tokens": {
|
||||
"type": "integer"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"type": "integer"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"type": "integer"
|
||||
},
|
||||
"total_tokens": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ require (
|
||||
github.com/moby/moby/client v0.5.1
|
||||
github.com/nats-io/nats-server/v2 v2.14.4
|
||||
github.com/nats-io/nats.go v1.52.0
|
||||
github.com/samcharles93/ai-sdk v0.1.22
|
||||
github.com/samcharles93/ai-sdk v0.1.25
|
||||
github.com/traefik/yaegi v0.16.1
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/term v0.45.0
|
||||
|
||||
@@ -126,12 +126,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/samcharles93/ai-sdk v0.1.20 h1:Z52dyMN293aV8Cpgjdyyd2zw6oNF5FSXKWfCuxY/3UA=
|
||||
github.com/samcharles93/ai-sdk v0.1.20/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/samcharles93/ai-sdk v0.1.21 h1:V/OqLnoWuZQ/8qw6MiVZuQU5qVLkULGex6WMQYCbCg4=
|
||||
github.com/samcharles93/ai-sdk v0.1.21/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/samcharles93/ai-sdk v0.1.22 h1:IIV1HVOzCKMQl5MvZ23WzEzaOyHpnT8QcoN8ihFi9Xc=
|
||||
github.com/samcharles93/ai-sdk v0.1.22/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/samcharles93/ai-sdk v0.1.25 h1:30cvHZBw01XRif2cOG/PToC7xTQUZ5DHwMOShT8zSnw=
|
||||
github.com/samcharles93/ai-sdk v0.1.25/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
|
||||
@@ -103,6 +103,12 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep
|
||||
MaxSteps: req.Budget.MaxSteps,
|
||||
WallClock: req.Budget.WallClock,
|
||||
},
|
||||
Compact: agentloop.CompactionConfig{
|
||||
Enabled: req.ContextWindow > 0,
|
||||
ContextWindow: req.ContextWindow,
|
||||
ThresholdRatio: 0.5,
|
||||
TargetRatio: 0.15,
|
||||
},
|
||||
Completion: agentloop.CompletionForceFinish,
|
||||
ReadOnly: req.ReadOnly,
|
||||
ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly),
|
||||
@@ -114,19 +120,34 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep
|
||||
),
|
||||
Logger: r.logger(req),
|
||||
})
|
||||
result := resultFromRun(req, res, notes.appended, captures)
|
||||
if cause := context.Cause(ctx); cause != nil {
|
||||
return result, cause
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
func resultFromRun(req Request, res agentloop.Result, appended []string, captures map[string][]json.RawMessage) Result {
|
||||
result := Result{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Status: string(res.Status),
|
||||
StopReason: res.StopReason,
|
||||
Changes: res.Changes,
|
||||
Iterations: res.Iterations,
|
||||
TokensUsed: res.TokensUsed,
|
||||
Version: ProtocolVersion,
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Status: string(res.Status),
|
||||
StopReason: res.StopReason,
|
||||
Changes: res.Changes,
|
||||
Iterations: res.Iterations,
|
||||
TokensUsed: res.TokensUsed,
|
||||
Usage: Usage{
|
||||
PromptTokens: res.Usage.PromptTokens,
|
||||
CompletionTokens: res.Usage.CompletionTokens,
|
||||
TotalTokens: res.Usage.TotalTokens,
|
||||
CachedTokens: res.Usage.CachedTokens,
|
||||
CacheCreationTokens: res.Usage.CacheCreationTokens,
|
||||
},
|
||||
Summary: res.Summary,
|
||||
Detail: res.Detail,
|
||||
AppendedNotes: notes.appended,
|
||||
AppendedNotes: appended,
|
||||
Captures: captures,
|
||||
}
|
||||
// agentloop may return a zero-valued status on early exit (model
|
||||
@@ -136,10 +157,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep
|
||||
result.Status = "blocked"
|
||||
result.Detail = "agent returned no status (possible model connectivity issue)"
|
||||
}
|
||||
if cause := context.Cause(ctx); cause != nil {
|
||||
return result, cause
|
||||
}
|
||||
return result, err
|
||||
return result
|
||||
}
|
||||
|
||||
func projectScopedRules(workspace, extra string) string {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agentloop"
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
@@ -70,6 +71,9 @@ func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
if cfg.Completion != agentloop.CompletionForceFinish {
|
||||
t.Fatalf("Completion = %q, want forced finish recovery", cfg.Completion)
|
||||
}
|
||||
if !cfg.Compact.Enabled || cfg.Compact.ContextWindow <= 0 {
|
||||
t.Fatalf("Compact = %#v, want adaptive non-blocking history compaction", cfg.Compact)
|
||||
}
|
||||
if !strings.Contains(cfg.ExtraRules, "Confine discovery to /workspace") ||
|
||||
!strings.Contains(cfg.ExtraRules, "unless the mission explicitly requests") {
|
||||
t.Fatalf("project discovery rule missing from ExtraRules: %q", cfg.ExtraRules)
|
||||
@@ -80,11 +84,14 @@ func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
if _, err := cfg.Extra["decide"].Execute(ctx, `{"fit":true}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return agentloop.Result{Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10}, nil
|
||||
return agentloop.Result{
|
||||
Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10,
|
||||
Usage: chat.Usage{PromptTokens: 8, CompletionTokens: 2, TotalTokens: 10, CachedTokens: 6},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
req := Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", Mission: "mission",
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", ContextWindow: 120_000, Mission: "mission",
|
||||
Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}},
|
||||
CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}},
|
||||
}
|
||||
@@ -95,6 +102,9 @@ func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
if got.Status != StatusPassed || got.Summary != "done" || got.TokensUsed != 10 {
|
||||
t.Fatalf("unexpected result: %#v", got)
|
||||
}
|
||||
if got.Usage.PromptTokens != 8 || got.Usage.CompletionTokens != 2 || got.Usage.CachedTokens != 6 {
|
||||
t.Fatalf("usage = %#v, want provider breakdown", got.Usage)
|
||||
}
|
||||
if len(got.AppendedNotes) != 1 || got.AppendedNotes[0] != "verified note" {
|
||||
t.Fatalf("appended notes = %v", got.AppendedNotes)
|
||||
}
|
||||
|
||||
@@ -60,21 +60,22 @@ type CaptureTool struct {
|
||||
// map a host path to a fixed path without exposing host layout in the wire
|
||||
// protocol.
|
||||
type Request struct {
|
||||
Version int `json:"version"`
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Stage string `json:"stage"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Model string `json:"model"`
|
||||
Mission string `json:"mission"`
|
||||
ExtraRules string `json:"extra_rules,omitempty"`
|
||||
ReadOnly bool `json:"read_only,omitempty"`
|
||||
Budget Budget `json:"budget"`
|
||||
Gate Gate `json:"gate"`
|
||||
Preflight []Command `json:"preflight,omitempty"`
|
||||
Protection Protection `json:"protection"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
CaptureTools []CaptureTool `json:"capture_tools,omitempty"`
|
||||
Version int `json:"version"`
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Stage string `json:"stage"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Model string `json:"model"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
Mission string `json:"mission"`
|
||||
ExtraRules string `json:"extra_rules,omitempty"`
|
||||
ReadOnly bool `json:"read_only,omitempty"`
|
||||
Budget Budget `json:"budget"`
|
||||
Gate Gate `json:"gate"`
|
||||
Preflight []Command `json:"preflight,omitempty"`
|
||||
Protection Protection `json:"protection"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
CaptureTools []CaptureTool `json:"capture_tools,omitempty"`
|
||||
// Plugins are bundled Yaegi plugins from the skill's plugins/
|
||||
// directory. Each entry carries the name and source so the agent
|
||||
// can register them as tools. PRD section 5 Layer 1.
|
||||
@@ -118,12 +119,23 @@ type Result struct {
|
||||
Changes []string `json:"changes,omitempty"`
|
||||
Iterations int `json:"iterations,omitempty"`
|
||||
TokensUsed int `json:"tokens_used,omitempty"`
|
||||
Usage Usage `json:"usage"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
AppendedNotes []string `json:"appended_notes,omitempty"`
|
||||
Captures map[string][]json.RawMessage `json:"captures,omitempty"`
|
||||
}
|
||||
|
||||
// Usage preserves provider-reported token economics for evaluation. Total is
|
||||
// retained separately as TokensUsed for compatibility with stored task rows.
|
||||
type Usage struct {
|
||||
PromptTokens int `json:"prompt_tokens,omitempty"`
|
||||
CompletionTokens int `json:"completion_tokens,omitempty"`
|
||||
TotalTokens int `json:"total_tokens,omitempty"`
|
||||
CachedTokens int `json:"cached_tokens,omitempty"`
|
||||
CacheCreationTokens int `json:"cache_creation_tokens,omitempty"`
|
||||
}
|
||||
|
||||
// Provider describes how the worker resolves a model provider. API keys are
|
||||
// referenced by environment variable name and never serialized.
|
||||
type Provider struct {
|
||||
|
||||
@@ -147,8 +147,12 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
|
||||
wf := workflow.Route(req.Task, registry)
|
||||
|
||||
trees := &hybridTrees{
|
||||
push: dependencies.trees,
|
||||
local: &worktree.Manager{WorkDir: workDir},
|
||||
push: dependencies.trees,
|
||||
local: &worktree.Manager{
|
||||
WorkDir: workDir,
|
||||
BotUser: req.Cfg.BotUser,
|
||||
BotEmail: req.Cfg.BotEmail,
|
||||
},
|
||||
localDir: workDir,
|
||||
branch: req.Task.Branch,
|
||||
worktreeUID: worktreeOwnerID(os.Getenv("WORKTREE_UID")),
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v6"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
@@ -337,7 +338,11 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("prepare: %v", err)
|
||||
}
|
||||
req := taskrun.Request{Task: task, Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, Cfg: config.Config{}.ForTask()}
|
||||
req := taskrun.Request{
|
||||
Task: task,
|
||||
Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"},
|
||||
Cfg: config.Config{BotUser: "archie-bot", BotEmail: "archie-bot@example.com"}.ForTask(),
|
||||
}
|
||||
fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return panicRunner{t} })
|
||||
response, err := runTask(ctx, req, taskDependencies{forge: fg, store: st, trees: remote}, fakeRunner, hostDir, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
@@ -353,6 +358,23 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
|
||||
if _, err := os.Stat(filepath.Join(hostDir, ".archie", "bootstrap.md")); err != nil {
|
||||
t.Fatalf("expected bootstrap marker file: %v", err)
|
||||
}
|
||||
repo, err := git.PlainOpen(hostDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := repo.Head()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commit, err := repo.CommitObject(head.Hash())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if commit.Author.Name != "archie-bot" || commit.Author.Email != "archie-bot@example.com" ||
|
||||
commit.Committer.Name != "archie-bot" || commit.Committer.Email != "archie-bot@example.com" {
|
||||
t.Fatalf("commit identity = author %q <%s>, committer %q <%s>",
|
||||
commit.Author.Name, commit.Author.Email, commit.Committer.Name, commit.Committer.Email)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecuteTaskRequestUsesInfrastructureRPCDependencies preserves the
|
||||
|
||||
@@ -9,8 +9,9 @@ import "testing"
|
||||
func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) {
|
||||
enabled := true
|
||||
orig := Config{
|
||||
Models: map[string]string{"builder": "m"},
|
||||
Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}},
|
||||
Models: map[string]string{"builder": "m"},
|
||||
ModelLimits: map[string]ModelLimits{"m": {ContextWindow: 128_000}},
|
||||
Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}},
|
||||
Identities: []IdentityConfig{{
|
||||
Models: map[string]string{"planner": "m2"},
|
||||
Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}},
|
||||
@@ -28,6 +29,7 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) {
|
||||
|
||||
got := orig.Clone()
|
||||
got.Models["builder"] = "changed"
|
||||
got.ModelLimits["m"] = ModelLimits{ContextWindow: 1}
|
||||
got.Repos[0].Gate[0][0] = "changed"
|
||||
got.Repos[0].Protect[0] = "changed"
|
||||
got.Identities[0].Models["planner"] = "changed"
|
||||
@@ -44,6 +46,9 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) {
|
||||
if orig.Models["builder"] != "m" {
|
||||
t.Error("Models map is shared")
|
||||
}
|
||||
if orig.ModelLimits["m"].ContextWindow != 128_000 {
|
||||
t.Error("ModelLimits map is shared")
|
||||
}
|
||||
if orig.Repos[0].Gate[0][0] != "task" || orig.Repos[0].Protect[0] != "p" {
|
||||
t.Error("Repo nested slices are shared")
|
||||
}
|
||||
|
||||
@@ -439,8 +439,9 @@ type Config struct {
|
||||
// namespace. When empty, the single-identity fields (BotUser,
|
||||
// Forge, Repos, Models, Providers, Dispatch, PollInterval) are used
|
||||
// unchanged for backward compatibility.
|
||||
Identities []IdentityConfig `toml:"identities" yaml:"identities"`
|
||||
Repos []Repo `toml:"repos" yaml:"repos"`
|
||||
Identities []IdentityConfig `toml:"identities" yaml:"identities"`
|
||||
Repos []Repo `toml:"repos" yaml:"repos"`
|
||||
ModelLimits map[string]ModelLimits `toml:"-" yaml:"-" json:"-"`
|
||||
|
||||
// Extra holds additional feature configuration from conf.d/ files that
|
||||
// don't match a known feature name. Keys are the filename stem (e.g.
|
||||
@@ -475,15 +476,25 @@ type IdentityConfig struct {
|
||||
Repos []Repo `toml:"repos" yaml:"repos"`
|
||||
}
|
||||
|
||||
type ModelLimits struct {
|
||||
ContextWindow int `json:"context_window"`
|
||||
MaxOutputTokens int `json:"max_output_tokens"`
|
||||
}
|
||||
|
||||
// TaskConfig is the non-secret subset of Config needed to run workflow
|
||||
// stages. It is safe to send to an archie-agent container.
|
||||
type TaskConfig struct {
|
||||
Models map[string]string `json:"models"`
|
||||
Budgets Budgets `json:"budgets"`
|
||||
Dispatch Dispatch `json:"dispatch"`
|
||||
DiffCapLines int `json:"diff_cap_lines"`
|
||||
Notify Notify `json:"notify"`
|
||||
Forge TaskForge `json:"forge"`
|
||||
// BotUser and BotEmail are non-secret commit attribution carried to the
|
||||
// sandbox because the worker owns local deterministic commits.
|
||||
BotUser string `json:"bot_user"`
|
||||
BotEmail string `json:"bot_email"`
|
||||
Models map[string]string `json:"models"`
|
||||
ModelLimits map[string]ModelLimits `json:"model_limits,omitempty"`
|
||||
Budgets Budgets `json:"budgets"`
|
||||
Dispatch Dispatch `json:"dispatch"`
|
||||
DiffCapLines int `json:"diff_cap_lines"`
|
||||
Notify Notify `json:"notify"`
|
||||
Forge TaskForge `json:"forge"`
|
||||
}
|
||||
|
||||
// TaskForge is the non-secret forge configuration needed by workflow stages.
|
||||
@@ -495,7 +506,10 @@ type TaskForge struct {
|
||||
// needed to run a workflow.
|
||||
func (c Config) ForTask() TaskConfig {
|
||||
return TaskConfig{
|
||||
BotUser: c.BotUser,
|
||||
BotEmail: c.BotEmail,
|
||||
Models: cloneStringMap(c.Models),
|
||||
ModelLimits: maps.Clone(c.ModelLimits),
|
||||
Budgets: c.Budgets,
|
||||
Dispatch: Dispatch{Trigger: c.Dispatch.Trigger, AckReaction: c.Dispatch.AckReaction, Labels: cloneStringMap(c.Dispatch.Labels)},
|
||||
DiffCapLines: c.DiffCapLines,
|
||||
@@ -510,7 +524,10 @@ func (c Config) ForTask() TaskConfig {
|
||||
// workflow stages read via TaskContext.Cfg.
|
||||
func (tc TaskConfig) ToConfig() Config {
|
||||
return Config{
|
||||
BotUser: tc.BotUser,
|
||||
BotEmail: tc.BotEmail,
|
||||
Models: cloneStringMap(tc.Models),
|
||||
ModelLimits: maps.Clone(tc.ModelLimits),
|
||||
Budgets: tc.Budgets,
|
||||
Dispatch: Dispatch{Trigger: tc.Dispatch.Trigger, AckReaction: tc.Dispatch.AckReaction, Labels: cloneStringMap(tc.Dispatch.Labels)},
|
||||
DiffCapLines: tc.DiffCapLines,
|
||||
@@ -537,6 +554,7 @@ func cloneStringMap(src map[string]string) map[string]string {
|
||||
// are shared with the published snapshot.
|
||||
func (c Config) Clone() Config {
|
||||
c.Models = cloneStringMap(c.Models)
|
||||
c.ModelLimits = maps.Clone(c.ModelLimits)
|
||||
c.Providers = maps.Clone(c.Providers)
|
||||
c.Dispatch.Labels = cloneStringMap(c.Dispatch.Labels)
|
||||
c.LegacyAgent.Env = append([]string(nil), c.LegacyAgent.Env...)
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
|
||||
func TestTaskConfigToConfigRoundTrip(t *testing.T) {
|
||||
cfg := Config{
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@users.noreply.github.com",
|
||||
DiffCapLines: 321,
|
||||
Models: map[string]string{"builder": "anthropic/claude"},
|
||||
Budgets: Budgets{MaxSteps: 12, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3},
|
||||
@@ -114,6 +116,8 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
}
|
||||
|
||||
want := TaskConfig{
|
||||
BotUser: cfg.BotUser,
|
||||
BotEmail: cfg.BotEmail,
|
||||
Models: cfg.Models,
|
||||
Budgets: cfg.Budgets,
|
||||
Dispatch: cfg.Dispatch,
|
||||
@@ -146,7 +150,7 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSONKeys(t, data, "models", "budgets", "dispatch", "diff_cap_lines", "notify", "forge")
|
||||
assertJSONKeys(t, data, "bot_user", "bot_email", "models", "budgets", "dispatch", "diff_cap_lines", "notify", "forge")
|
||||
|
||||
var forgePayload map[string]json.RawMessage
|
||||
var payload map[string]json.RawMessage
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/skill"
|
||||
)
|
||||
|
||||
@@ -120,22 +121,23 @@ func (a AgentStage) Stage() Stage {
|
||||
}
|
||||
|
||||
req := agentexec.Request{
|
||||
Version: agentexec.ProtocolVersion,
|
||||
TaskID: tc.Task.ID,
|
||||
Attempt: tc.Task.Attempt,
|
||||
Stage: a.Name,
|
||||
Workflow: tc.Task.Workflow,
|
||||
Model: modelRef,
|
||||
Mission: missionWithSkill(tc, a.Mission(tc)),
|
||||
ExtraRules: extraRules,
|
||||
ReadOnly: a.ReadOnly,
|
||||
Budget: budget,
|
||||
Gate: gate,
|
||||
Preflight: preflight,
|
||||
Protection: protection,
|
||||
Notes: tc.Task.Notes,
|
||||
CaptureTools: captureTools,
|
||||
Plugins: pluginSpecs(tc.SkillPlugins),
|
||||
Version: agentexec.ProtocolVersion,
|
||||
TaskID: tc.Task.ID,
|
||||
Attempt: tc.Task.Attempt,
|
||||
Stage: a.Name,
|
||||
Workflow: tc.Task.Workflow,
|
||||
Model: modelRef,
|
||||
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
|
||||
Mission: missionWithSkill(tc, a.Mission(tc)),
|
||||
ExtraRules: extraRules,
|
||||
ReadOnly: a.ReadOnly,
|
||||
Budget: budget,
|
||||
Gate: gate,
|
||||
Preflight: preflight,
|
||||
Protection: protection,
|
||||
Notes: tc.Task.Notes,
|
||||
CaptureTools: captureTools,
|
||||
Plugins: pluginSpecs(tc.SkillPlugins),
|
||||
}
|
||||
res, err := tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter(a.Name))
|
||||
|
||||
@@ -163,17 +165,15 @@ func (a AgentStage) Stage() Stage {
|
||||
return fmt.Errorf("persist agent notes: %w", saveErr)
|
||||
}
|
||||
}
|
||||
tc.Task.TokensUsed += res.TokensUsed
|
||||
tc.Task.Iterations += res.Iterations
|
||||
if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, a.Name, res.Summary, agentFinishData(res, modelRef)); emitErr != nil {
|
||||
return fmt.Errorf("persist agent finish: %w", emitErr)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("agent run: %w", err)
|
||||
}
|
||||
|
||||
tc.Task.TokensUsed += res.TokensUsed
|
||||
tc.Task.Iterations += res.Iterations
|
||||
tc.Emit("agent_finish", a.Name, res.Summary, map[string]any{
|
||||
"status": res.Status, "stop_reason": res.StopReason,
|
||||
"tokens": res.TokensUsed, "iterations": res.Iterations, "model": modelRef,
|
||||
})
|
||||
|
||||
if res.Status != agentexec.StatusPassed {
|
||||
detail := res.Detail
|
||||
if detail == "" {
|
||||
@@ -194,6 +194,23 @@ func (a AgentStage) Stage() Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
func modelContextBudget(cfg config.Config, modelRef string) int {
|
||||
limits := cfg.ModelLimits[modelRef]
|
||||
if limits.ContextWindow <= limits.MaxOutputTokens {
|
||||
return 0
|
||||
}
|
||||
return limits.ContextWindow - limits.MaxOutputTokens
|
||||
}
|
||||
|
||||
func agentFinishData(res agentexec.Result, modelRef string) map[string]any {
|
||||
return map[string]any{
|
||||
"status": res.Status, "stop_reason": res.StopReason,
|
||||
"tokens": res.TokensUsed, "iterations": res.Iterations, "model": modelRef,
|
||||
"prompt_tokens": res.Usage.PromptTokens, "completion_tokens": res.Usage.CompletionTokens,
|
||||
"cached_tokens": res.Usage.CachedTokens, "cache_creation_tokens": res.Usage.CacheCreationTokens,
|
||||
}
|
||||
}
|
||||
|
||||
// GateFromRepo converts the repo's configured command lists into an
|
||||
// agent execution gate.
|
||||
func GateFromRepo(repo config.Repo, budgets config.Budgets) agentexec.Gate {
|
||||
|
||||
@@ -7,13 +7,15 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// Bounds on how much of a failing gate command's output rides along at each
|
||||
// point in this stage. They serve different purposes and are sized
|
||||
// independently, not derived from one another:
|
||||
// - baselineWarnLogBytes is a daemon log line -- kept short so one baseline
|
||||
// failure doesn't dominate the log around it.
|
||||
// - baselineWarnLogBytes is the tail shown in daemon/container logs. Test
|
||||
// runners put the useful failure after their long list of passing packages,
|
||||
// so keeping the head made the operator log actively misleading.
|
||||
// - baselineMissionBytes is what the builder agent sees -- generous, since
|
||||
// it needs enough context to actually diagnose the failure.
|
||||
// - baselineParkOutputBytes is what a human (or Archie's own chat tools)
|
||||
@@ -23,7 +25,7 @@ import (
|
||||
// see the actual compiler error. It stays comfortably under the store's
|
||||
// own park-reason cap (see internal/store's Task.ParkReason clip).
|
||||
const (
|
||||
baselineWarnLogBytes = 200
|
||||
baselineWarnLogBytes = 2048
|
||||
baselineMissionBytes = 3000
|
||||
baselineParkOutputBytes = 2048
|
||||
)
|
||||
@@ -46,7 +48,7 @@ func StageBaselineGate() Stage {
|
||||
}
|
||||
tc.Log.Warn("baseline red -- auto-fixing pre-existing gate failure",
|
||||
"cmd", strings.Join(argv, " "),
|
||||
"err", clip(string(out), baselineWarnLogBytes))
|
||||
"err", clipTail(string(out), baselineWarnLogBytes))
|
||||
|
||||
// Run builder to fix the failure via TDD.
|
||||
mission := fmt.Sprintf(
|
||||
@@ -65,13 +67,14 @@ func StageBaselineGate() Stage {
|
||||
|
||||
modelRef := tc.Cfg.Models["builder"]
|
||||
req := agentexec.Request{
|
||||
Version: agentexec.ProtocolVersion,
|
||||
TaskID: tc.Task.ID,
|
||||
Attempt: tc.Task.Attempt,
|
||||
Stage: "baseline-fix",
|
||||
Workflow: tc.Task.Workflow,
|
||||
Model: modelRef,
|
||||
Mission: mission,
|
||||
Version: agentexec.ProtocolVersion,
|
||||
TaskID: tc.Task.ID,
|
||||
Attempt: tc.Task.Attempt,
|
||||
Stage: "baseline-fix",
|
||||
Workflow: tc.Task.Workflow,
|
||||
Model: modelRef,
|
||||
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
|
||||
Mission: mission,
|
||||
Budget: agentexec.Budget{
|
||||
MaxSteps: tc.Cfg.Budgets.MaxSteps,
|
||||
WallClock: tc.Cfg.Budgets.WallClock.Std(),
|
||||
@@ -81,6 +84,14 @@ func StageBaselineGate() Stage {
|
||||
}
|
||||
|
||||
res, agentErr := tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter("baseline-fix"))
|
||||
if agentErr != nil && res.Version == 0 {
|
||||
return fmt.Errorf("baseline-fix agent run: %w", agentErr)
|
||||
}
|
||||
tc.Task.TokensUsed += res.TokensUsed
|
||||
tc.Task.Iterations += res.Iterations
|
||||
if emitErr := tc.EmitDurable(ctx, events.KindAgentFinish, "baseline-fix", res.Summary, agentFinishData(res, modelRef)); emitErr != nil {
|
||||
return fmt.Errorf("persist baseline-fix agent finish: %w", emitErr)
|
||||
}
|
||||
if agentErr != nil {
|
||||
return fmt.Errorf("baseline-fix agent run: %w", agentErr)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
@@ -12,10 +13,114 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
func TestStageBaselineGateAccountsForRepairAgentUsage(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
runGit(t, dir, "init")
|
||||
script := filepath.Join(dir, "gate.sh")
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := agentRunnerFunc(func(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
return agentexec.Result{
|
||||
Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed,
|
||||
TokensUsed: 120, Iterations: 3,
|
||||
Usage: agentexec.Usage{PromptTokens: 100, CompletionTokens: 20, TotalTokens: 120, CachedTokens: 80},
|
||||
}, nil
|
||||
})
|
||||
task := &store.Task{ID: 1, Attempt: 1, Owner: "o", Repo: "r"}
|
||||
tc := &TaskContext{
|
||||
Task: task, Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}},
|
||||
Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}},
|
||||
Agent: runner, Trees: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"},
|
||||
Dir: dir, Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := StageBaselineGate().Run(t.Context(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.TokensUsed != 120 || task.Iterations != 3 {
|
||||
t.Fatalf("baseline usage = %d tokens/%d iterations, want 120/3", task.TokensUsed, task.Iterations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageBaselineGateWarningIncludesFailureTail(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
script := filepath.Join(dir, "gate.sh")
|
||||
// Pad past baselineWarnLogBytes (2048) so clipTail short-circuit does
|
||||
// NOT save head-clipping from being detected. The marker near the END
|
||||
// would otherwise be inside the window either way; a marker past the
|
||||
// window asserts the direction.
|
||||
body := "echo headmarker; head -c 5000 /dev/zero | tr '\\0' x; echo; echo tailmarker; exit 1\n"
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\n"+body), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
tc := &TaskContext{
|
||||
Task: &store.Task{ID: 1, Owner: "o", Repo: "r"},
|
||||
Repo: config.Repo{Gate: [][]string{{"sh", script}}},
|
||||
Agent: alwaysFailingRunner,
|
||||
Dir: dir,
|
||||
Log: slog.New(slog.NewJSONHandler(&logs, nil)),
|
||||
}
|
||||
|
||||
_ = StageBaselineGate().Run(t.Context(), tc)
|
||||
logsStr := logs.String()
|
||||
if !strings.Contains(logsStr, "tailmarker") {
|
||||
t.Fatalf("baseline warning omitted the useful failure tail: %s", logsStr)
|
||||
}
|
||||
if strings.Contains(logsStr, "headmarker") {
|
||||
t.Fatalf("baseline warning included the head marker -- clip is retaining the head instead of the tail")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStageBaselineGateAgentRunErrorSkipsAgentFinish pins the ordering
|
||||
// inside StageBaselineGate: when the baseline-fix agent returns an error,
|
||||
// the stage must surface that error WITHOUT first emitting an
|
||||
// agent_finish event whose status/stop_reason/tokens are all zero. AgentStage
|
||||
// (internal/domain/workflow/agent.go) bails on every error path before its
|
||||
// own agent_finish emit, so the baseline-fix path must match.
|
||||
func TestStageBaselineGateAgentRunErrorSkipsAgentFinish(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
script := filepath.Join(dir, "gate.sh")
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bus := events.NewBus()
|
||||
sub := bus.Subscribe(8)
|
||||
t.Cleanup(sub.Close)
|
||||
runner := agentRunnerFunc(func(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) {
|
||||
return agentexec.Result{}, errors.New("simulated transport failure")
|
||||
})
|
||||
task := &store.Task{ID: 1, Owner: "o", Repo: "r"}
|
||||
tc := &TaskContext{
|
||||
Task: task,
|
||||
Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}},
|
||||
Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}},
|
||||
Agent: runner,
|
||||
Bus: bus,
|
||||
Dir: dir,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := StageBaselineGate().Run(t.Context(), tc); err == nil {
|
||||
t.Fatal("expected StageBaselineGate to surface the agent error")
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case ev := <-sub.C:
|
||||
if ev.Kind == "agent_finish" {
|
||||
t.Fatalf("baseline-fix errored but agent_finish was still published: %+v", ev)
|
||||
}
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fakeForge implements forge.Forge for TestStageCommitPushCloses.
|
||||
type fakeForge struct {
|
||||
closed int
|
||||
|
||||
@@ -7,6 +7,7 @@ package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
@@ -119,6 +120,29 @@ func (tc *TaskContext) Emit(kind, stage, detail string, data map[string]any) {
|
||||
})
|
||||
}
|
||||
|
||||
// EmitDurable persists evaluation-critical telemetry before publishing it to
|
||||
// the lossy live bus. The assigned ID tells the daemon sink to broadcast
|
||||
// without inserting a duplicate row.
|
||||
func (tc *TaskContext) EmitDurable(ctx context.Context, kind, stage, detail string, data map[string]any) error {
|
||||
if tc.Store == nil {
|
||||
tc.Emit(kind, stage, detail, data)
|
||||
return nil
|
||||
}
|
||||
event := events.Event{
|
||||
At: time.Now().UTC(), Kind: kind, TaskID: tc.Task.ID, Repo: tc.Task.Owner + "/" + tc.Task.Repo,
|
||||
Issue: tc.Task.IssueNumber, Workflow: tc.Task.Workflow, Stage: stage, Detail: detail, Data: data,
|
||||
}
|
||||
id, err := tc.Store.InsertEvent(ctx, event)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
event.ID = id
|
||||
if tc.Bus != nil {
|
||||
tc.Bus.Publish(event)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// toolCallReporter builds the agentexec.ToolCallReporter an agent stage
|
||||
// passes to tc.Agent.Run, so every completed tool call during that run
|
||||
// surfaces as a tool_call event on the task timeline (archie-core-467's
|
||||
@@ -248,6 +272,9 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) {
|
||||
data := map[string]any{"duration_ms": time.Since(started).Milliseconds()}
|
||||
if err != nil {
|
||||
data["error"] = err.Error()
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
data["interrupted"] = true
|
||||
}
|
||||
}
|
||||
tc.Emit(events.KindStageFinish, stage.Name, "", data)
|
||||
|
||||
|
||||
@@ -15,7 +15,13 @@ const (
|
||||
KindTaskQueued = "task_queued"
|
||||
KindStageStart = "stage_start"
|
||||
KindStageFinish = "stage_finish" // data: duration_ms, error
|
||||
KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model
|
||||
// KindAgentFinish carries the stage's token economics as well as its
|
||||
// outcome: tokens is the run total (agentexec.Result.TokensUsed) and the
|
||||
// prompt/completion/cached/cache_creation breakdown is the provider's own
|
||||
// accounting, forwarded verbatim for evaluation. The breakdown is absent
|
||||
// on events persisted before it was carried across the agent boundary, so
|
||||
// consumers must treat each field as optional rather than zero.
|
||||
KindAgentFinish = "agent_finish" // data: status, stop_reason, tokens, iterations, model, prompt_tokens, completion_tokens, cached_tokens, cache_creation_tokens
|
||||
// KindToolCall marks one completed tool invocation during an agent
|
||||
// stage run (archie-core-467's task-transcript counterpart -- the
|
||||
// interactive chat gateway surfaces its own tool calls separately via
|
||||
@@ -31,9 +37,12 @@ const (
|
||||
// intervention is recorded in the tasks table but invisible on the
|
||||
// timeline and the activity stream -- the one kind of event most worth
|
||||
// seeing, because it explains why a task changed course.
|
||||
KindHumanApproved = "human_approved"
|
||||
KindHumanRejected = "human_rejected"
|
||||
KindTaskRetried = "task_retried"
|
||||
KindHumanApproved = "human_approved"
|
||||
KindHumanRejected = "human_rejected"
|
||||
// KindTaskRetried records what the retry was escaping from. RetryTask
|
||||
// clears stage and park_reason in the same statement that increments the
|
||||
// count, so this event is the only place that context survives.
|
||||
KindTaskRetried = "task_retried" // data: retry_count, previous_stage, previous_reason
|
||||
KindTaskCancelled = "task_cancelled"
|
||||
KindTaskStopped = "task_stopped"
|
||||
KindTaskAbandoned = "task_abandoned"
|
||||
|
||||
@@ -204,8 +204,9 @@ func (s *sqliteSessionStore) Close() error {
|
||||
}
|
||||
|
||||
func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord) (TurnRecord, TurnClaim, error) {
|
||||
if initial.TurnID == "" {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: turn ID is required")
|
||||
initial, initialToolCalls, err := prepareInitialTurn(initial, time.Now().UTC())
|
||||
if err != nil {
|
||||
return TurnRecord{}, "", err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -216,6 +217,22 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
// Claim by writing first. Under WAL, a transaction that reads and then
|
||||
// upgrades to a writer can fail immediately with SQLITE_BUSY_SNAPSHOT;
|
||||
// busy_timeout only waits for ordinary writer contention. INSERT ... ON
|
||||
// CONFLICT acquires writer intent before any snapshot read, so concurrent
|
||||
// claimers wait normally and the loser can inspect the committed turn.
|
||||
inserted, err := insertInitialTurn(ctx, tx, initial, initialToolCalls)
|
||||
if err != nil {
|
||||
return TurnRecord{}, "", err
|
||||
}
|
||||
if inserted {
|
||||
if err := tx.Commit(); err != nil {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: commit: %w", err)
|
||||
}
|
||||
return initial, TurnClaimOwned, nil
|
||||
}
|
||||
|
||||
var turn TurnRecord
|
||||
var createdMS, updatedMS int64
|
||||
var toolCallsRaw string
|
||||
@@ -228,61 +245,6 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord)
|
||||
&turn.InputMessageID, &turn.AssistantMessageID, &turn.PartialText,
|
||||
&turn.ResponseText, &toolCallsRaw, &turn.Error, &createdMS, &updatedMS,
|
||||
)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
now := time.Now().UTC()
|
||||
initial.Status = TurnStatusRunning
|
||||
initial.Attempt = 1
|
||||
if initial.CreatedAt.IsZero() {
|
||||
initial.CreatedAt = now
|
||||
}
|
||||
initial.UpdatedAt = now
|
||||
initialToolCalls, marshalErr := marshalToolCalls(initial.ToolCalls)
|
||||
if marshalErr != nil {
|
||||
return TurnRecord{}, "", marshalErr
|
||||
}
|
||||
// insertErr is deliberately its own name, not err: this whole block
|
||||
// is inside `if errors.Is(err, sql.ErrNoRows)`, so reusing err here
|
||||
// would shadow the outer err for the rest of the block -- including
|
||||
// the retry read below, whose result must reach the outer `if err
|
||||
// != nil` after this block closes. A shadowed reassignment there
|
||||
// would go out of scope silently, leaving the outer err at its
|
||||
// original sql.ErrNoRows value regardless of how the retry read
|
||||
// actually went.
|
||||
result, insertErr := tx.ExecContext(ctx, `
|
||||
INSERT INTO turns (
|
||||
turn_id, session_id, source_id, status, attempt, owner_id,
|
||||
input_message_id, assistant_message_id, partial_text,
|
||||
response_text, tool_calls, error, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(turn_id) DO NOTHING`, turnValues(initial, initialToolCalls)...)
|
||||
if insertErr != nil {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: insert: %w", insertErr)
|
||||
}
|
||||
affected, insertErr := result.RowsAffected()
|
||||
if insertErr != nil {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: rows affected: %w", insertErr)
|
||||
}
|
||||
if affected == 1 {
|
||||
if err := tx.Commit(); err != nil {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: claim turn: commit: %w", err)
|
||||
}
|
||||
return initial, TurnClaimOwned, nil
|
||||
}
|
||||
// Another connection inserted the same turn between our read and
|
||||
// insert. Read it in this transaction and apply the normal claim
|
||||
// state machine instead of surfacing a uniqueness error. This
|
||||
// assigns the OUTER err (see above) -- it is what the `if err !=
|
||||
// nil` check below this block actually sees.
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT turn_id, session_id, source_id, status, attempt, owner_id,
|
||||
input_message_id, assistant_message_id, partial_text,
|
||||
response_text, tool_calls, error, created_at, updated_at
|
||||
FROM turns WHERE turn_id = ?`, initial.TurnID).Scan(
|
||||
&turn.TurnID, &turn.SessionID, &turn.SourceID, &turn.Status, &turn.Attempt, &turn.OwnerID,
|
||||
&turn.InputMessageID, &turn.AssistantMessageID, &turn.PartialText,
|
||||
&turn.ResponseText, &toolCallsRaw, &turn.Error, &createdMS, &updatedMS,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: read turn: %w", err)
|
||||
}
|
||||
@@ -291,7 +253,10 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord)
|
||||
if turn.ToolCalls, err = unmarshalToolCalls(toolCallsRaw); err != nil {
|
||||
return TurnRecord{}, "", err
|
||||
}
|
||||
return claimExistingTurn(ctx, tx, turn, initial)
|
||||
}
|
||||
|
||||
func claimExistingTurn(ctx context.Context, tx *sql.Tx, turn, initial TurnRecord) (TurnRecord, TurnClaim, error) {
|
||||
switch turn.Status {
|
||||
case TurnStatusCompleted:
|
||||
return turn, TurnClaimCompleted, nil
|
||||
@@ -341,6 +306,38 @@ func (s *sqliteSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord)
|
||||
}
|
||||
}
|
||||
|
||||
func insertInitialTurn(ctx context.Context, tx *sql.Tx, initial TurnRecord, toolCalls string) (bool, error) {
|
||||
result, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO turns (
|
||||
turn_id, session_id, source_id, status, attempt, owner_id,
|
||||
input_message_id, assistant_message_id, partial_text,
|
||||
response_text, tool_calls, error, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(turn_id) DO NOTHING`, turnValues(initial, toolCalls)...)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("sessionstore: claim turn: insert: %w", err)
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("sessionstore: claim turn: rows affected: %w", err)
|
||||
}
|
||||
return affected == 1, nil
|
||||
}
|
||||
|
||||
func prepareInitialTurn(initial TurnRecord, now time.Time) (TurnRecord, string, error) {
|
||||
if initial.TurnID == "" {
|
||||
return TurnRecord{}, "", fmt.Errorf("sessionstore: turn ID is required")
|
||||
}
|
||||
initial.Status = TurnStatusRunning
|
||||
initial.Attempt = 1
|
||||
if initial.CreatedAt.IsZero() {
|
||||
initial.CreatedAt = now
|
||||
}
|
||||
initial.UpdatedAt = now
|
||||
toolCalls, err := marshalToolCalls(initial.ToolCalls)
|
||||
return initial, toolCalls, err
|
||||
}
|
||||
|
||||
func (s *sqliteSessionStore) RecoverTurns(ctx context.Context, ownerID string) error {
|
||||
if ownerID == "" {
|
||||
return fmt.Errorf("sessionstore: recovery owner ID is required")
|
||||
|
||||
@@ -4,43 +4,23 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestClaimTurnConcurrentInsertRaceNeverReturnsAnError guards against a
|
||||
// variable-shadowing bug in ClaimTurn (session_store_sqlite.go), fixed
|
||||
// alongside this test: the branch handling "another connection inserted the
|
||||
// same turn between our read and insert" used to write its retry read's
|
||||
// result into an `err` shadowed inside the `errors.Is(err, sql.ErrNoRows)`
|
||||
// block by an earlier `result, err := tx.ExecContext(...)`. That shadowed
|
||||
// err went out of scope at the block's closing brace, so the outer err
|
||||
// checked afterward was still sql.ErrNoRows from the original read -- the
|
||||
// loser of that race would always return an error wrapped
|
||||
// "sessionstore: read turn: %w", even though the comment's own stated
|
||||
// intent is "apply the normal claim state machine instead of surfacing a
|
||||
// uniqueness error." Confirmed via careful reading of Go's block-scoping
|
||||
// rules, not assumed.
|
||||
// TestClaimTurnConcurrentInsertRaceResolvesToOneOwner verifies that ordinary
|
||||
// contention between processes sharing the session database is resolved by
|
||||
// ClaimTurn itself. Callers must not need to recognize and retry SQLite's
|
||||
// SQLITE_BUSY or SQLITE_BUSY_SNAPSHOT implementation details.
|
||||
//
|
||||
// Honest limitation: this test could NOT be made to reproduce that exact
|
||||
// branch through genuine concurrent access. A one-off diagnostic (real
|
||||
// two-connection race, sleep-widened to force overlap, reverted before this
|
||||
// commit -- never present in a shipped file) showed the loser instead fails
|
||||
// its own INSERT outright with SQLITE_BUSY_SNAPSHOT under WAL mode with this
|
||||
// driver, before ON CONFLICT DO NOTHING can ever report affected=0. That
|
||||
// means the specific "0 rows affected" branch this bug lived in may be
|
||||
// effectively unreachable via a same-driver, same-journal-mode race today.
|
||||
// The fix stands regardless -- the shadowing was real, wrong on its own
|
||||
// terms, and free to correct -- but this test cannot claim to exercise the
|
||||
// exact line that was fixed. What it verifies is the weaker, still real
|
||||
// property that matters operationally: many genuinely concurrent
|
||||
// same-turn-ID claims across separate connections never produce the bug's
|
||||
// specific error signature. Treat this as a guard against a regression
|
||||
// becoming reachable (a different SQLite version, journal mode, or driver
|
||||
// with weaker snapshot isolation), not as proof the original bug was ever
|
||||
// live in production.
|
||||
// Two invariants must hold under contention: every ClaimTurn call returns
|
||||
// without error, and EXACTLY ONE of the racers ends up TurnClaimOwned while
|
||||
// the other observes the committed row and returns a non-owning claim.
|
||||
// The second invariant matters more than the first: a bug that returns
|
||||
// TurnClaimOwned to both racers means two archied processes drive the same
|
||||
// turn to completion, and the assistant reply gets emitted twice to the
|
||||
// chat. The first invariant alone would not catch that.
|
||||
//
|
||||
// A single sqliteSessionStore instance cannot exhibit any of this: its own
|
||||
// mutex serializes every ClaimTurn call against that instance's connection,
|
||||
@@ -48,20 +28,11 @@ import (
|
||||
// against the same file-backed database -- the real-world shape of the
|
||||
// scenario (two archied/worker processes or connections sharing one session
|
||||
// DB).
|
||||
//
|
||||
// SQLite's own write-lock contention (SQLITE_BUSY / SQLITE_BUSY_SNAPSHOT,
|
||||
// "database is locked") is infrastructure noise distinct from the bug: it
|
||||
// comes from BeginTx/ExecContext/Commit failing outright and is wrapped
|
||||
// with a different prefix ("claim turn: begin/insert/rows affected/commit").
|
||||
// Only the "sessionstore: read turn:" wrap was the bug's unique signature,
|
||||
// so transient busy errors are retried rather than treated as failures.
|
||||
func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) {
|
||||
func TestClaimTurnConcurrentInsertRaceResolvesToOneOwner(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "sessions.db")
|
||||
|
||||
const stores = 2
|
||||
const trials = 100
|
||||
const maxRetriesPerAttempt = 20
|
||||
const busyRetryDelay = time.Millisecond
|
||||
|
||||
openers := make([]TurnLedger, stores)
|
||||
for i := range openers {
|
||||
@@ -84,23 +55,9 @@ func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
now := time.UnixMilli(1000).UTC()
|
||||
|
||||
claimRetryingBusy := func(ledger TurnLedger, initial TurnRecord) error {
|
||||
var err error
|
||||
for range maxRetriesPerAttempt {
|
||||
_, _, err = ledger.ClaimTurn(ctx, initial)
|
||||
if err == nil || !strings.Contains(err.Error(), "database is locked") {
|
||||
return err
|
||||
}
|
||||
time.Sleep(busyRetryDelay)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Each trial races the two independent stores over one turn ID, then waits
|
||||
// before starting the next trial. Running every trial at once adds 100-way
|
||||
// global writer contention that is unrelated to the same-turn insert race
|
||||
// this regression covers and can exhaust the bounded SQLITE_BUSY retries
|
||||
// before any competing transaction gets scheduled to finish.
|
||||
// before starting the next trial. This isolates the same-turn claim race
|
||||
// from unrelated 100-way global writer contention.
|
||||
for trial := range trials {
|
||||
turnID := fmt.Sprintf("race-turn-%d", trial)
|
||||
initial := TurnRecord{
|
||||
@@ -112,6 +69,7 @@ func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) {
|
||||
UpdatedAt: now,
|
||||
}
|
||||
errs := make([]error, stores)
|
||||
claims := make([]TurnClaim, stores)
|
||||
var wg sync.WaitGroup
|
||||
var start sync.WaitGroup
|
||||
start.Add(1)
|
||||
@@ -120,20 +78,25 @@ func TestClaimTurnConcurrentInsertRaceNeverReturnsAnError(t *testing.T) {
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
start.Wait()
|
||||
errs[i] = claimRetryingBusy(openers[i], initial)
|
||||
_, claims[i], errs[i] = openers[i].ClaimTurn(ctx, initial)
|
||||
}(i)
|
||||
}
|
||||
start.Done()
|
||||
wg.Wait()
|
||||
|
||||
for i, err := range errs {
|
||||
if err == nil {
|
||||
continue
|
||||
if err != nil {
|
||||
t.Fatalf("trial %d, store %d: ClaimTurn() unexpected error = %v", trial, i, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "sessionstore: read turn:") {
|
||||
t.Fatalf("trial %d, store %d: ClaimTurn() error = %v -- a losing racer surfaced the winner's insert as a read failure instead of applying the normal claim state machine", trial, i, err)
|
||||
}
|
||||
owners := 0
|
||||
for _, c := range claims {
|
||||
if c == TurnClaimOwned {
|
||||
owners++
|
||||
}
|
||||
t.Fatalf("trial %d, store %d: ClaimTurn() unexpected error = %v", trial, i, err)
|
||||
}
|
||||
if owners != 1 {
|
||||
t.Fatalf("trial %d: expected exactly one TurnClaimOwned across %d racers, got %d (claims=%v)", trial, stores, owners, claims)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -225,18 +225,28 @@ func applyDispatchDefaults(cfg *config.Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// applyIdentityDefaults derives the commit email for a single-identity
|
||||
// deployment. Multi-identity deployments configure each identity explicitly.
|
||||
// applyIdentityDefaults derives forge-appropriate commit emails wherever the
|
||||
// operator omitted one, for both deployment shapes.
|
||||
func applyIdentityDefaults(cfg *config.Config) {
|
||||
if len(cfg.Identities) > 0 || cfg.BotUser == "" || cfg.BotEmail != "" {
|
||||
return
|
||||
if len(cfg.Identities) > 0 {
|
||||
for i := range cfg.Identities {
|
||||
cfg.Identities[i].BotEmail = defaultBotEmail(cfg.Identities[i].Forge.Type, cfg.Identities[i].BotUser, cfg.Identities[i].BotEmail)
|
||||
}
|
||||
}
|
||||
switch cfg.Forge.Type {
|
||||
cfg.BotEmail = defaultBotEmail(cfg.Forge.Type, cfg.BotUser, cfg.BotEmail)
|
||||
}
|
||||
|
||||
func defaultBotEmail(forgeType, user, email string) string {
|
||||
if user == "" || email != "" {
|
||||
return email
|
||||
}
|
||||
switch forgeType {
|
||||
case forgeTypeGitHub:
|
||||
cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com"
|
||||
return user + "@users.noreply.github.com"
|
||||
case forgeTypeGitea:
|
||||
cfg.BotEmail = cfg.BotUser + "@gitea.local"
|
||||
return user + "@gitea.local"
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
// applyContainerDefaults makes managed task workers usable without an explicit
|
||||
|
||||
@@ -63,6 +63,23 @@ func TestApplyForgeDefaultsIntake(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyIdentityDefaultsDerivesEmailPerIdentity(t *testing.T) {
|
||||
cfg := &config.Config{Identities: []config.IdentityConfig{
|
||||
{BotUser: "github-bot", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
{BotUser: "gitea-bot", Forge: config.Forge{Type: forgeTypeGitea}},
|
||||
{BotUser: "explicit", BotEmail: "bot@example.test", Forge: config.Forge{Type: forgeTypeGitHub}},
|
||||
}}
|
||||
|
||||
applyIdentityDefaults(cfg)
|
||||
|
||||
want := []string{"github-bot@users.noreply.github.com", "gitea-bot@gitea.local", "bot@example.test"}
|
||||
for i := range want {
|
||||
if cfg.Identities[i].BotEmail != want[i] {
|
||||
t.Errorf("identity %d BotEmail = %q, want %q", i, cfg.Identities[i].BotEmail, want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCaptureDefaultsFillsZeroValues(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
applyCaptureDefaults(cfg)
|
||||
|
||||
@@ -74,6 +74,7 @@ type TaskEvents interface {
|
||||
type WorkflowStore interface {
|
||||
Update(ctx context.Context, t *Task) error
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
InsertEvent(ctx context.Context, e events.Event) (int64, error)
|
||||
}
|
||||
|
||||
// CaptureStore persists unbound inbound webhook captures -- events with no
|
||||
|
||||
@@ -12,14 +12,16 @@ import (
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Subjects for the two store.TaskStore methods workflow stages call mid-run.
|
||||
const (
|
||||
SubjectUpdate = "archie.store.update"
|
||||
SubjectTransition = "archie.store.transition"
|
||||
SubjectUpdate = "archie.store.update"
|
||||
SubjectTransition = "archie.store.transition"
|
||||
SubjectInsertEvent = "archie.store.insert_event"
|
||||
)
|
||||
|
||||
// UpdateRequest mirrors store.TaskStore.Update's argument.
|
||||
@@ -35,9 +37,14 @@ type TransitionRequest struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
type InsertEventRequest struct {
|
||||
Event events.Event `json:"event"`
|
||||
}
|
||||
|
||||
// Response carries the result of an RPC. Error is empty on success.
|
||||
type Response struct {
|
||||
natsrpc.Envelope
|
||||
ID int64 `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
// Server handles storerpc requests against the daemon's TaskStore.
|
||||
@@ -52,9 +59,20 @@ func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectUpdate, Handler: s.handleUpdate},
|
||||
{Subject: SubjectTransition, Handler: s.handleTransition},
|
||||
{Subject: SubjectInsertEvent, Handler: s.handleInsertEvent},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleInsertEvent(msg *nats.Msg) {
|
||||
var req InsertEventRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.reply(msg, err)
|
||||
return
|
||||
}
|
||||
id, err := s.Store.InsertEvent(context.Background(), req.Event)
|
||||
natsrpc.Respond(msg, s.Log, "storerpc", Response{Envelope: natsrpc.NewEnvelope(err), ID: id})
|
||||
}
|
||||
|
||||
func (s *Server) handleUpdate(msg *nats.Msg) {
|
||||
var req UpdateRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
@@ -106,5 +124,13 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
func (c *Client) InsertEvent(ctx context.Context, event events.Event) (int64, error) {
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectInsertEvent, InsertEventRequest{Event: event})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return resp.ID, resp.Err()
|
||||
}
|
||||
|
||||
// Compile-time check: Client satisfies WorkflowStore.
|
||||
var _ store.WorkflowStore = (*Client)(nil)
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
@@ -108,6 +109,21 @@ func TestClientTransitionPersistsViaServer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientInsertEventPersistsViaServer(t *testing.T) {
|
||||
s, _, client := newTestServer(t)
|
||||
task := enqueueTask(t, s)
|
||||
event := events.Event{Kind: events.KindAgentFinish, TaskID: task.ID, Data: map[string]any{"tokens": 42}}
|
||||
|
||||
id, err := client.InsertEvent(context.Background(), event)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEvent: %v", err)
|
||||
}
|
||||
got, err := s.TaskEvents(context.Background(), task.ID)
|
||||
if err != nil || len(got) != 1 || got[0].ID != id || got[0].Kind != events.KindAgentFinish {
|
||||
t.Fatalf("TaskEvents = (%+v, %v), want persisted agent_finish id %d", got, err, id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientPropagatesServerError(t *testing.T) {
|
||||
s, _, client := newTestServer(t)
|
||||
task := enqueueTask(t, s)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
@@ -53,14 +54,65 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
views := make([]taskView, len(tasks))
|
||||
for i := range tasks {
|
||||
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status)}
|
||||
repoURL, issueURL, prURL := s.taskURLs(tasks[i])
|
||||
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL}
|
||||
}
|
||||
writeJSON(w, views)
|
||||
}
|
||||
|
||||
type taskView struct {
|
||||
store.Task
|
||||
Actions []taskstate.Action `json:"actions"`
|
||||
Actions []taskstate.Action `json:"actions"`
|
||||
RepoURL string `json:"repo_url,omitempty"`
|
||||
IssueURL string `json:"issue_url,omitempty"`
|
||||
PRURL string `json:"pr_url,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) taskURLs(task store.Task) (repoURL, issueURL, prURL string) {
|
||||
if s.Cfg == nil {
|
||||
return "", "", ""
|
||||
}
|
||||
forgeCfg := forgeConfigForTask(s.Cfg.Get(), task)
|
||||
if forgeCfg.Host == "" || task.Owner == "" || task.Repo == "" {
|
||||
return "", "", ""
|
||||
}
|
||||
repoURL = strings.TrimRight(forgeCfg.Host, "/") + "/" + url.PathEscape(task.Owner) + "/" + url.PathEscape(task.Repo)
|
||||
if task.IsForgeBacked() && task.IssueNumber > 0 {
|
||||
issueURL = repoURL + "/issues/" + strconv.Itoa(task.IssueNumber)
|
||||
}
|
||||
if task.PRNumber > 0 {
|
||||
segment := "pull"
|
||||
if forgeCfg.Type == "gitea" {
|
||||
segment = "pulls"
|
||||
}
|
||||
prURL = repoURL + "/" + segment + "/" + strconv.Itoa(task.PRNumber)
|
||||
}
|
||||
return repoURL, issueURL, prURL
|
||||
}
|
||||
|
||||
func forgeConfigForTask(cfg config.Config, task store.Task) config.Forge {
|
||||
for _, identity := range cfg.Identities {
|
||||
if task.Identity != "" && identity.Name == task.Identity {
|
||||
return identity.Forge
|
||||
}
|
||||
}
|
||||
var matched *config.Forge
|
||||
for i := range cfg.Identities {
|
||||
identity := &cfg.Identities[i]
|
||||
for _, repo := range identity.Repos {
|
||||
if repo.Owner == task.Owner && repo.Name == task.Repo {
|
||||
if matched != nil {
|
||||
return cfg.Forge
|
||||
}
|
||||
forgeCopy := identity.Forge
|
||||
matched = &forgeCopy
|
||||
}
|
||||
}
|
||||
}
|
||||
if matched != nil {
|
||||
return *matched
|
||||
}
|
||||
return cfg.Forge
|
||||
}
|
||||
|
||||
func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -122,7 +174,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
ID: outcome.eventID,
|
||||
Kind: outcome.kind, TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber,
|
||||
Detail: outcome.detail,
|
||||
Detail: outcome.detail, Data: outcome.data,
|
||||
})
|
||||
writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id})
|
||||
}
|
||||
@@ -268,6 +320,7 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
|
||||
type actionOutcome struct {
|
||||
kind string
|
||||
detail string
|
||||
data map[string]any
|
||||
eventID int64
|
||||
}
|
||||
|
||||
@@ -380,7 +433,15 @@ func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *sto
|
||||
if s.storeFailed(w, s.Store.RetryTask(ctx, task.ID, store.StatusParked, "")) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{kind: events.KindTaskRetried, detail: "retried via the dashboard"}
|
||||
return &actionOutcome{
|
||||
kind: events.KindTaskRetried,
|
||||
detail: "retried via the dashboard",
|
||||
data: map[string]any{
|
||||
"retry_count": task.RetryCount + 1,
|
||||
"previous_stage": task.Stage,
|
||||
"previous_reason": task.ParkReason,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// retireTask moves a spent task to dead. Failure is logged, not returned:
|
||||
|
||||
@@ -276,6 +276,11 @@ func TestActionsEmitEvents(t *testing.T) {
|
||||
if ev.Kind == "" {
|
||||
t.Error("event Kind is empty")
|
||||
}
|
||||
if tc.action == "retry" {
|
||||
if ev.Data["retry_count"] != 1 || ev.Data["previous_reason"] != tc.reason {
|
||||
t.Errorf("retry event Data = %#v, want retry count and previous failure", ev.Data)
|
||||
}
|
||||
}
|
||||
default:
|
||||
t.Fatalf("%s emitted no event: the activity stream and timeline "+
|
||||
"never show that a human intervened", tc.action)
|
||||
|
||||
@@ -15,10 +15,34 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskURLsUseOwningForgeRoutes(t *testing.T) {
|
||||
srv := &Server{Cfg: config.NewHolder(config.Config{
|
||||
Forge: config.Forge{Type: "github", Host: "https://github.example"},
|
||||
Identities: []config.IdentityConfig{{
|
||||
Name: "gitea", Forge: config.Forge{Type: "gitea", Host: "https://gitea.example"},
|
||||
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
|
||||
}},
|
||||
})}
|
||||
task := store.Task{Owner: "acme", Repo: "widget", IssueNumber: 12, PRNumber: 34, Identity: "gitea"}
|
||||
|
||||
repoURL, issueURL, prURL := srv.taskURLs(task)
|
||||
if repoURL != "https://gitea.example/acme/widget" || issueURL != repoURL+"/issues/12" || prURL != repoURL+"/pulls/34" {
|
||||
t.Fatalf("URLs = %q, %q, %q; want canonical Gitea routes", repoURL, issueURL, prURL)
|
||||
}
|
||||
|
||||
task.Identity = ""
|
||||
task.Owner, task.Repo = "other", "repo"
|
||||
_, _, prURL = srv.taskURLs(task)
|
||||
if prURL != "https://github.example/other/repo/pull/34" {
|
||||
t.Fatalf("GitHub PR URL = %q", prURL)
|
||||
}
|
||||
}
|
||||
|
||||
// Approve requeues from the task's own recorded state rather than anything
|
||||
// the caller supplies, so a stale dashboard cannot approve a task twice.
|
||||
func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {
|
||||
|
||||
+2
-1
@@ -17,10 +17,11 @@ require (
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/samcharles93/ai-sdk v0.1.20 // indirect
|
||||
github.com/samcharles93/ai-sdk v0.1.25 // indirect
|
||||
github.com/traefik/yaegi v0.16.1 // indirect
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.74.4 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
|
||||
+4
-24
@@ -1,7 +1,5 @@
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2 h1:oEEedg1Xgi8drRjqB0f9tfjhLoInE0IYZfZ6zAhQUbY=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
|
||||
@@ -10,8 +8,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -20,22 +16,8 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
|
||||
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
|
||||
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.14.4 h1:efgjZ8cdExAKRuqSg8UPJFprb+l7NlBtSDPhDlw3rO4=
|
||||
github.com/nats-io/nats-server/v2 v2.14.4/go.mod h1:BltdpOYestjbtQSnVO2zGHdg5SGBZjt+GYTgB9LZq/I=
|
||||
github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc=
|
||||
github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
|
||||
@@ -46,16 +28,14 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
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/samcharles93/ai-sdk v0.1.20 h1:Z52dyMN293aV8Cpgjdyyd2zw6oNF5FSXKWfCuxY/3UA=
|
||||
github.com/samcharles93/ai-sdk v0.1.20/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/samcharles93/ai-sdk v0.1.25 h1:30cvHZBw01XRif2cOG/PToC7xTQUZ5DHwMOShT8zSnw=
|
||||
github.com/samcharles93/ai-sdk v0.1.25/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
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.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
@@ -63,10 +43,10 @@ golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
|
||||
|
||||
Vendored
+6
-6
@@ -6,8 +6,8 @@
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${c}"
|
||||
stroke-dashoffset="${c*(1-i/100)}"
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function x(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var S=`archie.setup-complete.dismissed.v1`;function C(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(S),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function w(e=globalThis.localStorage){e?.setItem?.(S,`1`)}var T=new Set([`waiting_human`,`parked`]);function E(e=[]){let t=e.filter(e=>T.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function D(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),m=e(`h1.hero-title`,A()),_=r(`connecting`,`idle`),y=[],b=new Map;S(),D();let x=g(e=>{y.unshift(e),y.splice(50),T()},e=>{_.className=`pill pill-${e===`live`?`ok`:`warn`}`,_.textContent=e});t.addEventListener(`archie:teardown`,x);function S(){n(t,e(`div.hero`,e(`div`,m,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),_),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),T()}function T(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>O(e,b)))}async function D(){try{let[e,t,n,r]=await Promise.all([h.summary(),h.setup().catch(()=>null),h.workflows().catch(()=>null),h.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);T(),k(r),m.textContent=t?.operator?`${A()}, ${t.operator}`:A(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Retry`))}}function k(t){let r=E(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,v({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),v({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),v({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),v({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:N(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=C(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{w(),F(t)}},`×`)))))}function
Line truncated
|
||||
`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await h.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await h.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.storage,t.containers,a),Ce(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?J(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):J(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function J(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?J(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):J(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?J(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):J(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>q(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.<name>] entry so a model role above has something to run on.`);return J(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?J(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budLine truncated
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function x(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var S=`archie.setup-complete.dismissed.v1`;function C(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(S),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function w(e=globalThis.localStorage){e?.setItem?.(S,`1`)}var T=new Set([`waiting_human`,`parked`]);function E(e=[]){let t=e.filter(e=>T.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function D(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),m=e(`h1.hero-title`,A()),_=r(`connecting`,`idle`),y=[],b=new Map;S(),D();let x=g(e=>{y.unshift(e),y.splice(50),T()},e=>{_.className=`pill pill-${e===`live`?`ok`:`warn`}`,_.textContent=e});t.addEventListener(`archie:teardown`,x);function S(){n(t,e(`div.hero`,e(`div`,m,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),_),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),T()}function T(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>O(e,b)))}async function D(){try{let[e,t,n,r]=await Promise.all([h.summary(),h.setup().catch(()=>null),h.workflows().catch(()=>null),h.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);T(),k(r),m.textContent=t?.operator?`${A()}, ${t.operator}`:A(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Retry`))}}function k(t){let r=E(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:D},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,v({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),v({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),v({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),v({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:N(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=C(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{w(),F(t)}},`×`)))))}function
Line truncated
|
||||
`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(pe[t.status]||t.status,me[t.status]||`idle`)))))))):ge(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function ge(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function _e(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await h.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await h.version();n(i,he(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,ye(t.identity,a),be(t.repositories),Se(t.models,t.providers),we(t.budgets,a),Te(t.storage,t.containers,a),De(t.web,a),ve(t.provenance))}return t}function ve(t){return t?.length?J(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>q(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):J(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function J(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function ye(t,n){return t?J(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,q(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),q(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),q(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),q(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),q(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),q(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):J(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function be(t){return t?.length?J(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,xe(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):J(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function xe(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function Se(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>q(Ce(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.<name>] entry so a model role above has something to run on.`);return J(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function Ce(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function we(t,n){return t?J(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,q(`Max steps`,t.max_steps||`Unlimited`,{key:`budLine truncated
|
||||
<div class="chat-page-content">
|
||||
<header class="chat-topbar">
|
||||
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
|
||||
@@ -72,10 +72,10 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;function Ze(){let e=document.createElement(`template`);e.innerHTML=Xe.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function Y(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function Qe(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`;function tt(){let e=document.createElement(`template`);e.innerHTML=et.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function Y(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function nt(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`),i=[],a=null,o=null,s=()=>{i.length&&(n.append(e(`p`,Y(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;t<r.length;t++){let l=r[t];if(l.startsWith("```")){s(),c(),o?(n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=$e(l),d=t+1<r.length?$e(r[t+1]):null;if(u&&d&&et(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=$e(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,Y(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,Y(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,Y(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,Y((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,Y(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function $e(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function et(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function tt(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function nt(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function rt(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?it(t,r):e(`div.chat-bubble-text`,r)))}function it(t,n){let r=t.tool_calls||t.ToolCalls||[],i=[e(`div.chat-tools`)];for(let t of r){let n=!!(t.err||t.Err);i[0].append(e(`div.chat-tool`+(n?`.failed`:``),e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,t.name||t.Name||`tool`),e(`span.chat-tool-summary`,t.err||t.Err||t.output||t.Output||`done`)))}return i.push(Qe(n)),i}function X(e,t){let n=Qe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function at(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),ot(t).append(o),o}function ot(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var st=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(st);return e||(e=u(),localStorage.setItem(st,e)),e}function ct(e){return{text:e,sourceID:u()}}function lt(e){return{...e}}function ut(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?lt(e.turn):ct(r),isRetry:n}}function dt({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,tt(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ft(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,pt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function pt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function mt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function ht(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function gt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{on
Line truncated
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=rt(l),d=t+1<r.length?rt(r[t+1]):null;if(u&&d&&it(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=rt(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,Y(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,Y(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,Y(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,Y((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,Y(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function rt(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function it(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function at(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function ot(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function st(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?ct(t,r):e(`div.chat-bubble-text`,r)))}function ct(t,n){let r=t.tool_calls||t.ToolCalls||[],i=[e(`div.chat-tools`)];for(let t of r){let n=!!(t.err||t.Err);i[0].append(e(`div.chat-tool`+(n?`.failed`:``),e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,t.name||t.Name||`tool`),e(`span.chat-tool-summary`,t.summary||t.Summary||t.err||t.Err||`done`)))}return i.push(nt(n)),i}function X(e,t){let n=nt(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function lt(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),ut(t).append(o),o}function ut(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var dt=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(dt);return e||(e=u(),localStorage.setItem(dt,e)),e}function ft(e){return{text:e,sourceID:u()}}function pt(e){return{...e}}function mt(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?pt(e.turn):ft(r),isRetry:n}}function ht({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,at(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function gt(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,_t(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function _t(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function vt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function yt(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function bt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{
Line truncated
|
||||
|
||||
`);i=a.pop()||``;for(let e of a){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&at(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=lt(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&h.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await h.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{pt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await h.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:D},{path:`/chat`,label:`Chat`,icon:`chat`,view:vt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:V},{path:`/logs`,label:`Logs`,icon:`logs`,view:Ee},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Le},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Ke},{path:`/skills`,label:`Skills`,icon:`skills`,view:H},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:qe},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:pe}],yt=`archie.theme`;function bt(e){document.documentElement.dataset.theme=e,localStorage.setItem(yt,e)}function $(){return localStorage.getItem(yt)||`dark`}function xt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{bt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function St(){bt($());let t=e(`main.main`),r=xt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?Line truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&<(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=pt(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&h.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await h.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{_t({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await h.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let ee={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=ee[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:D},{path:`/chat`,label:`Chat`,icon:`chat`,view:St},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:te},{path:`/logs`,label:`Logs`,icon:`logs`,view:Ae},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Ve},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Xe},{path:`/skills`,label:`Skills`,icon:`skills`,view:ne},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:ae},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ze},{path:`/channels`,label:`Channels`,icon:`channels`,view:oe},{path:`/settings`,label:`Configuration`,icon:`settings`,view:_e}],Ct=`archie.theme`;function wt(e){document.documentElement.dataset.theme=e,localStorage.setItem(Ct,e)}function $(){return localStorage.getItem(Ct)||`dark`}function Tt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{wt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Et(){wt($());let t=e(`main.main`),r=Tt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.spli
Line truncated
|
||||
+14
-23
@@ -4,6 +4,7 @@ import { ago, el, empty, mount, pill, statusKind } from "../base/dom.js";
|
||||
import { statTile } from "../base/statTile.js";
|
||||
import { taskRowA11y } from "./task-row.js";
|
||||
import { initialTaskFilter, taskMatchesStatus } from "./task-filters.js";
|
||||
import { describeTimelineEvent } from "./timeline-event.js";
|
||||
|
||||
/**
|
||||
* Plain-language status labels. One place, so "waiting_human" only ever
|
||||
@@ -41,7 +42,6 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
const requestedTask = Number(params.get("task"));
|
||||
let expandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null;
|
||||
let focusRequestedTask = expandedId !== null;
|
||||
let forgeHost = "";
|
||||
const eventCache = new Map();
|
||||
// Keyed by task id. A single shared string leaked one row's failure into
|
||||
// every other row's action cell.
|
||||
@@ -114,10 +114,7 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
[tasks, forgeHost] = await Promise.all([
|
||||
api.tasks(),
|
||||
api.config().then((cfg) => cfg?.identity?.forge_host || "").catch(() => ""),
|
||||
]);
|
||||
tasks = await api.tasks();
|
||||
renderSummary();
|
||||
renderRows();
|
||||
if (expandedId && tasks.some((task) => String(task.id) === String(expandedId))) {
|
||||
@@ -333,9 +330,9 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
`Archive the local record for "${t.title || "this task"}"?`,
|
||||
);
|
||||
case "open_pr":
|
||||
return taskLink(t, "pulls", t.pr_number, "Open PR");
|
||||
return taskLink(t, "pull_request", t.pr_number, "Open PR");
|
||||
case "open_issue":
|
||||
return taskLink(t, "issues", t.issue_number, "Open issue");
|
||||
return taskLink(t, "issue", t.issue_number, "Open issue");
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -360,16 +357,9 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
}
|
||||
}
|
||||
|
||||
// Both forge links derive from the same host so they can never drift apart:
|
||||
// one place builds the base, both anchors reuse it.
|
||||
function forgeBase(t) {
|
||||
if (!forgeHost || !t.owner || !t.repo) return null;
|
||||
return `${forgeHost.replace(/\/+$/, "")}/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`;
|
||||
}
|
||||
|
||||
function taskLink(t, kind, number, label) {
|
||||
const base = forgeBase(t);
|
||||
if (!base || !number || (kind === "issues" && t.source === "chat")) {
|
||||
const href = kind === "issue" ? t.issue_url : t.pr_url;
|
||||
if (!href || !number || (kind === "issue" && t.source === "chat")) {
|
||||
return el(
|
||||
"button.btn.btn-small",
|
||||
{ type: "button", disabled: true, title: `${label} is unavailable` },
|
||||
@@ -379,7 +369,7 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
return el(
|
||||
"a.btn.btn-small",
|
||||
{
|
||||
href: `${base}/${kind}/${number}`,
|
||||
href,
|
||||
target: "_blank",
|
||||
rel: "noreferrer",
|
||||
onclick: (event) => event.stopPropagation(),
|
||||
@@ -389,7 +379,7 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
}
|
||||
|
||||
function repoLink(t) {
|
||||
const base = forgeBase(t);
|
||||
const base = t.repo_url;
|
||||
if (!base) return null;
|
||||
return el(
|
||||
"a.task-source-link",
|
||||
@@ -405,14 +395,14 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
}
|
||||
|
||||
function issueLink(t) {
|
||||
const base = forgeBase(t);
|
||||
const href = t.issue_url;
|
||||
// A chat-sourced task has no issue on the forge, but its repo may still
|
||||
// exist -- the repo link stays, the issue link does not.
|
||||
if (t.source === "chat" || !base || !t.issue_number) return null;
|
||||
if (t.source === "chat" || !href || !t.issue_number) return null;
|
||||
return el(
|
||||
"a.task-source-link",
|
||||
{
|
||||
href: `${base}/issues/${t.issue_number}`,
|
||||
href,
|
||||
target: "_blank",
|
||||
rel: "noreferrer",
|
||||
title: `Open issue #${t.issue_number} on the forge`,
|
||||
@@ -460,13 +450,14 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
}
|
||||
|
||||
function timelineEntry(ev) {
|
||||
const description = describeTimelineEvent(ev);
|
||||
return el(
|
||||
"li.task-timeline-entry",
|
||||
el("span.task-timeline-dot"),
|
||||
el(
|
||||
"div",
|
||||
el("div.task-timeline-kind", ev.kind || ev.type || "event"),
|
||||
ev.detail && el("div.task-timeline-detail", ev.detail),
|
||||
el("div.task-timeline-kind", description.title),
|
||||
description.detail && el("div.task-timeline-detail", description.detail),
|
||||
el("div.task-timeline-when", ago(ev.at)),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
function words(value) {
|
||||
return String(value || "event")
|
||||
.replaceAll("_", " ")
|
||||
.replace(/\b\w/g, (letter) => letter.toUpperCase());
|
||||
}
|
||||
|
||||
function duration(milliseconds) {
|
||||
const ms = Number(milliseconds);
|
||||
if (!Number.isFinite(ms) || ms < 0) return "";
|
||||
if (ms < 1000) return `${Math.round(ms)} ms`;
|
||||
const seconds = ms / 1000;
|
||||
// Under 60s: 1 dp when seconds < 10, 0 dp otherwise (40.6 s, but 41 s).
|
||||
if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)} s`;
|
||||
const roundedSeconds = Math.round(seconds);
|
||||
const minutes = Math.floor(roundedSeconds / 60);
|
||||
const remSec = roundedSeconds % 60;
|
||||
if (minutes < 60) return remSec === 0 ? `${minutes} min` : `${minutes} min ${remSec} s`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remMin = minutes - hours * 60;
|
||||
return remMin === 0 ? `${hours} h` : `${hours} h ${remMin} min`;
|
||||
}
|
||||
|
||||
function count(value) {
|
||||
const n = Number(value);
|
||||
// Render only for positive counts; zero is treated as "no metric
|
||||
// reported" so a partially-populated agent_finish (pre-v0.1.24 events,
|
||||
// or a failed run whose result is the zero Result) does not appear as
|
||||
// "0 prompt · 0 completion · 0 cached".
|
||||
if (!Number.isFinite(n) || n <= 0) return "";
|
||||
return n.toLocaleString("en-US");
|
||||
}
|
||||
|
||||
export function describeTimelineEvent(ev = {}) {
|
||||
const data = ev.data || {};
|
||||
const stage = ev.stage || "unknown stage";
|
||||
const workflow = ev.workflow ? `${ev.workflow} workflow` : "";
|
||||
|
||||
if (ev.kind === "stage_start") {
|
||||
return { title: `Started stage: ${stage}`, detail: workflow };
|
||||
}
|
||||
if (ev.kind === "stage_finish") {
|
||||
const elapsed = duration(data.duration_ms);
|
||||
const context = [workflow, elapsed && `ran for ${elapsed}`].filter(Boolean).join(" · ");
|
||||
return {
|
||||
title: data.interrupted ? `Stage interrupted: ${stage}` : data.error ? `Stage failed: ${stage}` : `Finished stage: ${stage}`,
|
||||
detail: [context, data.error].filter(Boolean).join(" — "),
|
||||
};
|
||||
}
|
||||
if (ev.kind === "task_retried") {
|
||||
const count = Number(data.retry_count);
|
||||
const attempt = Number.isFinite(count) && count > 0 ? `Retry ${count}` : "Retry requested";
|
||||
const previous = [data.previous_stage && `after ${data.previous_stage}`, data.previous_reason]
|
||||
.filter(Boolean)
|
||||
.join(": ");
|
||||
return { title: attempt, detail: previous || ev.detail || "" };
|
||||
}
|
||||
if (ev.kind === "agent_finish") {
|
||||
const iterations = count(data.iterations);
|
||||
const total = count(data.tokens);
|
||||
const prompt = count(data.prompt_tokens);
|
||||
const completion = count(data.completion_tokens);
|
||||
const cached = count(data.cached_tokens);
|
||||
const usage = [
|
||||
iterations && `${iterations} iterations`,
|
||||
total && `${total} tokens`,
|
||||
prompt && `${prompt} prompt`,
|
||||
completion && `${completion} completion`,
|
||||
cached && `${cached} cached`,
|
||||
data.model,
|
||||
].filter(Boolean);
|
||||
return {
|
||||
title: `Agent ${data.status || "finished"}: ${stage}`,
|
||||
detail: usage.join(" · ") || ev.detail || "",
|
||||
};
|
||||
}
|
||||
|
||||
return { title: words(ev.kind || ev.type), detail: ev.detail || "" };
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { describeTimelineEvent } from "../src/tasks/timeline-event.js";
|
||||
|
||||
test("stage events name the stage, workflow, duration, and failure", () => {
|
||||
assert.deepEqual(
|
||||
describeTimelineEvent({
|
||||
kind: "stage_finish",
|
||||
workflow: "implement",
|
||||
stage: "baseline",
|
||||
data: { duration_ms: 1250, error: "task check failed" },
|
||||
}),
|
||||
{
|
||||
title: "Stage failed: baseline",
|
||||
detail: "implement workflow · ran for 1.3 s — task check failed",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("retry events explain which failure caused the retry", () => {
|
||||
assert.deepEqual(
|
||||
describeTimelineEvent({
|
||||
kind: "task_retried",
|
||||
detail: "retried via the dashboard",
|
||||
data: { retry_count: 2, previous_stage: "baseline", previous_reason: "task check failed" },
|
||||
}),
|
||||
{ title: "Retry 2", detail: "after baseline: task check failed" },
|
||||
);
|
||||
});
|
||||
|
||||
test("agent events expose stage efficiency and cache usage", () => {
|
||||
assert.deepEqual(
|
||||
describeTimelineEvent({
|
||||
kind: "agent_finish",
|
||||
stage: "analyse",
|
||||
data: {
|
||||
status: "passed",
|
||||
iterations: 7,
|
||||
tokens: 282066,
|
||||
prompt_tokens: 280000,
|
||||
completion_tokens: 2066,
|
||||
cached_tokens: 240000,
|
||||
model: "openai/gpt-5.6-luna",
|
||||
},
|
||||
}),
|
||||
{
|
||||
title: "Agent passed: analyse",
|
||||
detail:
|
||||
"7 iterations · 282,066 tokens · 280,000 prompt · 2,066 completion · 240,000 cached · openai/gpt-5.6-luna",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("agent events with zero-valued usage fields omit them entirely", () => {
|
||||
// Pre-v0.1.24 persisted events lack the breakdown fields, and a
|
||||
// failed run still publishes agent_finish with the zero Result. Either
|
||||
// shape must not render "0 prompt · 0 completion · 0 cached".
|
||||
const result = describeTimelineEvent({
|
||||
kind: "agent_finish",
|
||||
stage: "baseline-fix",
|
||||
data: {
|
||||
status: "",
|
||||
iterations: 0,
|
||||
tokens: 0,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
cached_tokens: 0,
|
||||
model: "openai/gpt-5.6-luna",
|
||||
},
|
||||
});
|
||||
assert.equal(result.title, "Agent finished: baseline-fix");
|
||||
assert.equal(result.detail.includes("0 "), false, `detail should not mention zero counts: ${result.detail}`);
|
||||
assert.equal(result.detail, "openai/gpt-5.6-luna");
|
||||
});
|
||||
|
||||
test("stage durations render minutes and hours, not raw seconds", () => {
|
||||
const r1 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 8_500 } });
|
||||
assert.equal(r1.detail, "ran for 8.5 s");
|
||||
const r2 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 40_600 } });
|
||||
assert.equal(r2.detail, "ran for 41 s");
|
||||
const r3 = describeTimelineEvent({ kind: "stage_finish", stage: "fix", data: { duration_ms: 5 * 60_000 + 12_000 } });
|
||||
assert.equal(r3.detail, "ran for 5 min 12 s");
|
||||
const r4 = describeTimelineEvent({ kind: "stage_finish", stage: "tdd", data: { duration_ms: 1 * 3_600_000 } });
|
||||
assert.equal(r4.detail, "ran for 1 h");
|
||||
const r5 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 90_000 } });
|
||||
assert.equal(r5.detail, "ran for 1 min 30 s");
|
||||
const r6 = describeTimelineEvent({ kind: "stage_finish", stage: "analyse", data: { duration_ms: 3_599_600 } });
|
||||
assert.equal(r6.detail, "ran for 1 h");
|
||||
});
|
||||
|
||||
test("cancelled stages are described as interrupted rather than failed", () => {
|
||||
assert.deepEqual(
|
||||
describeTimelineEvent({
|
||||
kind: "stage_finish",
|
||||
stage: "implement",
|
||||
data: { error: "context canceled", interrupted: true },
|
||||
}),
|
||||
{ title: "Stage interrupted: implement", detail: "context canceled" },
|
||||
);
|
||||
});
|
||||
|
||||
test("unknown event kinds become readable labels", () => {
|
||||
assert.deepEqual(describeTimelineEvent({ kind: "human_approved", detail: "approved via dashboard" }), {
|
||||
title: "Human Approved",
|
||||
detail: "approved via dashboard",
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user