chore: replace 607 em-dashes with double hyphens project-wide
Includes MCP crash-after-init test fix (crash moved from handle() to serve() entry point so transport sees immediate subprocess death).
This commit is contained in:
1 parent
16d6cd62b7
commit
f6d51416f0
112 files changed
+587
-582
No files matched your search
@@ -36,7 +36,7 @@ var mockFactory = func(providers map[string]Provider, log *slog.Logger) Runner {
|
||||
return &mockRunner{}
|
||||
}
|
||||
|
||||
// ── regression: Gap 1 — per-task agent ──────────────────────────────
|
||||
// ── regression: Gap 1 -- per-task agent ──────────────────────────────
|
||||
|
||||
func TestHandleMessageReadsWorkflowField(t *testing.T) {
|
||||
// Gap 1: archie-agent is per-stage, not per-task.
|
||||
@@ -69,7 +69,7 @@ func TestHandleMessageReadsWorkflowField(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if singleResp.TaskCompleted {
|
||||
t.Error("single-stage mode set TaskCompleted=true — should be false")
|
||||
t.Error("single-stage mode set TaskCompleted=true -- should be false")
|
||||
}
|
||||
|
||||
// Per-task mode: Workflow set, Stages populated with two stages.
|
||||
@@ -116,14 +116,14 @@ func TestHandleMessageReadsWorkflowField(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── regression: Gap 3 — response/system channel split ───────────────
|
||||
// ── regression: Gap 3 -- response/system channel split ───────────────
|
||||
|
||||
func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
|
||||
// Gap 3: no response/system channel split.
|
||||
// PRD section 2: system messages go to archie.agent.<id>.system and
|
||||
// are never forwarded to humans. Response messages go to
|
||||
// archie.agent.<id>.response for daemon review before human delivery.
|
||||
// Currently HandleMessage always returns Channel="response" — there
|
||||
// Currently HandleMessage always returns Channel="response" -- there
|
||||
// is no code path that produces a system-channel response.
|
||||
|
||||
msg := AgentRequestMessage{
|
||||
@@ -143,7 +143,7 @@ func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
|
||||
Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}},
|
||||
}
|
||||
|
||||
// Normal stage request — should route to response channel.
|
||||
// Normal stage request -- should route to response channel.
|
||||
resp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -152,7 +152,7 @@ func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
|
||||
t.Errorf("normal stage request: Channel = %q, want \"response\"", resp.Channel)
|
||||
}
|
||||
|
||||
// System message (health check, log dump request) — should route to
|
||||
// System message (health check, log dump request) -- should route to
|
||||
// system channel. Currently HandleMessage always returns "response".
|
||||
// The daemon sets Channel on the request to indicate message type.
|
||||
msg.Channel = "system"
|
||||
@@ -172,7 +172,7 @@ func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
|
||||
respSubj := arnats.SubjectForAgentResponse(42)
|
||||
sysSubj := arnats.SubjectForAgentSystem(42)
|
||||
if respSubj == sysSubj || respSubj == "" || sysSubj == "" {
|
||||
t.Error("Gap 3: subject functions broken — verify SubjectForAgentResponse " +
|
||||
t.Error("Gap 3: subject functions broken -- verify SubjectForAgentResponse " +
|
||||
"and SubjectForAgentSystem return distinct, non-empty subjects.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import "github.com/samcharles93/archie-core/internal/config"
|
||||
|
||||
// ProvidersFromConfig converts the daemon's configured LLM providers into
|
||||
// the wire-safe Provider map sent to an agent runner. It carries only
|
||||
// class/env-var-name/base-URL — never the resolved API key.
|
||||
// class/env-var-name/base-URL -- never the resolved API key.
|
||||
func ProvidersFromConfig(providers map[string]config.Provider) map[string]Provider {
|
||||
out := make(map[string]Provider, len(providers))
|
||||
for name, p := range providers {
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestHandleMessageDoesNotDuplicateSkillBody(t *testing.T) {
|
||||
// Regression for issue #65: the daemon already prepends the skill
|
||||
// body to every mission via missionWithSkill() before the Request
|
||||
// reaches HandleMessage. HandleMessage must pass the mission
|
||||
// through unchanged — a second prepend here would duplicate the
|
||||
// through unchanged -- a second prepend here would duplicate the
|
||||
// skill body in the agent's context window.
|
||||
|
||||
dir := t.TempDir()
|
||||
@@ -92,7 +92,7 @@ Analyse the bug. Write repro tests. Fix.
|
||||
if capturedMission != alreadyPrepended {
|
||||
t.Errorf("HandleMessage modified the mission:\n got: %q\n want: %q\n\n"+
|
||||
"The daemon already prepends the skill body via missionWithSkill(). "+
|
||||
"HandleMessage must not prepend it again — doing so duplicates content "+
|
||||
"HandleMessage must not prepend it again -- doing so duplicates content "+
|
||||
"in the agent's context window (issue #65).",
|
||||
capturedMission, alreadyPrepended)
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ func (g *Gateway) WebhookHandler() http.Handler {
|
||||
return g.bot.WebhookHandler()
|
||||
}
|
||||
|
||||
// ── command handlers (gateway-local — no LLM) ────────────────
|
||||
// ── command handlers (gateway-local -- no LLM) ────────────────
|
||||
|
||||
func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
@@ -174,9 +174,9 @@ func (g *Gateway) helpHandler() bot.HandlerFunc {
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID,
|
||||
"🤖 <b>Archie Gateway</b>\n\n"+
|
||||
"/status — Show task status\n"+
|
||||
"/help — This message\n\n"+
|
||||
"Anything else: chat with the LLM (not yet wired — coming soon).")
|
||||
"/status -- Show task status\n"+
|
||||
"/help -- This message\n\n"+
|
||||
"Anything else: chat with the LLM (not yet wired -- coming soon).")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
|
||||
}
|
||||
|
||||
// If it starts with / but wasn't matched by a registered
|
||||
// handler, it's unknown — let the router handle it (which
|
||||
// handler, it's unknown -- let the router handle it (which
|
||||
// will say "unrecognized").
|
||||
reply, err := router.Route(ctx, gateway.Message{
|
||||
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
|
||||
|
||||
@@ -66,7 +66,7 @@ func TestStartAndStopLifecycle(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
|
||||
g := New("test-token", "", "", nil, log)
|
||||
|
||||
// Override the API base URL — the go-telegram/bot library uses
|
||||
// Override the API base URL -- the go-telegram/bot library uses
|
||||
// https://api.telegram.org by default. We want it to hit our test
|
||||
// server instead. The library doesn't expose a BaseURL override, so
|
||||
// we test what we can: ensure Start fails predictably when the API
|
||||
@@ -82,7 +82,7 @@ func TestStartAndStopLifecycle(t *testing.T) {
|
||||
// The point: we exercise the Start/Stop path; accept either
|
||||
// success or failure.
|
||||
_ = g.Start(ctx, router)
|
||||
// Best-effort stop — don't assert on Start result since we can't
|
||||
// Best-effort stop -- don't assert on Start result since we can't
|
||||
// fully mock the Bot API without the library supporting a base URL
|
||||
// override.
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
|
||||
@@ -53,12 +53,12 @@ type Repo struct {
|
||||
Base string `toml:"base" json:"base" yaml:"base"`
|
||||
// Gate is the quality-gate command list for this repo, e.g.
|
||||
// [["go","vet","./..."], ["task","check"]]. By convention the
|
||||
// LAST command is the test runner — TDD workflows invert only
|
||||
// LAST command is the test runner -- TDD workflows invert only
|
||||
// that one with ExpectFailure during the repro stage and re-run
|
||||
// it in capture-proof. Workflow stages may extend or override
|
||||
// Gate (a TDD repro stage inverts the test command).
|
||||
Gate [][]string `toml:"gate" json:"gate" yaml:"gate"`
|
||||
// Protect lists path suffixes agents must never write directly —
|
||||
// Protect lists path suffixes agents must never write directly --
|
||||
// generated files (e.g. "_templ.go") whose sources they should edit
|
||||
// instead. Enforced environmentally via agentloop.ProtectPaths.
|
||||
Protect []string `toml:"protect" json:"protect" yaml:"protect"`
|
||||
@@ -286,7 +286,7 @@ type Config struct {
|
||||
// PluginDir is an optional path to a directory of Yaegi-interpreted
|
||||
// daemon plugins (*.go files). Each file must export a "Plugin"
|
||||
// variable satisfying the plugin.Plugin interface. Failed plugins
|
||||
// are skipped — the daemon starts with the remaining set. When
|
||||
// are skipped -- the daemon starts with the remaining set. When
|
||||
// empty, no daemon plugins are loaded.
|
||||
PluginDir string `toml:"plugin_dir" yaml:"plugin_dir"`
|
||||
DBPath string `toml:"db_path" yaml:"db_path"`
|
||||
@@ -394,7 +394,7 @@ func (c Config) ForTask() TaskConfig {
|
||||
}
|
||||
|
||||
// ToConfig expands a TaskConfig back into a Config with only the carried
|
||||
// fields populated — everything else (Repos, NATS, Containers, Providers,
|
||||
// fields populated -- everything else (Repos, NATS, Containers, Providers,
|
||||
// secrets) is zero. Used by archie-agent to reconstruct the Config value
|
||||
// workflow stages read via TaskContext.Cfg.
|
||||
func (tc TaskConfig) ToConfig() Config {
|
||||
@@ -448,7 +448,7 @@ type ContainerConfig struct {
|
||||
}
|
||||
|
||||
// ChatConfig configures conversational front-ends (multi-agent
|
||||
// collaboration PRD, phase C — docs/prds/multi-agent-collaboration.md).
|
||||
// collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md).
|
||||
// Empty (Telegram.TokenEnv == "") disables chat entirely.
|
||||
type ChatConfig struct {
|
||||
Telegram TelegramConfig `toml:"telegram" yaml:"telegram"`
|
||||
@@ -471,7 +471,7 @@ type Notify struct {
|
||||
// Web configures the observability dashboard.
|
||||
type Web struct {
|
||||
// Listen is the dashboard address; "off" disables the web UI.
|
||||
// Bind localhost (or a LAN/tailnet address) — there is no auth.
|
||||
// Bind localhost (or a LAN/tailnet address) -- there is no auth.
|
||||
Listen string `toml:"listen" yaml:"listen"`
|
||||
}
|
||||
|
||||
@@ -485,7 +485,7 @@ func Load(path string) (Config, error) {
|
||||
}
|
||||
|
||||
// LoadOverlay reads basePath, then re-decodes overlayPath into the same
|
||||
// struct so only the fields overlayPath sets are overridden — every field
|
||||
// struct so only the fields overlayPath sets are overridden -- every field
|
||||
// it omits keeps the value from basePath. This lets a deployment-specific
|
||||
// file (e.g. config.docker.toml) declare only what differs from the base
|
||||
// config instead of duplicating the whole schema. overlayPath == "" is
|
||||
@@ -603,7 +603,7 @@ func finalize(cfg Config) (Config, error) {
|
||||
return cfg, fmt.Errorf("config: identities[%d].bot_user is required", i)
|
||||
}
|
||||
if len(id.Repos) == 0 {
|
||||
return cfg, fmt.Errorf("config: identities[%d] has no [[identities.repos]] entries — at least one is required", i)
|
||||
return cfg, fmt.Errorf("config: identities[%d] has no [[identities.repos]] entries -- at least one is required", i)
|
||||
}
|
||||
switch id.Forge.Type {
|
||||
case "github", "gitea":
|
||||
|
||||
@@ -211,7 +211,7 @@ func assertJSONKeys(t *testing.T, data []byte, want ...string) {
|
||||
}
|
||||
|
||||
func TestDispatchDefaults(t *testing.T) {
|
||||
// Simulate a config with no [dispatch] section — all fields zero.
|
||||
// Simulate a config with no [dispatch] section -- all fields zero.
|
||||
var d Dispatch
|
||||
d.Labels = map[string]string{}
|
||||
|
||||
@@ -269,7 +269,7 @@ func TestDispatchCustomLabels(t *testing.T) {
|
||||
"queued": "bot:queued",
|
||||
"working": "bot:working",
|
||||
"parked": "bot:parked",
|
||||
// "waiting" and "pr" intentionally missing — should fall back.
|
||||
// "waiting" and "pr" intentionally missing -- should fall back.
|
||||
},
|
||||
}
|
||||
|
||||
@@ -546,7 +546,7 @@ func TestDockerConfigOverlaysExampleConfig(t *testing.T) {
|
||||
if cfg.Containers.Image == "" {
|
||||
t.Error("Containers.Image: want docker overlay image, got empty")
|
||||
}
|
||||
// bot_user and repos are not set by the docker overlay — they must
|
||||
// bot_user and repos are not set by the docker overlay -- they must
|
||||
// come from the base config, proving the overlay isn't a standalone
|
||||
// config that silently drops required fields.
|
||||
if cfg.BotUser == "" {
|
||||
@@ -599,7 +599,7 @@ func TestEcosystemOverrides(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEcosystemCustom(t *testing.T) {
|
||||
// "custom" ecosystem has no defaults — preflight empty, test glob empty.
|
||||
// "custom" ecosystem has no defaults -- preflight empty, test glob empty.
|
||||
r := Repo{Ecosystem: "custom"}
|
||||
if got := r.ResolvedTestGlob(); got != "" {
|
||||
t.Errorf("ResolvedTestGlob custom: got %q, want empty", got)
|
||||
|
||||
@@ -9,7 +9,7 @@ type ecosystemDefaults struct {
|
||||
}
|
||||
|
||||
// ecosystems maps known ecosystem names to their defaults.
|
||||
// "custom" is deliberately absent — it means user-configured everything.
|
||||
// "custom" is deliberately absent -- it means user-configured everything.
|
||||
var ecosystems = map[string]ecosystemDefaults{
|
||||
"go": {
|
||||
Preflight: [][]string{{"go", "version"}},
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// knownFeatureNames is the set of recognised config.<name>.yaml feature files.
|
||||
// Any config.<name>.yaml file whose <name> is not in this set is rejected —
|
||||
// Any config.<name>.yaml file whose <name> is not in this set is rejected --
|
||||
// silent ignores would hide typos.
|
||||
var knownFeatureNames = map[string]bool{
|
||||
"gateway": true,
|
||||
@@ -23,20 +23,20 @@ var knownFeatureNames = map[string]bool{
|
||||
|
||||
// LoadDir loads configuration from a directory tree.
|
||||
//
|
||||
// ~/.config/archie/config.yaml — daemon-level fields
|
||||
// ~/.config/archie/config.gateway.yaml — chat channels, platforms
|
||||
// ~/.config/archie/config.tools.yaml — MCP servers, tool policy
|
||||
// ~/.config/archie/config.memory.yaml — memory provider config
|
||||
// ~/.config/archie/config.models.yaml — LLM providers and models
|
||||
// ~/.config/archie/config.identities.yaml — identity configs
|
||||
// ~/.config/archie/conf.d/*.yaml — additional feature files
|
||||
// ~/.config/archie/config.yaml -- daemon-level fields
|
||||
// ~/.config/archie/config.gateway.yaml -- chat channels, platforms
|
||||
// ~/.config/archie/config.tools.yaml -- MCP servers, tool policy
|
||||
// ~/.config/archie/config.memory.yaml -- memory provider config
|
||||
// ~/.config/archie/config.models.yaml -- LLM providers and models
|
||||
// ~/.config/archie/config.identities.yaml -- identity configs
|
||||
// ~/.config/archie/conf.d/*.yaml -- additional feature files
|
||||
//
|
||||
// Missing feature files mean "feature disabled" — no error, just zero values.
|
||||
// Missing feature files mean "feature disabled" -- no error, just zero values.
|
||||
// Legacy config.toml is used as a fallback when config.yaml is absent.
|
||||
// YAML takes precedence over TOML when both exist.
|
||||
//
|
||||
// When overlayDir is non-empty, files from overlayDir are decoded on top of
|
||||
// baseDir — only the fields an overlay file declares are overridden; everything
|
||||
// baseDir -- only the fields an overlay file declares are overridden; everything
|
||||
// else is inherited from the base.
|
||||
func LoadDir(baseDir, overlayDir string) (Config, error) {
|
||||
var cfg Config
|
||||
@@ -54,7 +54,7 @@ func LoadDir(baseDir, overlayDir string) (Config, error) {
|
||||
// loadDirInto scans dir for config files and decodes them into cfg.
|
||||
// When requireMain is true the directory must contain config.yaml or
|
||||
// config.toml; when false (overlay mode) a missing main config is
|
||||
// fine — only feature and conf.d/ files are applied.
|
||||
// fine -- only feature and conf.d/ files are applied.
|
||||
func loadDirInto(cfg *Config, dir string, requireMain bool) error {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
@@ -186,7 +186,7 @@ func loadDirInto(cfg *Config, dir string, requireMain bool) error {
|
||||
// Config. Most feature files map to top-level Config fields and can be
|
||||
// decoded with yaml.Unmarshal(data, cfg) directly. Memory and tools are
|
||||
// sub-structs whose YAML keys live at the top level of the file, not nested
|
||||
// under a "memory:" or "tools:" key — decode those into their target
|
||||
// under a "memory:" or "tools:" key -- decode those into their target
|
||||
// sub-struct directly.
|
||||
func loadFeatureFile(cfg *Config, feature, path string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
@@ -203,7 +203,7 @@ func loadFeatureFile(cfg *Config, feature, path string) error {
|
||||
return fmt.Errorf("parsing %s: %w", path, err)
|
||||
}
|
||||
default:
|
||||
// models, gateway, identities — these have top-level keys that
|
||||
// models, gateway, identities -- these have top-level keys that
|
||||
// match Config fields directly.
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
return fmt.Errorf("parsing %s: %w", path, err)
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
// modifying the tests themselves. The tests are the spec.
|
||||
//
|
||||
// Design:
|
||||
// - ~/.config/archie/config.yaml — daemon-level fields
|
||||
// - ~/.config/archie/config.gateway.yaml — chat channels, platforms
|
||||
// - ~/.config/archie/config.tools.yaml — MCP servers, tool policy
|
||||
// - ~/.config/archie/config.memory.yaml — memory provider config
|
||||
// - ~/.config/archie/config.models.yaml — LLM providers and models
|
||||
// - ~/.config/archie/config.identities.yaml — identity configs
|
||||
// - ~/.config/archie/conf.d/*.yaml — additional feature files (Linux convention)
|
||||
// - ~/.config/archie/config.yaml -- daemon-level fields
|
||||
// - ~/.config/archie/config.gateway.yaml -- chat channels, platforms
|
||||
// - ~/.config/archie/config.tools.yaml -- MCP servers, tool policy
|
||||
// - ~/.config/archie/config.memory.yaml -- memory provider config
|
||||
// - ~/.config/archie/config.models.yaml -- LLM providers and models
|
||||
// - ~/.config/archie/config.identities.yaml -- identity configs
|
||||
// - ~/.config/archie/conf.d/*.yaml -- additional feature files (Linux convention)
|
||||
//
|
||||
// Missing files mean "feature disabled" — no error, just zero values.
|
||||
// Missing files mean "feature disabled" -- no error, just zero values.
|
||||
// Legacy config.toml is still supported as a fallback.
|
||||
// Overlay support: --config-overlay <dir> applies files from <dir>
|
||||
// on top of the base config directory.
|
||||
@@ -111,7 +111,7 @@ func TestLoadDirRequiresBotUser(t *testing.T) {
|
||||
|
||||
func TestLoadDirMissingFeatureFilesSucceeds(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
// Only config.yaml exists — no gateway, tools, memory, models, identities files.
|
||||
// Only config.yaml exists -- no gateway, tools, memory, models, identities files.
|
||||
writeFile(t, dir, "config.yaml", `bot_user: minimal`)
|
||||
|
||||
cfg, err := LoadDir(dir, "")
|
||||
@@ -348,7 +348,7 @@ custom_tools:
|
||||
|
||||
func TestLoadDirFallsBackToLegacyToml(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
// No config.yaml — only the legacy config.toml exists.
|
||||
// No config.yaml -- only the legacy config.toml exists.
|
||||
writeFile(t, dir, "config.toml", `
|
||||
bot_user = "legacy"
|
||||
poll_interval = "90s"
|
||||
@@ -380,7 +380,7 @@ name = "legacy-repo"
|
||||
|
||||
func TestLoadDirYamlTakesPrecedenceOverToml(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
// Both exist — YAML wins.
|
||||
// Both exist -- YAML wins.
|
||||
writeFile(t, dir, "config.yaml", `bot_user: yaml-wins`)
|
||||
writeFile(t, dir, "config.toml", `bot_user = "toml-loses"`)
|
||||
|
||||
@@ -469,7 +469,7 @@ func TestLoadDirOverlayEmptyDirIsNoop(t *testing.T) {
|
||||
writeFile(t, baseDir, "config.yaml", `bot_user: base-only`)
|
||||
|
||||
overlayDir := tmpConfigDir(t)
|
||||
// Empty overlay directory — same as calling LoadDir(baseDir, "").
|
||||
// Empty overlay directory -- same as calling LoadDir(baseDir, "").
|
||||
|
||||
cfg, err := LoadDir(baseDir, overlayDir)
|
||||
if err != nil {
|
||||
@@ -496,7 +496,7 @@ func TestLoadDirRejectsInvalidFeatureFile(t *testing.T) {
|
||||
func TestLoadDirRejectsUnknownFeatureFile(t *testing.T) {
|
||||
dir := tmpConfigDir(t)
|
||||
writeFile(t, dir, "config.yaml", `bot_user: valid`)
|
||||
// config.unknown.yaml is not a known feature — should error, not silently ignore.
|
||||
// config.unknown.yaml is not a known feature -- should error, not silently ignore.
|
||||
writeFile(t, dir, "config.unknown.yaml", `foo: bar`)
|
||||
|
||||
_, err := LoadDir(dir, "")
|
||||
|
||||
@@ -64,7 +64,7 @@ type Pool struct {
|
||||
// detected from the daemon's own container so they can resolve
|
||||
// sibling services (nats, etc.) by compose service name. Empty when
|
||||
// the daemon isn't running in a container on such a network, or when
|
||||
// detection fails — Docker then falls back to its default bridge.
|
||||
// detection fails -- Docker then falls back to its default bridge.
|
||||
network string
|
||||
|
||||
mu sync.Mutex
|
||||
@@ -132,7 +132,7 @@ func NewPool(ctx context.Context, cfg Config, natsURL string, log *slog.Logger)
|
||||
// Acquire creates and starts a container with the given mounts and
|
||||
// environment variables. Mounts are provided by the caller (typically
|
||||
// from a storage.Backend). If MaxUptime is set, the container is
|
||||
// created with a deadline — Docker kills it when the time elapses.
|
||||
// created with a deadline -- Docker kills it when the time elapses.
|
||||
func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string) (*Container, error) {
|
||||
p.mu.Lock()
|
||||
if p.cfg.MaxConcurrency > 0 && p.active >= p.cfg.MaxConcurrency {
|
||||
@@ -158,7 +158,7 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string
|
||||
if p.network != "" {
|
||||
// Join the same user-defined network the daemon itself is on, so
|
||||
// the agent container can resolve sibling compose services (nats,
|
||||
// etc.) by name — otherwise Docker attaches it to the default
|
||||
// etc.) by name -- otherwise Docker attaches it to the default
|
||||
// bridge network, where those hostnames don't resolve.
|
||||
hostConfig.NetworkMode = container.NetworkMode(p.network)
|
||||
}
|
||||
@@ -198,7 +198,7 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string
|
||||
|
||||
// Release stops and removes a container after a task completes. If
|
||||
// GracePeriod is configured, the container stays alive for that duration
|
||||
// before being killed — the agent can handle follow-ups (gate re-runs,
|
||||
// before being killed -- the agent can handle follow-ups (gate re-runs,
|
||||
// human replies) during this window. PRD section 1.
|
||||
func (p *Pool) Release(c *Container) {
|
||||
if c == nil {
|
||||
@@ -291,7 +291,7 @@ func (p *Pool) pullImage(ctx context.Context) error {
|
||||
// process's own container is attached to, by inspecting the container
|
||||
// named after our hostname (Docker sets a container's hostname to its
|
||||
// short ID by default). Returns "" if we're not running in a container,
|
||||
// the inspect fails, or we're only on the default bridge network — in
|
||||
// the inspect fails, or we're only on the default bridge network -- in
|
||||
// all of those cases Acquire falls back to Docker's normal default.
|
||||
func selfNetwork(ctx context.Context, cli *client.Client, log *slog.Logger) string {
|
||||
hostname, err := os.Hostname()
|
||||
|
||||
@@ -8,16 +8,16 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// ── regression: Gap 2 — post-completion grace period ────────────────
|
||||
// ── regression: Gap 2 -- post-completion grace period ────────────────
|
||||
|
||||
func TestContainerSupportsGracePeriod(t *testing.T) {
|
||||
// Gap 2: MaxUptime is a container-level context timeout at creation,
|
||||
// not a post-completion grace period. PRD section 1 says:
|
||||
// "max_uptime — grace period after task completion before kill."
|
||||
// "max_uptime -- grace period after task completion before kill."
|
||||
//
|
||||
// The agent should stay alive after the task finishes so it can
|
||||
// handle follow-ups (gate re-runs, human replies). Currently
|
||||
// Release() stops the container immediately — there's no way to
|
||||
// Release() stops the container immediately -- there's no way to
|
||||
// keep it alive after task completion.
|
||||
|
||||
c := &Container{ID: "test"}
|
||||
@@ -72,11 +72,11 @@ func TestWriteTaskJSONProducesValidFile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── regression: Gap 6 — /data/task.json boot brief ───────────────────
|
||||
// ── regression: Gap 6 -- /data/task.json boot brief ───────────────────
|
||||
|
||||
func TestTaskPayloadWrittenAsVolumeFile(t *testing.T) {
|
||||
// Gap 6: task travels over NATS, not a file. PRD section 3 describes
|
||||
// /data/task.json as the container's boot-time brief — the daemon
|
||||
// /data/task.json as the container's boot-time brief -- the daemon
|
||||
// writes it to the volume before the container starts, and the agent
|
||||
// reads it on boot alongside NATS messages.
|
||||
|
||||
@@ -105,7 +105,7 @@ func TestTaskPayloadWrittenAsVolumeFile(t *testing.T) {
|
||||
|
||||
// Gap 6 assertion: the daemon must serialize this payload as JSON
|
||||
// and write it to <workspace>/task.json before calling Acquire().
|
||||
// Currently no such file is written — the task travels over NATS.
|
||||
// Currently no such file is written -- the task travels over NATS.
|
||||
if payload.ID == 0 {
|
||||
t.Error("TaskPayload ID is zero")
|
||||
}
|
||||
|
||||
+20
-20
@@ -73,7 +73,7 @@ type Daemon struct {
|
||||
|
||||
// IdentityRunner bundles identity-specific state for a single agent
|
||||
// identity running within a multi-identity daemon. Each identity gets its
|
||||
// own forge client, worktree manager, repo list, and config — but shares
|
||||
// own forge client, worktree manager, repo list, and config -- but shares
|
||||
// the store, NATS connection, container pool, and event bus with siblings.
|
||||
type IdentityRunner struct {
|
||||
Name string
|
||||
@@ -125,7 +125,7 @@ func (d *Daemon) Startup(ctx context.Context) error {
|
||||
}
|
||||
for _, r := range d.Cfg.Repos {
|
||||
if err := d.Forge.VerifyPush(ctx, r.Owner, r.Name); err != nil {
|
||||
d.Log.Warn("repo not pushable — tasks from it will fail", "repo", r.FullName(), "err", err)
|
||||
d.Log.Warn("repo not pushable -- tasks from it will fail", "repo", r.FullName(), "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -133,7 +133,7 @@ func (d *Daemon) Startup(ctx context.Context) error {
|
||||
|
||||
// Run polls until the context ends. When Identities is non-empty, each
|
||||
// identity gets its own goroutine with its own forge client, repo list,
|
||||
// and poll interval — failure isolation between identities (one identity's
|
||||
// and poll interval -- failure isolation between identities (one identity's
|
||||
// forge outage doesn't block another's poll cycle).
|
||||
func (d *Daemon) Run(ctx context.Context) error {
|
||||
if len(d.Identities) > 0 {
|
||||
@@ -205,7 +205,7 @@ func (d *Daemon) cycleForIdentity(ctx context.Context, id *IdentityRunner) {
|
||||
}
|
||||
|
||||
// pollIssuesWithForge is pollIssues using an explicit forge client rather
|
||||
// than d.Forge — used by multi-identity poll loops.
|
||||
// than d.Forge -- used by multi-identity poll loops.
|
||||
func (d *Daemon) pollIssuesWithForge(ctx context.Context, fg forge.Forge, repo config.Repo) []forge.Issue {
|
||||
switch d.Cfg.Dispatch.Trigger {
|
||||
case "label":
|
||||
@@ -352,7 +352,7 @@ func (d *Daemon) drainNATS(ctx context.Context) {
|
||||
// one-task-per-repository safety rule. Submit order is retained within a repo;
|
||||
// tasks for different repos may run concurrently. Repos for which
|
||||
// allowConcurrent reports true opt out of the same-repo serialization
|
||||
// entirely — the global slot limit is the only bound on their concurrency.
|
||||
// entirely -- the global slot limit is the only bound on their concurrency.
|
||||
type taskDispatcher struct {
|
||||
slots chan struct{}
|
||||
allowConcurrent func(owner, repo string) bool
|
||||
@@ -450,7 +450,7 @@ func (d *Daemon) pollSQLite(ctx context.Context, repo config.Repo, is forge.Issu
|
||||
|
||||
// pollNATS publishes discovered issues to NATS (new flow).
|
||||
func (d *Daemon) pollNATS(ctx context.Context, repo config.Repo, is forge.Issue, labels string) {
|
||||
// Read-only existence check — needed for maybeRetryParked.
|
||||
// Read-only existence check -- needed for maybeRetryParked.
|
||||
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
|
||||
if err != nil {
|
||||
d.Log.Error("task lookup failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
@@ -505,7 +505,7 @@ func (d *Daemon) processNATSTask(ctx context.Context, msg jetstream.Msg) {
|
||||
return
|
||||
}
|
||||
if !inserted {
|
||||
// Already tracked — dedup. Ack and move on.
|
||||
// Already tracked -- dedup. Ack and move on.
|
||||
if err := msg.Ack(); err != nil {
|
||||
d.Log.Warn("ack failed", "err", err)
|
||||
}
|
||||
@@ -587,7 +587,7 @@ func (d *Daemon) pollEither(ctx context.Context, repo config.Repo) []forge.Issue
|
||||
}
|
||||
|
||||
// maybeRetryParked requeues a parked task whose state label a human has
|
||||
// removed — the forge-native retry trigger. When retry_count reaches the
|
||||
// removed -- the forge-native retry trigger. When retry_count reaches the
|
||||
// configured max_retries the task moves to dead instead of requeuing.
|
||||
func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forge.Issue) {
|
||||
if hasLabel(is.Labels, d.Cfg.Dispatch.StateLabel("parked")) {
|
||||
@@ -622,7 +622,7 @@ func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forg
|
||||
|
||||
// markDead permanently parks a task that has exhausted its max_retries.
|
||||
func (d *Daemon) markDead(ctx context.Context, repo config.Repo, task *store.Task, maxRetries int) {
|
||||
reason := fmt.Sprintf("max retries reached (%d/%d) — task parked permanently", task.RetryCount, maxRetries)
|
||||
reason := fmt.Sprintf("max retries reached (%d/%d) -- task parked permanently", task.RetryCount, maxRetries)
|
||||
if err := d.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
|
||||
d.Log.Error("transition to dead failed", "task", task.ID, "err", err)
|
||||
return
|
||||
@@ -631,7 +631,7 @@ func (d *Daemon) markDead(ctx context.Context, repo config.Repo, task *store.Tas
|
||||
d.Cfg.Dispatch.StateLabel("dead"), d.Cfg.Dispatch.LabelValues())
|
||||
d.Log.Warn("task permanently parked after max retries",
|
||||
"issue", task.IssueNumber, "retry_count", task.RetryCount, "max_retries", maxRetries)
|
||||
body := fmt.Sprintf("**Max retries reached (%d/%d) — task parked permanently.**\n\n"+
|
||||
body := fmt.Sprintf("**Max retries reached (%d/%d) -- task parked permanently.**\n\n"+
|
||||
"The task failed %d times and has been moved to `dead` status. "+
|
||||
"Manual intervention is required to recover this task.",
|
||||
task.RetryCount, maxRetries, task.RetryCount)
|
||||
@@ -688,7 +688,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
}
|
||||
|
||||
// checkWaiting looks for human replies on waiting_human tasks and asks
|
||||
// an LLM — not keyword matching — whether the reply is a go-ahead.
|
||||
// an LLM -- not keyword matching -- whether the reply is a go-ahead.
|
||||
// Approved tasks requeue under the implement workflow; rejections close
|
||||
// the issue with the human's reasoning acknowledged.
|
||||
func (d *Daemon) checkWaiting(ctx context.Context) {
|
||||
@@ -723,7 +723,7 @@ func (d *Daemon) checkWaiting(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
_, _ = d.Forge.Comment(ctx, t.Owner, t.Repo, t.IssueNumber,
|
||||
"**Go-ahead received — implementation is queued.** ("+reason+")")
|
||||
"**Go-ahead received -- implementation is queued.** ("+reason+")")
|
||||
d.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: "human_approved", TaskID: t.ID,
|
||||
@@ -732,7 +732,7 @@ func (d *Daemon) checkWaiting(ctx context.Context) {
|
||||
case "reject":
|
||||
_ = d.Store.Transition(ctx, t.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, reason)
|
||||
_ = d.Forge.CloseIssue(ctx, t.Owner, t.Repo, t.IssueNumber,
|
||||
"**Understood — closing without implementation.** ("+reason+")")
|
||||
"**Understood -- closing without implementation.** ("+reason+")")
|
||||
d.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: "human_rejected", TaskID: t.ID,
|
||||
@@ -740,7 +740,7 @@ func (d *Daemon) checkWaiting(ctx context.Context) {
|
||||
})
|
||||
default:
|
||||
// Unclear: keep waiting; the humans can be more explicit.
|
||||
d.Log.Info("reply unclear — still waiting", "issue", t.IssueNumber, "reason", reason)
|
||||
d.Log.Info("reply unclear -- still waiting", "issue", t.IssueNumber, "reason", reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -802,7 +802,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
if _, err := os.Stat(workDir); err == nil {
|
||||
aug, err := skillbuild.AugmentRegistry(workDir, d.Workflows)
|
||||
if err != nil {
|
||||
d.Log.Error("worktree registry augmentation failed — using startup registry", "dir", workDir, "err", err)
|
||||
d.Log.Error("worktree registry augmentation failed -- using startup registry", "dir", workDir, "err", err)
|
||||
d.emit(events.Event{
|
||||
Kind: "registry_augment_failed", TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber,
|
||||
@@ -816,7 +816,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
d.Log.Info("processing task", "repo", repo.FullName(), "issue", task.IssueNumber, "workflow", wf.Name, "attempt", task.Attempt)
|
||||
|
||||
// Clone the worktree before Docker mount setup. The container
|
||||
// binds /data/worktree to workDir on the host — the directory
|
||||
// binds /data/worktree to workDir on the host -- the directory
|
||||
// must exist before Acquire is called.
|
||||
var branch string
|
||||
var err error
|
||||
@@ -838,7 +838,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
|
||||
// Acquire a container for the task when Docker sandboxing is enabled.
|
||||
if d.ContainerPool != nil {
|
||||
// Write task.json — the container's boot-time brief.
|
||||
// Write task.json -- the container's boot-time brief.
|
||||
if err := container.WriteTaskJSON(workDir, container.TaskPayload{
|
||||
ID: task.ID, Owner: task.Owner, Repo: task.Repo,
|
||||
Number: task.IssueNumber, Title: task.Title, Body: task.Body,
|
||||
@@ -854,7 +854,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
// Guard: Storage may be nil if the daemon was wired incorrectly.
|
||||
// In normal operation, Storage is always set when ContainerPool is set.
|
||||
if d.Storage == nil {
|
||||
d.Log.Error("storage backend is nil — cannot acquire container")
|
||||
d.Log.Error("storage backend is nil -- cannot acquire container")
|
||||
_ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "storage backend not configured")
|
||||
return
|
||||
}
|
||||
@@ -886,7 +886,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
// Sandboxed path: hand the whole task to archie-agent in one NATS round
|
||||
// trip instead of running the stage loop here. archie-agent proxies
|
||||
// Store/Forge/worktree-push calls back to archied over storerpc/
|
||||
// forgerpc/worktreerpc — by the time runViaAgent returns, the task's
|
||||
// forgerpc/worktreerpc -- by the time runViaAgent returns, the task's
|
||||
// terminal state already landed via those calls.
|
||||
if d.ContainerPool != nil {
|
||||
d.runViaAgent(ctx, task, repo)
|
||||
@@ -923,7 +923,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
// archie.taskrun.<id> and waits for its completion report. Every durable
|
||||
// side effect (Store transitions, Forge calls, git push) happens inside
|
||||
// archie-agent's workflow.Run, proxied back to this daemon over
|
||||
// storerpc/forgerpc/worktreerpc — those RPC servers are the sole place a
|
||||
// storerpc/forgerpc/worktreerpc -- those RPC servers are the sole place a
|
||||
// terminal state gets written on success. runViaAgent only parks the task
|
||||
// itself when nothing else could have: the request never reached (or was
|
||||
// never answered by) an archie-agent, or archie-agent failed before its
|
||||
|
||||
@@ -181,7 +181,7 @@ func TestTaskDispatcherRunsConcurrentReposInParallel(t *testing.T) {
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("%s did not start — allow_concurrent repos should not be serialized", name)
|
||||
t.Fatalf("%s did not start -- allow_concurrent repos should not be serialized", name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,7 +304,7 @@ func TestRunViaAgentParksOnRequestFailure(t *testing.T) {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
// No responder registered on the taskrun subject — the request must
|
||||
// No responder registered on the taskrun subject -- the request must
|
||||
// fail, and runViaAgent must park rather than leave the task stuck
|
||||
// running.
|
||||
d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget"})
|
||||
@@ -395,7 +395,7 @@ func TestRunViaAgentSendsExpectedRequest(t *testing.T) {
|
||||
}
|
||||
|
||||
// Success path: runViaAgent must not park a task that archie-agent
|
||||
// already reported as complete — the daemon just logs it.
|
||||
// already reported as complete -- the daemon just logs it.
|
||||
got, err := s.TaskByIssue(ctx, "acme", "widget", 3)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByIssue: (%+v, %v)", got, err)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package events is archied's in-process observability stream, adapted
|
||||
// from tau's eventbus but slimmed for a small daemon: one event type,
|
||||
// mutex fan-out instead of a router goroutine, and — unlike tau's
|
||||
// blocking delivery — bounded per-subscriber buffers that DROP on
|
||||
// mutex fan-out instead of a router goroutine, and -- unlike tau's
|
||||
// blocking delivery -- bounded per-subscriber buffers that DROP on
|
||||
// overflow, so a stalled dashboard connection can never apply
|
||||
// backpressure to the task engine.
|
||||
package events
|
||||
@@ -27,7 +27,7 @@ const (
|
||||
)
|
||||
|
||||
// Event is the single wire type: task lifecycle, stage progress, agent
|
||||
// stats, and log lines all flow through it — every consumer (SQLite
|
||||
// stats, and log lines all flow through it -- every consumer (SQLite
|
||||
// sink, SSE fan-out, future aggregators) is just another subscriber.
|
||||
type Event struct {
|
||||
ID int64 `json:"id,omitempty"` // set by the store sink
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package forge defines the interface archie uses to interact with a git
|
||||
// host — polling issues, managing labels, opening PRs, and reacting to
|
||||
// host -- polling issues, managing labels, opening PRs, and reacting to
|
||||
// comments. GitHub and Gitea are the supported implementations.
|
||||
package forge
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ func labelNames(is *github.Issue) []string {
|
||||
}
|
||||
|
||||
// IssuesWithLabel returns open issues matching the given label, excluding
|
||||
// PRs. Used when Dispatch.Trigger is "label" or "either" — no assignee
|
||||
// PRs. Used when Dispatch.Trigger is "label" or "either" -- no assignee
|
||||
// required, just the label.
|
||||
func (c *GitHubClient) IssuesWithLabel(ctx context.Context, owner, repo, label string) ([]Issue, error) {
|
||||
var out []Issue
|
||||
@@ -149,7 +149,7 @@ type Reply struct {
|
||||
}
|
||||
|
||||
// RepliesAfter returns comments on the issue with id > afterID that were
|
||||
// not written by exclude (the bot) — the human side of waiting_human.
|
||||
// not written by exclude (the bot) -- the human side of waiting_human.
|
||||
func (c *GitHubClient) RepliesAfter(ctx context.Context, owner, repo string, number int, afterID int64, exclude string) ([]Reply, error) {
|
||||
comments, _, err := c.gh.Issues.ListComments(ctx, owner, repo, number,
|
||||
&github.IssueListCommentsOptions{ListOptions: github.ListOptions{PerPage: 50}})
|
||||
@@ -204,19 +204,19 @@ func (c *GitHubClient) CloseIssue(ctx context.Context, owner, repo string, numbe
|
||||
return err
|
||||
}
|
||||
|
||||
// LinkBranch associates a branch with an issue (GitHub stub — Gitea is primary).
|
||||
// LinkBranch associates a branch with an issue (GitHub stub -- Gitea is primary).
|
||||
func (c *GitHubClient) LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateIssue opens a new issue and returns its number (stub — Gitea is primary).
|
||||
// CreateIssue opens a new issue and returns its number (stub -- Gitea is primary).
|
||||
func (c *GitHubClient) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
|
||||
return 0, fmt.Errorf("GitHub CreateIssue not yet implemented")
|
||||
}
|
||||
|
||||
// State labels mirror the task lifecycle onto the forge so archie's
|
||||
// status is visible at a glance. SQLite remains the source of truth;
|
||||
// labels are the human-facing projection — and removing the parked
|
||||
// labels are the human-facing projection -- and removing the parked
|
||||
// label is the forge-native retry trigger.
|
||||
// Label strings are configured via [dispatch.labels]; these are the
|
||||
// legacy defaults used as a fallback when config is absent.
|
||||
@@ -233,7 +233,7 @@ var stateLabelColors = map[string]string{
|
||||
// defaultLabelColor is used for custom labels not in stateLabelColors.
|
||||
const defaultLabelColor = "bfd4f2"
|
||||
|
||||
// React adds an emoji reaction to an issue — the instant "received"
|
||||
// React adds an emoji reaction to an issue -- the instant "received"
|
||||
// acknowledgement on pickup.
|
||||
func (c *GitHubClient) React(ctx context.Context, owner, repo string, number int, reaction string) error {
|
||||
_, _, err := c.gh.Reactions.CreateIssueReaction(ctx, owner, repo, number, reaction)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// container holding a live forge API token. archied remains the sole
|
||||
// holder of forge credentials and the sole caller of forge.Forge.
|
||||
//
|
||||
// Only these four methods are proxied — the rest of forge.Forge (issue
|
||||
// Only these four methods are proxied -- the rest of forge.Forge (issue
|
||||
// polling, invitations, reactions, PR-state reconciliation) is used
|
||||
// exclusively by the daemon's own poll/reconcile loops, never from inside
|
||||
// a workflow stage, so there's nothing for archie-agent to call.
|
||||
@@ -121,7 +121,7 @@ func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode set_state_label request: %w", err))})
|
||||
return
|
||||
}
|
||||
// SetStateLabel has no error return in forge.Forge — nothing to propagate.
|
||||
// SetStateLabel has no error return in forge.Forge -- nothing to propagate.
|
||||
s.Forge.SetStateLabel(context.Background(), req.Owner, req.Repo, req.Number, req.Label, req.KnownLabels)
|
||||
s.respond(msg, Response{})
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ func connect(t *testing.T, url string) *nats.Conn {
|
||||
}
|
||||
|
||||
// fakeForge implements forge.Forge, recording calls to the four methods
|
||||
// workflow stages invoke mid-run. Every other method panics if called —
|
||||
// workflow stages invoke mid-run. Every other method panics if called --
|
||||
// this RPC layer must never proxy them.
|
||||
type fakeForge struct {
|
||||
comments []commentCall
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package gateeval evaluates a repo's .archie/gate.go via Yaegi. Split
|
||||
// from internal/gate (which only declares the GateContext/Finding types)
|
||||
// because the generated symbol table in gateextract imports internal/gate —
|
||||
// because the generated symbol table in gateextract imports internal/gate --
|
||||
// this package sits above both to avoid the resulting import cycle.
|
||||
package gateeval
|
||||
|
||||
@@ -22,10 +22,10 @@ import (
|
||||
const scriptPath = ".archie/gate.go"
|
||||
|
||||
// Evaluate loads and runs the repo's .archie/gate.go against gctx. A
|
||||
// missing script is not an error — it returns (nil, nil), meaning no
|
||||
// missing script is not an error -- it returns (nil, nil), meaning no
|
||||
// custom gate is configured for this repo. The script runs in-process
|
||||
// (interpreted, not sandboxed), so a panic inside it — nil dereference,
|
||||
// out-of-range index — is recovered and returned as an error rather than
|
||||
// (interpreted, not sandboxed), so a panic inside it -- nil dereference,
|
||||
// out-of-range index -- is recovered and returned as an error rather than
|
||||
// taking down the daemon.
|
||||
func Evaluate(gctx gate.GateContext) ([]gate.Finding, error) {
|
||||
src, err := os.ReadFile(filepath.Join(gctx.Dir, scriptPath))
|
||||
|
||||
@@ -49,7 +49,7 @@ func Check(ctx gate.GateContext) []gate.Finding {
|
||||
}
|
||||
for _, f := range ctx.ChangedFiles {
|
||||
if strings.HasSuffix(f, ".md") {
|
||||
findings = append(findings, gate.Finding{Level: "warn", File: f, Message: "markdown change — no build impact"})
|
||||
findings = append(findings, gate.Finding{Level: "warn", File: f, Message: "markdown change -- no build impact"})
|
||||
}
|
||||
}
|
||||
return findings
|
||||
|
||||
@@ -13,8 +13,8 @@ type SendResult struct {
|
||||
// Success is true when the platform accepted the message.
|
||||
Success bool
|
||||
|
||||
// Retryable is true when the error is transient — rate limits, network
|
||||
// timeouts, temporary platform outages — and the caller should retry
|
||||
// Retryable is true when the error is transient -- rate limits, network
|
||||
// timeouts, temporary platform outages -- and the caller should retry
|
||||
// with backoff.
|
||||
Retryable bool
|
||||
|
||||
@@ -24,12 +24,12 @@ type SendResult struct {
|
||||
// ErrorCode classifies the failure for observability and retry-policy
|
||||
// decisions. Values:
|
||||
//
|
||||
// "" — no error (Success == true)
|
||||
// "rate_limited" — platform rejected due to rate limiting
|
||||
// "network" — connection lost or timeout
|
||||
// "auth" — token expired or credentials invalid
|
||||
// "invalid_message" — message content rejected by platform
|
||||
// "internal" — unexpected adapter or platform error
|
||||
// "" -- no error (Success == true)
|
||||
// "rate_limited" -- platform rejected due to rate limiting
|
||||
// "network" -- connection lost or timeout
|
||||
// "auth" -- token expired or credentials invalid
|
||||
// "invalid_message" -- message content rejected by platform
|
||||
// "internal" -- unexpected adapter or platform error
|
||||
ErrorCode string
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
// etc.) owns its connection lifecycle and delegates message dispatch to a
|
||||
// shared CommandRouter.
|
||||
//
|
||||
// The router distinguishes gateway-local commands — handled directly
|
||||
// without the LLM (model changes, status queries, restart) — from
|
||||
// The router distinguishes gateway-local commands -- handled directly
|
||||
// without the LLM (model changes, status queries, restart) -- from
|
||||
// general messages that need LLM processing.
|
||||
package gateway
|
||||
|
||||
@@ -43,7 +43,7 @@ type StatusReader interface {
|
||||
}
|
||||
|
||||
// LLMResponder routes a message to the LLM and returns the reply. When
|
||||
// nil (not yet wired — see abg.13), non-command messages get a static
|
||||
// nil (not yet wired -- see abg.13), non-command messages get a static
|
||||
// "LLM not configured" response. Gateways call this for any message the
|
||||
// router did not handle directly.
|
||||
type LLMResponder func(ctx context.Context, msg Message) (string, error)
|
||||
@@ -82,7 +82,7 @@ type Router struct {
|
||||
gatewayName string
|
||||
}
|
||||
|
||||
// NewRouter returns a Router. llm is optional — when nil, non-command
|
||||
// NewRouter returns a Router. llm is optional -- when nil, non-command
|
||||
// messages get a "not configured" response.
|
||||
func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router {
|
||||
return &Router{Store: store, LLM: llm, gatewayName: gatewayName}
|
||||
@@ -103,7 +103,7 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
|
||||
case "/model":
|
||||
return r.handleModel(ctx, arg)
|
||||
case "/spawn":
|
||||
// Title is everything after "/spawn" — keep the multi-word text.
|
||||
// Title is everything after "/spawn" -- keep the multi-word text.
|
||||
title := restAfter(text, cmd, r.gatewayName)
|
||||
return r.handleSpawn(ctx, title)
|
||||
default:
|
||||
|
||||
@@ -27,7 +27,7 @@ func TestMessageEventToLegacy(t *testing.T) {
|
||||
t.Errorf("Text = %q", m.Text)
|
||||
}
|
||||
|
||||
// ToLegacy carries Text for non-text types too — callers decide
|
||||
// ToLegacy carries Text for non-text types too -- callers decide
|
||||
// how to interpret it.
|
||||
img := MessageEvent{
|
||||
Type: MsgImage,
|
||||
|
||||
@@ -57,7 +57,7 @@ func (t MessageType) IsMedia() bool {
|
||||
|
||||
// IsEphemeral reports whether the type is a transient signal
|
||||
// (typing indicators, read receipts) that should not be stored.
|
||||
// Note: MsgEdited is NOT ephemeral — it carries content (original
|
||||
// Note: MsgEdited is NOT ephemeral -- it carries content (original
|
||||
// and updated text) that must be persisted to avoid serving stale data.
|
||||
func (t MessageType) IsEphemeral() bool {
|
||||
switch t {
|
||||
|
||||
@@ -135,7 +135,7 @@ func TestSessionStore_GetByChannel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Query chat-1 — should get both sessions.
|
||||
// Query chat-1 -- should get both sessions.
|
||||
results, err := st.GetByChannel(ctx, "telegram", "chat-1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetByChannel: %v", err)
|
||||
@@ -144,7 +144,7 @@ func TestSessionStore_GetByChannel(t *testing.T) {
|
||||
t.Fatalf("expected 2 sessions for chat-1, got %d", len(results))
|
||||
}
|
||||
|
||||
// Query chat-2 — should get one.
|
||||
// Query chat-2 -- should get one.
|
||||
results, err = st.GetByChannel(ctx, "telegram", "chat-2")
|
||||
if err != nil {
|
||||
t.Fatalf("GetByChannel chat-2: %v", err)
|
||||
@@ -153,7 +153,7 @@ func TestSessionStore_GetByChannel(t *testing.T) {
|
||||
t.Fatalf("expected 1 session for chat-2, got %d", len(results))
|
||||
}
|
||||
|
||||
// Different platform — none.
|
||||
// Different platform -- none.
|
||||
results, err = st.GetByChannel(ctx, "discord", "chat-1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetByChannel discord: %v", err)
|
||||
@@ -232,7 +232,7 @@ func TestSessionStore_Touch(t *testing.T) {
|
||||
t.Errorf("expected CreatedAt to be preserved, was %v vs %v", got.CreatedAt, oldTime)
|
||||
}
|
||||
|
||||
// Touch non-existent session — should not error.
|
||||
// Touch non-existent session -- should not error.
|
||||
if err := st.Touch(ctx, "nonexistent"); err != nil {
|
||||
t.Errorf("Touch nonexistent: %v", err)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func (c *StoreTaskCreator) CreateTask(ctx context.Context, title string) (int64,
|
||||
if c.owner == "" || c.repo == "" {
|
||||
return 0, fmt.Errorf("no repo configured for chat-spawned tasks")
|
||||
}
|
||||
// Synthetic issue number — prevents collisions with real Gitea issues
|
||||
// Synthetic issue number -- prevents collisions with real Gitea issues
|
||||
// (which are small sequential ints) while staying within the store's
|
||||
// existing (owner, repo, number) uniqueness constraint.
|
||||
number := int(time.Now().UnixNano())
|
||||
@@ -41,7 +41,7 @@ func (c *StoreTaskCreator) CreateTask(ctx context.Context, title string) (int64,
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// The store doesn't return the task ID from EnqueueIssue — ClaimByIssue
|
||||
// The store doesn't return the task ID from EnqueueIssue -- ClaimByIssue
|
||||
// gives us back the row. For the chat reply, the synthetic number is
|
||||
// all the user needs to reference the task.
|
||||
return int64(number), nil
|
||||
|
||||
@@ -42,7 +42,7 @@ type Config struct {
|
||||
// By default, the provider captures a frozen snapshot of both files at
|
||||
// Initialize() time and uses that snapshot for the system prompt block
|
||||
// (SystemPromptProvider). Writes go to disk immediately but the snapshot is
|
||||
// not updated mid-session — only the next session (or next Initialize call)
|
||||
// not updated mid-session -- only the next session (or next Initialize call)
|
||||
// picks up the changes. Set Config.FrozenSnapshot to false to read live
|
||||
// content on every SystemPromptBlock() call.
|
||||
type Provider struct {
|
||||
@@ -154,7 +154,7 @@ func (p *Provider) snapshotContent() (memory, user string) {
|
||||
//
|
||||
// When frozen snapshot is enabled (the default), Initialize captures the
|
||||
// rendered content of both files for use by SystemPromptBlock(). The snapshot
|
||||
// is not updated on subsequent writes — only the next Initialize() call (or
|
||||
// is not updated on subsequent writes -- only the next Initialize() call (or
|
||||
// the next session) picks up the fresh content.
|
||||
func (p *Provider) Initialize(sessionID string) error {
|
||||
if err := p.memory.Reload(); err != nil {
|
||||
|
||||
@@ -300,7 +300,7 @@ func TestProvider_FrozenSnapshot_NotUpdatedOnWrite(t *testing.T) {
|
||||
t.Fatalf("snapshot should be wrapped in <memory> fences, got: %s", firstBlock)
|
||||
}
|
||||
|
||||
// Write after initialization — the snapshot must not change.
|
||||
// Write after initialization -- the snapshot must not change.
|
||||
if _, err := p.HandleToolCall(toolName, map[string]any{
|
||||
"action": "add", "section": "Facts", "content": "new fact after init",
|
||||
}); err != nil {
|
||||
@@ -421,7 +421,7 @@ func TestProvider_FrozenSnapshot_ReInitialize(t *testing.T) {
|
||||
t.Fatalf("expected 'before', got: %s", block1)
|
||||
}
|
||||
|
||||
// Add more content and re-initialize — snapshot should refresh.
|
||||
// Add more content and re-initialize -- snapshot should refresh.
|
||||
if _, err := p.HandleToolCall(toolName, map[string]any{
|
||||
"action": "add", "section": "Facts", "content": "after",
|
||||
}); err != nil {
|
||||
@@ -459,7 +459,7 @@ func TestProvider_FrozenSnapshot_DefaultEnabled(t *testing.T) {
|
||||
|
||||
block1 := p.SystemPromptBlock()
|
||||
|
||||
// Write after init — snapshot should be frozen.
|
||||
// Write after init -- snapshot should be frozen.
|
||||
if _, err := p.HandleToolCall(toolName, map[string]any{
|
||||
"action": "add", "section": "Facts", "content": "post-init",
|
||||
}); err != nil {
|
||||
|
||||
@@ -132,8 +132,8 @@ type AddResult struct {
|
||||
}
|
||||
|
||||
// Add appends content as a new block in the named section, creating the
|
||||
// section if it does not already exist. The write is rejected — with no
|
||||
// change to in-memory state or disk — if the resulting file would exceed
|
||||
// section if it does not already exist. The write is rejected -- with no
|
||||
// change to in-memory state or disk -- if the resulting file would exceed
|
||||
// the store's size bound.
|
||||
func (s *Store) Add(sectionName, content string) (AddResult, error) {
|
||||
if err := ValidateSectionName(sectionName); err != nil {
|
||||
|
||||
@@ -7,7 +7,7 @@ package memory
|
||||
// and calls them at the appropriate points in the agent lifecycle.
|
||||
//
|
||||
// All hooks are called asynchronously (fire-and-forget) to avoid blocking
|
||||
// the main agent loop. Hook errors and panics are recovered — they must not
|
||||
// the main agent loop. Hook errors and panics are recovered -- they must not
|
||||
// interrupt the agent's operation.
|
||||
|
||||
// TurnStartHook is called at the beginning of each agent turn. Providers
|
||||
|
||||
@@ -39,7 +39,7 @@ var (
|
||||
|
||||
// Manager orchestrates the built-in memory provider plus at most one external
|
||||
// provider. It is the single entry point that agent lifecycle code interacts
|
||||
// with — callers never address providers directly.
|
||||
// with -- callers never address providers directly.
|
||||
//
|
||||
// Key responsibilities:
|
||||
// - Provider registration and lifecycle (Initialize, Shutdown)
|
||||
@@ -130,7 +130,7 @@ type Manager struct {
|
||||
// that kind is available.
|
||||
//
|
||||
// The built-in provider is always present and typically backed by the
|
||||
// filesystem or NellDB. The external provider is optional — pass nil
|
||||
// filesystem or NellDB. The external provider is optional -- pass nil
|
||||
// and call RegisterExternal later, or pass a single external provider
|
||||
// at construction time.
|
||||
//
|
||||
@@ -239,7 +239,7 @@ func (m *Manager) GetToolSchemas() []tools.ToolEntry {
|
||||
// ToolCallProvider.
|
||||
//
|
||||
// Before dispatching, any "content" or "replacement" string argument is
|
||||
// passed through ScanContent (18.15) — this is the actual integration point
|
||||
// passed through ScanContent (18.15) -- this is the actual integration point
|
||||
// for threat scanning, applying uniformly to every provider's write tools.
|
||||
// A ThreatBlock result rejects the call before it reaches the provider.
|
||||
//
|
||||
@@ -317,7 +317,7 @@ func (m *Manager) Initialize(sessionID string) error {
|
||||
// Each hook fans out to all active providers that implement the
|
||||
// corresponding sub-interface. Hooks are fire-and-forget: they launch a
|
||||
// goroutine per provider and return immediately. Hook errors and panics
|
||||
// are recovered — they must not interrupt the agent loop.
|
||||
// are recovered -- they must not interrupt the agent loop.
|
||||
|
||||
// safeGo runs fn in a goroutine, recovering any panic to prevent a
|
||||
// misbehaving provider from crashing the process.
|
||||
@@ -325,7 +325,7 @@ func safeGo(fn func()) {
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
// A provider panicked — this must not take down the agent.
|
||||
// A provider panicked -- this must not take down the agent.
|
||||
// The panic is intentionally swallowed after logging.
|
||||
_ = r
|
||||
_ = debug.Stack()
|
||||
@@ -482,7 +482,7 @@ func (m *Manager) Prefetch(query string) (string, error) {
|
||||
// is applied if the caller's context does not already have a shorter deadline.
|
||||
//
|
||||
// If the target provider is still prefetching from the previous turn, the
|
||||
// call is skipped — PrefetchContext returns ("", nil) and the skip is logged
|
||||
// call is skipped -- PrefetchContext returns ("", nil) and the skip is logged
|
||||
// (18.8). Results from successful prefetches are stored and included in
|
||||
// SystemPromptBlock() output.
|
||||
func (m *Manager) PrefetchContext(ctx context.Context, query string) (string, error) {
|
||||
@@ -674,7 +674,7 @@ func (m *Manager) Shutdown() error {
|
||||
//
|
||||
// After ShutdownContext returns, no new sync operations are accepted.
|
||||
func (m *Manager) ShutdownContext(ctx context.Context) error {
|
||||
// Signal that we're shutting down — new submissions will be rejected.
|
||||
// Signal that we're shutting down -- new submissions will be rejected.
|
||||
m.shuttingDown.Store(true)
|
||||
|
||||
// Record the drain deadline so the sync worker can self-abandon any op
|
||||
@@ -691,7 +691,7 @@ func (m *Manager) ShutdownContext(ctx context.Context) error {
|
||||
m.pipelineMu.Unlock()
|
||||
|
||||
// Wait for the sync worker to finish draining, or the deadline. On
|
||||
// timeout we don't block further — the worker keeps running in the
|
||||
// timeout we don't block further -- the worker keeps running in the
|
||||
// background, but every op still queued after the deadline is now
|
||||
// abandoned near-instantly by processSyncOp rather than dispatched.
|
||||
drainDone := make(chan struct{})
|
||||
|
||||
@@ -383,7 +383,7 @@ func TestManager_GetToolSchemas_MergesAllProviders(t *testing.T) {
|
||||
// Verify injected handlers are present (Finding 2 fix)
|
||||
for _, s := range schemas {
|
||||
if s.Handler == nil {
|
||||
t.Errorf("ToolEntry %q has nil Handler — GetToolSchemas must inject handlers", s.Name)
|
||||
t.Errorf("ToolEntry %q has nil Handler -- GetToolSchemas must inject handlers", s.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -669,7 +669,7 @@ func TestManager_TypeAssertions_DetectsOptionalInterfaces(t *testing.T) {
|
||||
t.Fatalf("NewManager returned error: %v", err)
|
||||
}
|
||||
|
||||
// The mock implements everything — verify the manager detects this
|
||||
// The mock implements everything -- verify the manager detects this
|
||||
if !mgr.HasSystemPrompt() {
|
||||
t.Error("HasSystemPrompt() = false, want true")
|
||||
}
|
||||
@@ -895,7 +895,7 @@ func TestManager_Shutdown_UnavailableProviderStillShutDown(t *testing.T) {
|
||||
|
||||
builtin.mu.Lock()
|
||||
if builtin.shutdownCalls != 1 {
|
||||
t.Errorf("unavailable provider shutdown was NOT called (shutdownCalls=%d), want 1 — resources may leak",
|
||||
t.Errorf("unavailable provider shutdown was NOT called (shutdownCalls=%d), want 1 -- resources may leak",
|
||||
builtin.shutdownCalls)
|
||||
}
|
||||
builtin.mu.Unlock()
|
||||
@@ -1159,7 +1159,7 @@ func (p *panickyProvider) GetToolSchemas() []tools.ToolEntry {
|
||||
}
|
||||
}
|
||||
|
||||
// Every hook panics — safeGo must recover each one.
|
||||
// Every hook panics -- safeGo must recover each one.
|
||||
func (p *panickyProvider) OnTurnStart(sessionID string) error {
|
||||
panic("OnTurnStart panicked")
|
||||
}
|
||||
@@ -1418,7 +1418,7 @@ func TestManager_PrefetchContext_StoresResult(t *testing.T) {
|
||||
|
||||
stored := mgr.PrefetchResult("builtin")
|
||||
if stored == "" {
|
||||
t.Error("PrefetchResult() returned empty — result was not stored")
|
||||
t.Error("PrefetchResult() returned empty -- result was not stored")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1726,7 +1726,7 @@ func TestManager_ShutdownContext_DrainsPipeline(t *testing.T) {
|
||||
// New submissions should be rejected.
|
||||
err = mgr.SubmitSync(SyncOp{})
|
||||
if err == nil {
|
||||
t.Error("SubmitSync after shutdown succeeded — wanted ErrShuttingDown")
|
||||
t.Error("SubmitSync after shutdown succeeded -- wanted ErrShuttingDown")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1766,7 +1766,7 @@ func TestManager_ShutdownContext_AbandonedCount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown with a very short deadline — ops won't finish.
|
||||
// Shutdown with a very short deadline -- ops won't finish.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ package memory
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/tools"
|
||||
|
||||
// MemoryProvider is the contract that every memory provider — built-in or
|
||||
// external/plugin — must implement. It covers provider identity, availability,
|
||||
// MemoryProvider is the contract that every memory provider -- built-in or
|
||||
// external/plugin -- must implement. It covers provider identity, availability,
|
||||
// session-scoped initialization, and tool schema export.
|
||||
type MemoryProvider interface {
|
||||
// Name returns a unique, human-readable identifier for this provider
|
||||
|
||||
@@ -128,19 +128,19 @@ func (s *Scrubber) processNormal(data []byte) []byte {
|
||||
if len(tail) >= len(openTag) {
|
||||
// Enough data to check the full tag.
|
||||
if string(tail[:len(openTag)]) == openTag {
|
||||
// Found <memory> — write everything before it, then enter memory block.
|
||||
// Found <memory> -- write everything before it, then enter memory block.
|
||||
s.writeOutput(data[:idx])
|
||||
s.depth++
|
||||
s.blocksStripped++
|
||||
s.bytesStripped += int64(len(openTag))
|
||||
return tail[len(openTag):]
|
||||
}
|
||||
// Not <memory> — write the '<' and continue after it.
|
||||
// Not <memory> -- write the '<' and continue after it.
|
||||
s.writeOutput(data[:idx+1])
|
||||
return data[idx+1:]
|
||||
}
|
||||
|
||||
// Not enough data to determine — partial tag at end of chunk.
|
||||
// Not enough data to determine -- partial tag at end of chunk.
|
||||
// Hold the tail for the next Write call.
|
||||
if isPrefixOfTag(tail, openTag) {
|
||||
s.writeOutput(data[:idx])
|
||||
@@ -148,7 +148,7 @@ func (s *Scrubber) processNormal(data []byte) []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Not a prefix of <memory> — write everything.
|
||||
// Not a prefix of <memory> -- write everything.
|
||||
s.writeOutput(data)
|
||||
return nil
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func (s *Scrubber) processNormal(data []byte) []byte {
|
||||
// processInMemory handles input when we're inside a memory block (depth > 0).
|
||||
// It looks for </memory> close tags and strips everything else.
|
||||
func (s *Scrubber) processInMemory(data []byte) []byte {
|
||||
// Fast path: no '<' means no possible close tag — strip everything.
|
||||
// Fast path: no '<' means no possible close tag -- strip everything.
|
||||
idx := bytes.IndexByte(data, '<')
|
||||
if idx < 0 {
|
||||
s.bytesStripped += int64(len(data))
|
||||
@@ -180,12 +180,12 @@ func (s *Scrubber) processInMemory(data []byte) []byte {
|
||||
s.depth--
|
||||
return tail[len(closeTag):]
|
||||
}
|
||||
// Not a close tag — skip the '<' and continue stripping.
|
||||
// Not a close tag -- skip the '<' and continue stripping.
|
||||
s.bytesStripped += int64(idx + 1)
|
||||
return data[idx+1:]
|
||||
}
|
||||
|
||||
// Not enough data to determine — partial tag at end of chunk.
|
||||
// Not enough data to determine -- partial tag at end of chunk.
|
||||
// Could be the start of </memory> (which would close the block) or
|
||||
// <memory> (which would nest). Buffer it.
|
||||
if isPrefixOfTag(tail, closeTag) || isPrefixOfTag(tail, openTag) {
|
||||
@@ -194,7 +194,7 @@ func (s *Scrubber) processInMemory(data []byte) []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Not a prefix of any relevant tag — strip everything.
|
||||
// Not a prefix of any relevant tag -- strip everything.
|
||||
s.bytesStripped += int64(len(data))
|
||||
return nil
|
||||
}
|
||||
@@ -223,13 +223,13 @@ func (s *Scrubber) writeOutput(data []byte) {
|
||||
func (s *Scrubber) Flush() error {
|
||||
if s.depth > 0 {
|
||||
// Inside an unclosed memory block. Pending bytes are content that
|
||||
// was buffered as potential tag starts — since no close tag arrives,
|
||||
// was buffered as potential tag starts -- since no close tag arrives,
|
||||
// they are memory-block content and should be stripped, not emitted.
|
||||
s.bytesStripped += int64(len(s.pending))
|
||||
s.pending = s.pending[:0]
|
||||
s.depth = 0
|
||||
} else if len(s.pending) > 0 {
|
||||
// Outside a memory block — pending bytes are literal text whose
|
||||
// Outside a memory block -- pending bytes are literal text whose
|
||||
// partial tag didn't resolve.
|
||||
s.writeOutput(s.pending)
|
||||
s.pending = s.pending[:0]
|
||||
@@ -249,7 +249,7 @@ func (s *Scrubber) Close() error {
|
||||
// Process is a convenience method that scrubs a single chunk and returns
|
||||
// the cleaned text. It maintains internal state across calls, so it can
|
||||
// be used for streaming just like Write. The returned string is only the
|
||||
// newly scrubbed output from this chunk — not the full accumulated output.
|
||||
// newly scrubbed output from this chunk -- not the full accumulated output.
|
||||
//
|
||||
// For zero-allocation streaming, prefer Write with a pre-allocated writer.
|
||||
func (s *Scrubber) Process(chunk string) string {
|
||||
@@ -308,7 +308,7 @@ func (s *Scrubber) Depth() int {
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
// isPrefixOfTag reports whether data is a prefix of tag — i.e., data could
|
||||
// isPrefixOfTag reports whether data is a prefix of tag -- i.e., data could
|
||||
// be the start of tag if more bytes arrive later. Returns false if data is
|
||||
// longer than tag.
|
||||
func isPrefixOfTag(data []byte, tag string) bool {
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestScrubber_EmptyContent(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestScrubber_OnlyOpenTag(t *testing.T) {
|
||||
// Missing close tag — block is implicitly closed at end of stream.
|
||||
// Missing close tag -- block is implicitly closed at end of stream.
|
||||
s := New(nil)
|
||||
result := s.ProcessString("Before <memory>stuff")
|
||||
if result != "Before " {
|
||||
@@ -61,7 +61,7 @@ func TestScrubber_OnlyOpenTag(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestScrubber_OnlyCloseTag(t *testing.T) {
|
||||
// Stray close tag with no open — treated as literal text.
|
||||
// Stray close tag with no open -- treated as literal text.
|
||||
s := New(nil)
|
||||
result := s.ProcessString("text </memory> more")
|
||||
if result != "text </memory> more" {
|
||||
@@ -110,7 +110,7 @@ func TestScrubber_DeeplyNestedMemoryBlocks(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestScrubber_UnbalancedNested_MoreOpens(t *testing.T) {
|
||||
// More open tags than close tags — remaining blocks implicitly closed
|
||||
// More open tags than close tags -- remaining blocks implicitly closed
|
||||
// at end of stream. Everything after the first <memory> is stripped
|
||||
// because the outer block never closes.
|
||||
s := New(nil)
|
||||
@@ -241,7 +241,7 @@ func TestScrubber_PartialTag_NotActuallyATag(t *testing.T) {
|
||||
{
|
||||
name: "partial in memory block not a close tag",
|
||||
chunk1: "<memory>content </", chunk2: "notmemory> more</memory>",
|
||||
// "</notmemory>" is not "</memory>" — it doesn't close the block.
|
||||
// "</notmemory>" is not "</memory>" -- it doesn't close the block.
|
||||
// Everything inside the memory block is stripped until the real
|
||||
// </memory> is found.
|
||||
expected: "",
|
||||
@@ -903,7 +903,7 @@ func TestScrubber_Write_ZeroLengthChunkWithPending(t *testing.T) {
|
||||
if len(s.pending) == 0 {
|
||||
t.Error("pending should not be empty after partial tag")
|
||||
}
|
||||
s.Write([]byte("")) // zero-length write — no-op
|
||||
s.Write([]byte("")) // zero-length write -- no-op
|
||||
if len(s.pending) == 0 {
|
||||
t.Error("pending should not be cleared by zero-length Write")
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ func (m *Manager) syncWorker() {
|
||||
}
|
||||
|
||||
// processSyncOp handles a single sync operation. Errors are logged but never
|
||||
// crash the pipeline — a misbehaving external provider must not take down
|
||||
// crash the pipeline -- a misbehaving external provider must not take down
|
||||
// the agent.
|
||||
func (m *Manager) processSyncOp(op SyncOp) {
|
||||
if deadlineNano := m.shutdownDeadlineNano.Load(); deadlineNano != 0 && time.Now().UnixNano() > deadlineNano {
|
||||
@@ -143,6 +143,6 @@ func (m *Manager) signalDone(done chan error, err error) {
|
||||
select {
|
||||
case done <- err:
|
||||
default:
|
||||
// Receiver stopped waiting — don't block the pipeline.
|
||||
// Receiver stopped waiting -- don't block the pipeline.
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func startEmbeddedWithToken(t *testing.T, token string) *server.Server {
|
||||
opts.Port = -1
|
||||
opts.Authorization = token
|
||||
srv := natssrv.RunServer(&opts)
|
||||
// TempDir before Cleanup — shutdown runs before TempDir removal.
|
||||
// TempDir before Cleanup -- shutdown runs before TempDir removal.
|
||||
jsDir := t.TempDir()
|
||||
if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: jsDir}); err != nil {
|
||||
t.Fatalf("enable jetstream: %v", err)
|
||||
|
||||
@@ -49,7 +49,7 @@ const (
|
||||
|
||||
// SubjectForAgentRequest returns the JetStream subject for a per-task
|
||||
// agent request. The stage is carried in the message payload, not the
|
||||
// subject — one subject per task with sequential stage messages. PRD §2.
|
||||
// subject -- one subject per task with sequential stage messages. PRD §2.
|
||||
func SubjectForAgentRequest(taskID int64) string {
|
||||
return fmt.Sprintf("archie.agent.%d.request", taskID)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ func (c *Client) Request(ctx context.Context, subject string, data []byte) ([]by
|
||||
}
|
||||
|
||||
// Call marshals req, sends it to subject, and unmarshals the reply
|
||||
// into a Resp. It does not inspect Resp's error envelope — callers
|
||||
// into a Resp. It does not inspect Resp's error envelope -- callers
|
||||
// that embed Envelope should check Err() themselves, since natsrpc
|
||||
// has no way to know a bare Resp type embeds one.
|
||||
func Call[Resp any](ctx context.Context, c *Client, subject string, req any) (Resp, error) {
|
||||
@@ -91,7 +91,7 @@ type Registration struct {
|
||||
|
||||
// RegisterAll subscribes every registration on nc. If any subscribe
|
||||
// call fails, every subscription made so far is unsubscribed before
|
||||
// returning the error — a server never ends up half-registered. The
|
||||
// returning the error -- a server never ends up half-registered. The
|
||||
// returned func unsubscribes all of them.
|
||||
func RegisterAll(nc *nats.Conn, regs []Registration) (unsubscribe func(), err error) {
|
||||
subs := make([]*nats.Subscription, 0, len(regs))
|
||||
@@ -113,7 +113,7 @@ func RegisterAll(nc *nats.Conn, regs []Registration) (unsubscribe func(), err er
|
||||
}
|
||||
|
||||
// Respond marshals v and replies to msg, logging (rather than
|
||||
// returning) any encode or transport failure — a handler has no
|
||||
// returning) any encode or transport failure -- a handler has no
|
||||
// meaningful way to retry or propagate a respond failure to its caller.
|
||||
// pkg prefixes the log message (e.g. "storerpc") to identify the
|
||||
// surface a failure came from.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// "<owner>:<repo>:<issue_number>". Events live in the "events" collection,
|
||||
// keyed by an auto-incrementing counter.
|
||||
//
|
||||
// Secondary indexes are not available — ClaimNext scans all tasks, and
|
||||
// Secondary indexes are not available -- ClaimNext scans all tasks, and
|
||||
// lookups by task ID (Transition, Requeue, etc.) scan all tasks. This is
|
||||
// acceptable at the daemon's scale (tens to hundreds of tasks).
|
||||
package nell
|
||||
@@ -233,7 +233,7 @@ func (a *Adapter) Update(ctx context.Context, t *store.Task) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("nell: get task for update: %w", err)
|
||||
}
|
||||
// Copy only mutable fields — same set as the SQLite store's UPDATE.
|
||||
// Copy only mutable fields -- same set as the SQLite store's UPDATE.
|
||||
doc["workflow"] = t.Workflow
|
||||
doc["stage"] = t.Stage
|
||||
doc["branch"] = t.Branch
|
||||
@@ -602,7 +602,7 @@ func (a *Adapter) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, erro
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// StageStats aggregates stage_finish events — where time goes and which
|
||||
// StageStats aggregates stage_finish events -- where time goes and which
|
||||
// stages fail.
|
||||
func (a *Adapter) StageStats(ctx context.Context) ([]store.StageStat, error) {
|
||||
all, err := a.events.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
|
||||
@@ -41,7 +41,7 @@ func (r *Registry) Plugins() []Plugin { return r.plugins }
|
||||
|
||||
// LoadDir discovers and evaluates .go files in the given directory.
|
||||
// Each file must export a variable named "Plugin" that implements the
|
||||
// Plugin interface. Failed plugins are logged and skipped — the daemon
|
||||
// Plugin interface. Failed plugins are logged and skipped -- the daemon
|
||||
// starts with the remaining plugins (PRD section 5).
|
||||
//
|
||||
// extraSymbols are additional Yaegi symbol tables made available to
|
||||
@@ -73,11 +73,11 @@ func LoadDir(dir string, extraSymbols ...map[string]map[string]reflect.Value) ([
|
||||
slog.Default().Warn("skipping unreadable daemon plugin", "file", name, "err", err)
|
||||
continue
|
||||
}
|
||||
// Each plugin file is package main — must use a fresh interpreter
|
||||
// Each plugin file is package main -- must use a fresh interpreter
|
||||
// to avoid symbol collisions between files.
|
||||
i, err := yaegiutil.New(interp.Options{}, extraSymbols...)
|
||||
if err != nil {
|
||||
slog.Default().Warn("skipping plugin — interpreter setup failed", "file", name, "err", err)
|
||||
slog.Default().Warn("skipping plugin -- interpreter setup failed", "file", name, "err", err)
|
||||
continue
|
||||
}
|
||||
p, err := yaegiutil.Resolve[Plugin](i, string(src), "main.Plugin")
|
||||
|
||||
@@ -62,7 +62,7 @@ var Plugin = plugin._Plugin{
|
||||
}
|
||||
|
||||
func TestLoadDirSkipsInvalidPlugin(t *testing.T) {
|
||||
// A .go file that doesn't compile must be skipped — not crash the loader.
|
||||
// A .go file that doesn't compile must be skipped -- not crash the loader.
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "broken.go"), []byte(`package main
|
||||
this is not valid Go syntax @@@@
|
||||
@@ -179,11 +179,11 @@ func TestLoadDirNonexistentDirReturnsNil(t *testing.T) {
|
||||
// ── Adversarial tests ────────────────────────────────────────────────
|
||||
//
|
||||
// These tests try to BREAK LoadDir. A correct implementation must
|
||||
// degrade gracefully — skip the bad plugin, load the rest, never panic.
|
||||
// degrade gracefully -- skip the bad plugin, load the rest, never panic.
|
||||
|
||||
func TestLoadDirNilFunctionFieldsLoadsWithoutPanic(t *testing.T) {
|
||||
// A _Plugin with nil WName/WVersion must LOAD without panicking
|
||||
// AND must not panic when Name()/Version() is called — the wrapper
|
||||
// AND must not panic when Name()/Version() is called -- the wrapper
|
||||
// must nil-guard. Otherwise logging plugin names at startup crashes
|
||||
// the daemon.
|
||||
dir := t.TempDir()
|
||||
@@ -207,7 +207,7 @@ var Plugin = plugin._Plugin{
|
||||
t.Fatalf("LoadDir returned %d plugins, want 1 (nil funcs should not prevent loading)", len(plugins))
|
||||
}
|
||||
|
||||
// These must not panic — the _Plugin wrapper must nil-guard.
|
||||
// These must not panic -- the _Plugin wrapper must nil-guard.
|
||||
// The daemon calls Name()/Version() at startup to log loaded plugins.
|
||||
name := plugins[0].Name()
|
||||
version := plugins[0].Version()
|
||||
@@ -220,7 +220,7 @@ var Plugin = plugin._Plugin{
|
||||
}
|
||||
|
||||
func TestLoadDirPluginReturningEmptyNameVersion(t *testing.T) {
|
||||
// Plugins with empty name/version are still valid — the interface
|
||||
// Plugins with empty name/version are still valid -- the interface
|
||||
// doesn't forbid empty strings. LoadDir must not reject them.
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "empty.go"), []byte(`package main
|
||||
@@ -264,14 +264,14 @@ var Plugin = 42
|
||||
}
|
||||
|
||||
func TestLoadDirSkipsPluginWithOnlySomeInterfaceMethods(t *testing.T) {
|
||||
// A struct that has Name() but not Version() — doesn't satisfy Plugin.
|
||||
// A struct that has Name() but not Version() -- doesn't satisfy Plugin.
|
||||
// type assertion must fail and the plugin must be skipped.
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "partial.go"), []byte(`package main
|
||||
|
||||
type partial struct{}
|
||||
func (p partial) Name() string { return "partial" }
|
||||
// No Version() method — deliberately incomplete.
|
||||
// No Version() method -- deliberately incomplete.
|
||||
|
||||
var Plugin partial
|
||||
`), 0o644); err != nil {
|
||||
@@ -325,12 +325,12 @@ var Plugin = plugin._Plugin{
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(plugins) != 0 {
|
||||
t.Errorf("LoadDir returned %d plugins, want 0 — subdirectories must not be traversed", len(plugins))
|
||||
t.Errorf("LoadDir returned %d plugins, want 0 -- subdirectories must not be traversed", len(plugins))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadDirPluginWithPanicInNameFunc(t *testing.T) {
|
||||
// A plugin whose Name() function panics must still be loadable —
|
||||
// A plugin whose Name() function panics must still be loadable --
|
||||
// the panic only fires on call, not on load.
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "panicky.go"), []byte(`package main
|
||||
@@ -353,12 +353,12 @@ var Plugin = plugin._Plugin{
|
||||
t.Fatalf("LoadDir returned %d plugins, want 1 (panics are deferred to call time)", len(plugins))
|
||||
}
|
||||
|
||||
// Verify calling Name() actually panics — the plugin loaded, the panic
|
||||
// Verify calling Name() actually panics -- the plugin loaded, the panic
|
||||
// is the caller's responsibility.
|
||||
func() {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Error("Name() did not panic — expected panic from panicky plugin")
|
||||
t.Error("Name() did not panic -- expected panic from panicky plugin")
|
||||
}
|
||||
}()
|
||||
plugins[0].Name()
|
||||
@@ -378,7 +378,7 @@ var Plugin = struct{}{}
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// This must not crash — just skip.
|
||||
// This must not crash -- just skip.
|
||||
plugins, err := plugin.LoadDir(dir, symbols)
|
||||
if err != nil {
|
||||
t.Fatal("LoadDir errored on unused import:", err)
|
||||
@@ -394,7 +394,7 @@ func TestGeneratedWrapperHasNilGuards(t *testing.T) {
|
||||
//
|
||||
// The _Plugin type is in the pluginextract package. We verify
|
||||
// indirectly by loading a plugin with nil funcs and calling
|
||||
// Name()/Version() — they must return empty strings, not panic.
|
||||
// Name()/Version() -- they must return empty strings, not panic.
|
||||
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "nilguard.go"), []byte(`package main
|
||||
@@ -423,7 +423,7 @@ var Plugin = plugin._Plugin{
|
||||
func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("Name()/Version() panicked with nil funcs — "+
|
||||
t.Fatalf("Name()/Version() panicked with nil funcs -- "+
|
||||
"the generated _Plugin wrapper is missing nil guards. "+
|
||||
"Re-run `go generate` may have overwritten them: %v", r)
|
||||
}
|
||||
@@ -441,7 +441,7 @@ var Plugin = plugin._Plugin{
|
||||
}
|
||||
|
||||
func TestLoadDirPluginWithGoBuildTag(t *testing.T) {
|
||||
// Build tags in Yaegi-interpreted code are just comments — they
|
||||
// Build tags in Yaegi-interpreted code are just comments -- they
|
||||
// don't gate evaluation. The file loads normally.
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "tagged.go"), []byte(`//go:build ignore
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ func init() {
|
||||
}
|
||||
|
||||
// _github_com_samcharles93_archie_core_internal_plugin_Plugin is an interface wrapper for Plugin type
|
||||
// generated by 'yaegi extract'. IValue is required by Yaegi's interface bridging —
|
||||
// generated by 'yaegi extract'. IValue is required by Yaegi's interface bridging --
|
||||
// it holds the underlying concrete value for the interpreter's type system even
|
||||
// though Name()/Version() delegate to the function fields. Do not remove.
|
||||
type _github_com_samcharles93_archie_core_internal_plugin_Plugin struct {
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestCatalogReturnsNameAndDescriptionOnly(t *testing.T) {
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(skillsDir, "SKILL.md"), []byte(`---
|
||||
name: archie-wf-tdd
|
||||
description: TDD bugfix workflow — reproduce, prove, fix.
|
||||
description: TDD bugfix workflow -- reproduce, prove, fix.
|
||||
version: 1.0.0
|
||||
metadata:
|
||||
archie:
|
||||
@@ -48,7 +48,7 @@ It should NOT appear in the catalog entry.
|
||||
t.Errorf("Name = %q, want archie-wf-tdd", e.Name)
|
||||
}
|
||||
if e.Description == "" {
|
||||
t.Error("Description is empty — catalog must include the description")
|
||||
t.Error("Description is empty -- catalog must include the description")
|
||||
}
|
||||
if strings.Contains(e.Description, "full SKILL.md body") {
|
||||
t.Error("Catalog entry contains the body text. " +
|
||||
@@ -187,7 +187,7 @@ func Run(input string) string {
|
||||
`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Write an unlisted plugin — it must NOT be loaded.
|
||||
// Write an unlisted plugin -- it must NOT be loaded.
|
||||
if err := os.WriteFile(filepath.Join(pluginsDir, "extra.go"), []byte(`package main
|
||||
|
||||
func Run(input string) string {
|
||||
@@ -197,7 +197,7 @@ func Run(input string) string {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Discover the skill — must include only the listed plugins in declared order.
|
||||
// Discover the skill -- must include only the listed plugins in declared order.
|
||||
skills, err := Discover(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -207,7 +207,7 @@ func Run(input string) string {
|
||||
}
|
||||
s := skills["archie-wf-tdd"]
|
||||
if len(s.Plugins) != 2 {
|
||||
t.Fatalf("skill has %d plugins, want 2 — Discover() must honor metadata.archie.plugins", len(s.Plugins))
|
||||
t.Fatalf("skill has %d plugins, want 2 -- Discover() must honor metadata.archie.plugins", len(s.Plugins))
|
||||
}
|
||||
if s.Plugins[0].Name != "security-check" {
|
||||
t.Errorf("plugin[0].Name = %q, want security-check (declared order)", s.Plugins[0].Name)
|
||||
@@ -227,7 +227,7 @@ func Run(input string) string {
|
||||
|
||||
// The frontmatter must declare the plugin.
|
||||
if s.Frontmatter.Metadata.Archie == nil || len(s.Frontmatter.Metadata.Archie.Plugins) != 2 {
|
||||
t.Error("Frontmatter.Metadata.Archie.Plugins is empty — " +
|
||||
t.Error("Frontmatter.Metadata.Archie.Plugins is empty -- " +
|
||||
"the SKILL.md must declare bundled plugins in the metadata.archie.plugins list")
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package skill
|
||||
|
||||
import "testing"
|
||||
|
||||
// ── regression: Gap 8 — frontmatter missing plugins key ─────────────
|
||||
// ── regression: Gap 8 -- frontmatter missing plugins key ─────────────
|
||||
|
||||
func TestFrontmatterMetadataArchieHasPluginsField(t *testing.T) {
|
||||
// Gap 8: Frontmatter.Metadata.Archie has Tools and Engine only.
|
||||
|
||||
@@ -29,7 +29,7 @@ func (p *Plugin) Run(input string) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("plugin %s: %w", p.Name, err)
|
||||
}
|
||||
// Plugins must use package main — the convention for runnable Yaegi scripts.
|
||||
// Plugins must use package main -- the convention for runnable Yaegi scripts.
|
||||
fn, err := yaegiutil.Resolve[func(string) string](i, p.Src, "main.Run")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("plugin %s: %w", p.Name, err)
|
||||
@@ -48,7 +48,7 @@ func DiscoverPlugins(dir, skillName string) ([]Plugin, error) {
|
||||
// LoadPlugins loads plugins from dir/.agents/skills/<skillName>/plugins/.
|
||||
//
|
||||
// When allowed is non-empty, only the listed filenames are loaded in
|
||||
// declared order — the plugins/ prefix is stripped before matching.
|
||||
// declared order -- the plugins/ prefix is stripped before matching.
|
||||
// A listed file that does not exist on disk is an error.
|
||||
//
|
||||
// When allowed is nil or empty, all *.go files in the plugins/ directory
|
||||
@@ -57,7 +57,7 @@ func LoadPlugins(dir, skillName string, allowed []string) ([]Plugin, error) {
|
||||
pluginsDir := filepath.Join(dir, skillsDir, skillName, "plugins")
|
||||
entries, err := os.ReadDir(pluginsDir)
|
||||
if os.IsNotExist(err) {
|
||||
// Skill exists but has no plugins directory — not an error.
|
||||
// Skill exists but has no plugins directory -- not an error.
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -28,21 +28,21 @@ type Frontmatter struct {
|
||||
} `yaml:"metadata"`
|
||||
}
|
||||
|
||||
// CatalogEntry is a lightweight skill reference — name + description
|
||||
// CatalogEntry is a lightweight skill reference -- name + description
|
||||
// only (~100 tokens). Loaded at daemon startup for skill discovery.
|
||||
// The full body is loaded on activation via LoadBody. agentskills.io
|
||||
// progressive disclosure Tier 1.
|
||||
type CatalogEntry struct {
|
||||
Name string
|
||||
Description string
|
||||
Workflow string // from metadata.archie.workflow — which workflow this skill handles
|
||||
Workflow string // from metadata.archie.workflow -- which workflow this skill handles
|
||||
Dir string // skill directory name
|
||||
}
|
||||
|
||||
// Catalog scans dir/.agents/skills/*/SKILL.md and returns catalog entries
|
||||
// (Tier 1: name + description + workflow only). Only the frontmatter is
|
||||
// parsed — full bodies are not loaded. Missing directory or a file at the
|
||||
// skills path returns nil (no error) — the caller treats this as "no skills."
|
||||
// parsed -- full bodies are not loaded. Missing directory or a file at the
|
||||
// skills path returns nil (no error) -- the caller treats this as "no skills."
|
||||
func Catalog(dir string) ([]CatalogEntry, error) {
|
||||
skillsPath := filepath.Join(dir, skillsDir)
|
||||
entries, err := os.ReadDir(skillsPath)
|
||||
@@ -50,7 +50,7 @@ func Catalog(dir string) ([]CatalogEntry, error) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
// A file at .agents/skills (ENOTDIR) is not fatal — treat as no skills.
|
||||
// A file at .agents/skills (ENOTDIR) is not fatal -- treat as no skills.
|
||||
// Same for permission errors and other non-fatal ReadDir failures.
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package skillscript runs skill-bundled Go scripts (.agents/skills/<skill>/scripts/*.go)
|
||||
// via Yaegi. Unlike the gate and workflow-stage extension surfaces, these
|
||||
// scripts only need the Go standard library — they wrap external tools
|
||||
// (gitleaks, trivy, ...) the way a shell script would — so no
|
||||
// scripts only need the Go standard library -- they wrap external tools
|
||||
// (gitleaks, trivy, ...) the way a shell script would -- so no
|
||||
// archie-core-specific symbol table is required here.
|
||||
package skillscript
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// Run interprets the Go script at path and executes its main function,
|
||||
// returning everything it wrote to stdout and stderr. The script runs
|
||||
// in-process (interpreted, not sandboxed) with unrestricted symbols
|
||||
// (os/exec included — these scripts wrap external tools the way a shell
|
||||
// (os/exec included -- these scripts wrap external tools the way a shell
|
||||
// script would), so a panic inside it is recovered and returned as an
|
||||
// error rather than taking down the daemon.
|
||||
func Run(path string) (string, error) {
|
||||
@@ -36,7 +36,7 @@ func Run(path string) (string, error) {
|
||||
|
||||
// EvalPath treats a package-main source file the way `go run` does:
|
||||
// evaluating it executes its main() directly. Unlike `go build`, it
|
||||
// does not complain about a missing main() — such a script simply
|
||||
// does not complain about a missing main() -- such a script simply
|
||||
// produces no output.
|
||||
if _, err := i.EvalPath(path); err != nil {
|
||||
return "", fmt.Errorf("yaegi: run %s: %w", path, err)
|
||||
|
||||
@@ -71,7 +71,7 @@ func main() {
|
||||
|
||||
func TestRunMissingMain(t *testing.T) {
|
||||
// Yaegi's EvalPath, like `go build` without `go run`, doesn't
|
||||
// complain about a missing main() — it just never gets called.
|
||||
// complain about a missing main() -- it just never gets called.
|
||||
path := writeScript(t, `package main
|
||||
|
||||
func notMain() {}
|
||||
|
||||
+18
-18
@@ -1,31 +1,31 @@
|
||||
// Package storage defines the pluggable storage backend interface for agent
|
||||
// container execution. The Docker backend (DockerBackend) is the MVP
|
||||
// implementation — no NFS/SMB/S3 yet, just Docker volumes + bind mounts.
|
||||
// implementation -- no NFS/SMB/S3 yet, just Docker volumes + bind mounts.
|
||||
//
|
||||
// /data/ volume layout (implemented):
|
||||
//
|
||||
// /data/
|
||||
// task.json — at /data/worktree/task.json (WriteTaskJSON writes
|
||||
// task.json -- at /data/worktree/task.json (WriteTaskJSON writes
|
||||
// to the worktree root, which is bind-mounted)
|
||||
// worktree/ — bind mount of host worktree
|
||||
// repo/ — per-repo persistent volume (optional, on request)
|
||||
// worktree/ -- bind mount of host worktree
|
||||
// repo/ -- per-repo persistent volume (optional, on request)
|
||||
// cache/
|
||||
// go/ — GOMODCACHE (shared across all tasks)
|
||||
// node/ — npm cache (shared)
|
||||
// pnpm/ — pnpm store (shared)
|
||||
// deno/ — Deno module cache (shared)
|
||||
// bun/ — Bun package cache (shared)
|
||||
// pip/ — pip cache (shared)
|
||||
// cargo/ — Rust cargo cache (shared)
|
||||
// go/ -- GOMODCACHE (shared across all tasks)
|
||||
// node/ -- npm cache (shared)
|
||||
// pnpm/ -- pnpm store (shared)
|
||||
// deno/ -- Deno module cache (shared)
|
||||
// bun/ -- Bun package cache (shared)
|
||||
// pip/ -- pip cache (shared)
|
||||
// cargo/ -- Rust cargo cache (shared)
|
||||
//
|
||||
// TODO(PRD §3): session.jsonl, memory.jsonl, plugins/ volume — these
|
||||
// TODO(PRD §3): session.jsonl, memory.jsonl, plugins/ volume -- these
|
||||
// require agent-side implementation before the storage layer can mount
|
||||
// them. session.jsonl needs per-stage structured output from the agent;
|
||||
// memory.jsonl needs cross-session persistence; plugins/ needs daemon-
|
||||
// staged bundled plugins.
|
||||
//
|
||||
// Cache volumes are named Docker volumes created once and shared across all
|
||||
// tasks. They are never deleted — the daemon operator manages them.
|
||||
// tasks. They are never deleted -- the daemon operator manages them.
|
||||
package storage
|
||||
|
||||
import (
|
||||
@@ -66,7 +66,7 @@ const (
|
||||
|
||||
// WorktreeMountDir is the fixed container path where a task's worktree is
|
||||
// bind-mounted. archie-agent uses this path directly rather than the host
|
||||
// path archied's worktree.Manager reports — the two processes see the same
|
||||
// path archied's worktree.Manager reports -- the two processes see the same
|
||||
// files at different paths.
|
||||
const WorktreeMountDir = "/data/worktree"
|
||||
|
||||
@@ -121,7 +121,7 @@ var cacheVolumesByEcosystem = map[string][]cacheVolume{
|
||||
|
||||
// cacheMounts returns the cache mount specs for an ecosystem, sorted by
|
||||
// destination path for deterministic container configuration.
|
||||
// Ecosystem is case-insensitive — "Python" and "python" are equivalent.
|
||||
// Ecosystem is case-insensitive -- "Python" and "python" are equivalent.
|
||||
func cacheMounts(ecosystem string) []Mount {
|
||||
vols, ok := cacheVolumesByEcosystem[strings.ToLower(ecosystem)]
|
||||
if !ok {
|
||||
@@ -176,7 +176,7 @@ func NewDockerBackend(cli *client.Client) *DockerBackend {
|
||||
|
||||
// ensureVolume creates a Docker volume if it doesn't already exist.
|
||||
// It is idempotent: concurrent callers racing to create the same volume
|
||||
// will not see an error — "already exists" is treated as success.
|
||||
// will not see an error -- "already exists" is treated as success.
|
||||
//
|
||||
// When d.cli is nil (unit tests), ensureVolume returns nil without
|
||||
// creating a volume. The returned mounts will fail at container create
|
||||
@@ -184,7 +184,7 @@ func NewDockerBackend(cli *client.Client) *DockerBackend {
|
||||
// cli via NewDockerBackend.
|
||||
func (d *DockerBackend) ensureVolume(ctx context.Context, name string, labels map[string]string) error {
|
||||
if d.cli == nil {
|
||||
return nil // nil client for testing — volumes must be pre-created
|
||||
return nil // nil client for testing -- volumes must be pre-created
|
||||
}
|
||||
// VolumeInspectOptions{} is the empty struct form (requires moby v25+).
|
||||
// The go.mod pins a compatible version; zero value is always valid.
|
||||
@@ -200,7 +200,7 @@ func (d *DockerBackend) ensureVolume(ctx context.Context, name string, labels ma
|
||||
if err != nil {
|
||||
// TOCTOU: a concurrent caller may have created the volume between
|
||||
// our inspect and create calls. Docker returns an error for
|
||||
// duplicate volumes — treat that as success.
|
||||
// duplicate volumes -- treat that as success.
|
||||
if strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "already in use") {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ func TestDockerBackendSetupWorktreeBindMount(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
backend := &DockerBackend{} // nil client — Setup doesn't need it for bind mounts
|
||||
backend := &DockerBackend{} // nil client -- Setup doesn't need it for bind mounts
|
||||
mounts, err := backend.Setup(context.Background(), TaskRef{
|
||||
WorktreeDir: dir,
|
||||
Ecosystem: "go",
|
||||
@@ -183,7 +183,7 @@ func TestDockerBackendSetupIncludesCacheMounts(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDockerBackendSetupWorktreeMountIsFirst(t *testing.T) {
|
||||
// Worktree bind mount must be the first entry — container create
|
||||
// Worktree bind mount must be the first entry -- container create
|
||||
// depends on this order for overlay semantics.
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
@@ -208,7 +208,7 @@ func TestDockerBackendSetupWorktreeMountIsFirst(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDockerBackendTeardownSucceeds(t *testing.T) {
|
||||
// Teardown is a no-op for Docker backend — cache volumes survive.
|
||||
// Teardown is a no-op for Docker backend -- cache volumes survive.
|
||||
// Must not error.
|
||||
backend := &DockerBackend{}
|
||||
err := backend.Teardown(context.Background(), TaskRef{
|
||||
@@ -223,7 +223,7 @@ func TestDockerBackendTeardownSucceeds(t *testing.T) {
|
||||
|
||||
func TestDockerBackendSetupEmptyWorktreeDir(t *testing.T) {
|
||||
// An empty (non-existent) worktree dir must still produce valid mounts.
|
||||
// The backend doesn't validate host paths — that's the pool's job.
|
||||
// The backend doesn't validate host paths -- that's the pool's job.
|
||||
backend := &DockerBackend{}
|
||||
mounts, err := backend.Setup(context.Background(), TaskRef{
|
||||
WorktreeDir: "/nonexistent/worktree",
|
||||
@@ -349,7 +349,7 @@ func TestDockerBackendSetupWithoutPersistentStorage(t *testing.T) {
|
||||
|
||||
func TestDockerBackendSetupPersistentStorageEmptyOwner(t *testing.T) {
|
||||
// With empty Owner/Repo, no per-repo volume should be created even
|
||||
// when PersistentStorage is true — we can't name the volume.
|
||||
// when PersistentStorage is true -- we can't name the volume.
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -66,7 +66,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
|
||||
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, detail, data"
|
||||
|
||||
// EventsSince returns up to limit events with id > sinceID, oldest
|
||||
// first — SSE catch-up and the live feed.
|
||||
// first -- SSE catch-up and the live feed.
|
||||
func (s *Store) EventsSince(ctx context.Context, sinceID int64, limit int) ([]events.Event, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT `+eventCols+` FROM events WHERE id > ? ORDER BY id LIMIT ?`, sinceID, limit)
|
||||
@@ -153,7 +153,7 @@ type WorkflowStat struct {
|
||||
TotalToken int
|
||||
}
|
||||
|
||||
// WorkflowStats aggregates outcomes and spend per workflow — the
|
||||
// WorkflowStats aggregates outcomes and spend per workflow -- the
|
||||
// core "is archie getting better per dollar" table.
|
||||
func (s *Store) WorkflowStats(ctx context.Context) (stats []WorkflowStat, retErr error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
@@ -186,7 +186,7 @@ type StageStat struct {
|
||||
Errors int
|
||||
}
|
||||
|
||||
// StageStats aggregates stage_finish events — where does time go, and
|
||||
// StageStats aggregates stage_finish events -- where does time go, and
|
||||
// which stages fail.
|
||||
func (s *Store) StageStats(ctx context.Context) (stats []StageStat, retErr error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// TaskStore is the full store surface the daemon needs.
|
||||
// Every storage backend — SQLite, NellDB, future additions — implements this
|
||||
// Every storage backend -- SQLite, NellDB, future additions -- implements this
|
||||
// interface. Consumers depend on TaskStore, never on a concrete type.
|
||||
type TaskStore interface {
|
||||
// ── Task lifecycle ──────────────────────────────────────────────
|
||||
|
||||
@@ -79,7 +79,7 @@ func (s *Server) reply(msg *nats.Msg, err error) {
|
||||
|
||||
// Client calls the storerpc Server from archie-agent's process.
|
||||
// It implements store.WorkflowStore (the narrow interface workflow stages
|
||||
// need — just Update + Transition), not the full store.TaskStore.
|
||||
// need -- just Update + Transition), not the full store.TaskStore.
|
||||
type Client struct {
|
||||
Conn *nats.Conn
|
||||
Timeout time.Duration // bounds each call when ctx has no deadline
|
||||
|
||||
@@ -23,7 +23,7 @@ func SubjectForTask(taskID int64) string {
|
||||
// workflow itself: the task row (already claimed by archied), the repo's
|
||||
// gate/ecosystem config, a non-secret config snapshot, and LLM provider
|
||||
// config (API keys are injected into the container's environment
|
||||
// separately — Providers only carries class/env-var-name/base-URL).
|
||||
// separately -- Providers only carries class/env-var-name/base-URL).
|
||||
type Request struct {
|
||||
Task *store.Task `json:"task"`
|
||||
Repo config.Repo `json:"repo"`
|
||||
|
||||
@@ -36,7 +36,7 @@ func writeMessage(w io.Writer, data []byte) error {
|
||||
//
|
||||
// r must be a *bufio.Reader. Callers that hold a plain io.Reader should
|
||||
// wrap it once with bufio.NewReader and reuse that wrapper across
|
||||
// multiple readMessage calls — creating a new bufio.Reader per call
|
||||
// multiple readMessage calls -- creating a new bufio.Reader per call
|
||||
// silently drops buffered data and breaks multi-message streams.
|
||||
//
|
||||
// The function parses HTTP-like headers terminated by an empty line
|
||||
@@ -47,7 +47,7 @@ func readMessage(r io.Reader) ([]byte, error) {
|
||||
br, ok := r.(*bufio.Reader)
|
||||
if !ok {
|
||||
// Caller passed a plain io.Reader without managing the
|
||||
// buffer — warn them once and wrap anyway. Multi-message
|
||||
// buffer -- warn them once and wrap anyway. Multi-message
|
||||
// streams will lose data after the first read.
|
||||
br = bufio.NewReader(r)
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ func (t *StdioTransport) Stop(_ context.Context) error {
|
||||
t.state = StateStopping
|
||||
t.mu.Unlock()
|
||||
|
||||
// Cancel the transport context — this signals all background
|
||||
// Cancel the transport context -- this signals all background
|
||||
// goroutines (reader, restart timer) to stop.
|
||||
t.mu.Lock()
|
||||
if t.cancel != nil {
|
||||
@@ -280,7 +280,7 @@ func (t *StdioTransport) Send(ctx context.Context, body []byte) ([]byte, error)
|
||||
// Wait for the response.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// De-register on context cancellation — no cleanup needed on the
|
||||
// De-register on context cancellation -- no cleanup needed on the
|
||||
// channel since the reader will close it when it tries to deliver.
|
||||
t.mu.Lock()
|
||||
delete(t.pending, msgID)
|
||||
@@ -289,7 +289,7 @@ func (t *StdioTransport) Send(ctx context.Context, body []byte) ([]byte, error)
|
||||
|
||||
case resp, ok := <-ch:
|
||||
if !ok {
|
||||
// Channel closed — the transport was stopped or the subprocess
|
||||
// Channel closed -- the transport was stopped or the subprocess
|
||||
// crashed before we got a response.
|
||||
return nil, errors.New("mcp: transport closed while waiting for response")
|
||||
}
|
||||
@@ -383,7 +383,7 @@ func (t *StdioTransport) deliverResponse(body []byte) {
|
||||
msgID, err := extractMessageID(body)
|
||||
if err != nil {
|
||||
// Cannot route a message without an ID. This could be a server
|
||||
// notification (no ID) — we silently drop it rather than blocking.
|
||||
// notification (no ID) -- we silently drop it rather than blocking.
|
||||
// In a full MCP client implementation, notifications would be
|
||||
// handled via a callback.
|
||||
return
|
||||
@@ -403,7 +403,7 @@ func (t *StdioTransport) deliverResponse(body []byte) {
|
||||
select {
|
||||
case ch <- body:
|
||||
default:
|
||||
// Caller is no longer waiting — discard.
|
||||
// Caller is no longer waiting -- discard.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -423,7 +423,7 @@ func (t *StdioTransport) handleProcessDeath() {
|
||||
t.cmd = nil
|
||||
t.stdin = nil
|
||||
|
||||
// Fail all pending requests — the subprocess is gone.
|
||||
// Fail all pending requests -- the subprocess is gone.
|
||||
t.failAllPendingLocked()
|
||||
t.mu.Unlock()
|
||||
|
||||
@@ -464,7 +464,7 @@ func (t *StdioTransport) attemptRestart() {
|
||||
|
||||
backoff := t.computeBackoffLocked()
|
||||
|
||||
// Check spawn-failure limit (not crash limit — crash loops are
|
||||
// Check spawn-failure limit (not crash limit -- crash loops are
|
||||
// bounded by the growing backoff cap).
|
||||
if t.config.MaxRetries > 0 && t.startupFailures >= t.config.MaxRetries {
|
||||
t.state = StateError
|
||||
@@ -501,7 +501,7 @@ func (t *StdioTransport) attemptRestart() {
|
||||
continue
|
||||
}
|
||||
|
||||
// Success — update state and start the reader.
|
||||
// Success -- update state and start the reader.
|
||||
t.mu.Lock()
|
||||
t.cmd = cmd
|
||||
t.stdin = stdin
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
// ── Helper: test MCP server process ─────────────────────────────────────
|
||||
|
||||
// TestMCPServerHelper is the entry point for the test helper subprocess.
|
||||
// It is NOT a test — it is a process invoked by StdioTransport tests.
|
||||
// It is NOT a test -- it is a process invoked by StdioTransport tests.
|
||||
// It must be the only Test* function in this file that runs as a subprocess;
|
||||
// we guard it with GO_WANT_MCP_HELPER.
|
||||
func TestMCPServerHelper(t *testing.T) {
|
||||
@@ -42,6 +42,12 @@ type testMCPServer struct {
|
||||
}
|
||||
|
||||
func (s *testMCPServer) serve() error {
|
||||
// crash-after-init must exit immediately on startup, before the read
|
||||
// loop, so the transport sees a subprocess that dies right after spawn.
|
||||
if s.behavior == "crash-after-init" {
|
||||
syscall.Exit(1)
|
||||
}
|
||||
|
||||
// Use a persistent bufio.Reader so buffered bytes between calls
|
||||
// are not lost (each readMessage call checks for an existing bufio.Reader).
|
||||
stdin := bufio.NewReader(os.Stdin)
|
||||
@@ -85,12 +91,6 @@ func (s *testMCPServer) handle(msg Message) (*Message, error) {
|
||||
}
|
||||
return nil, nil
|
||||
|
||||
case "crash-after-init":
|
||||
// Exit immediately without reading stdin to simulate a
|
||||
// subprocess that crashes right after starting.
|
||||
syscall.Exit(1) // bypass test harness os.Exit interception
|
||||
return nil, nil
|
||||
|
||||
case "slow-response":
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
return s.echo(msg), nil
|
||||
@@ -148,7 +148,7 @@ func helperTransportWithConfig(t *testing.T, behavior string, cfg StdioTransport
|
||||
cfg.MaxBackoff = 50 * time.Millisecond
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
// nothing — caller manages lifecycle
|
||||
// nothing -- caller manages lifecycle
|
||||
})
|
||||
return NewStdioTransport(cfg)
|
||||
}
|
||||
@@ -408,7 +408,7 @@ func TestStdioTransportConcurrentRequests(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, concurrency)
|
||||
|
||||
for i := 0; i < concurrency; i++ {
|
||||
for i := range concurrency {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
@@ -509,7 +509,7 @@ func TestStdioTransportRestartFromError(t *testing.T) {
|
||||
// We accept either Running or Error (depending on timing).
|
||||
if err := tr.Start(context.Background()); err != nil {
|
||||
// Starting a crashing process may return nil if the retry loop starts in background.
|
||||
// That's fine — we just check the transition happened.
|
||||
// That's fine -- we just check the transition happened.
|
||||
t.Logf("Start from Error: %v (acceptable)", err)
|
||||
}
|
||||
}
|
||||
@@ -552,7 +552,7 @@ func TestStdioTransportSendAfterStop(t *testing.T) {
|
||||
// ── Framing edge cases ──────────────────────────────────────────────────
|
||||
|
||||
func TestFramingCarriageReturnOnly(t *testing.T) {
|
||||
// Some servers might send \n without \r — we should be lenient.
|
||||
// Some servers might send \n without \r -- we should be lenient.
|
||||
input := "Content-Length: 4\n\nbody"
|
||||
body, err := readMessage(strings.NewReader(input))
|
||||
if err != nil {
|
||||
|
||||
@@ -12,7 +12,7 @@ import "encoding/json"
|
||||
type TransportState int
|
||||
|
||||
const (
|
||||
// StateStopped is the initial and final state — no subprocess running.
|
||||
// StateStopped is the initial and final state -- no subprocess running.
|
||||
StateStopped TransportState = iota
|
||||
// StateStarting means a subprocess has been spawned and is being
|
||||
// initialised. The transport is not yet usable for requests.
|
||||
|
||||
@@ -54,14 +54,14 @@ func (r *Registry) Register(e ToolEntry) error {
|
||||
return fmt.Errorf("%w: %q", ErrDuplicateTool, e.Name)
|
||||
}
|
||||
|
||||
// Defensive copy — sever shared Schema/RequiresEnv references so the
|
||||
// Defensive copy -- sever shared Schema/RequiresEnv references so the
|
||||
// caller cannot mutate them and race with concurrent readers.
|
||||
r.tools[e.Name] = e.Clone()
|
||||
return nil
|
||||
}
|
||||
|
||||
// All returns all registered tool entries. The returned slice is a
|
||||
// snapshot — mutating it does not affect the registry.
|
||||
// snapshot -- mutating it does not affect the registry.
|
||||
func (r *Registry) All() []ToolEntry {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
@@ -100,7 +100,7 @@ func (r *Registry) Available() []ToolEntry {
|
||||
}
|
||||
r.mu.RUnlock()
|
||||
|
||||
// Evaluate CheckFn outside the lock — no deadlock risk.
|
||||
// Evaluate CheckFn outside the lock -- no deadlock risk.
|
||||
var out []ToolEntry
|
||||
for _, e := range snapshot {
|
||||
if e.Available() {
|
||||
@@ -117,7 +117,7 @@ func (r *Registry) Available() []ToolEntry {
|
||||
// Discover returns the number of Register calls found. Function fields
|
||||
// (Handler, CheckFn, DynamicSchemaOverrides) cannot be resolved from
|
||||
// static source analysis and remain nil. Entries that fail
|
||||
// [ToolEntry.Validate] — typically because Handler is nil — are
|
||||
// [ToolEntry.Validate] -- typically because Handler is nil -- are
|
||||
// counted but not registered.
|
||||
//
|
||||
// Parse errors in individual files do not stop the scan; they are
|
||||
|
||||
@@ -147,7 +147,7 @@ func TestRegistryAvailable(t *testing.T) {
|
||||
t.Errorf("expected 3 available (toggle is true), got %d", len(r.Available()))
|
||||
}
|
||||
flag = false
|
||||
// Available() re-evaluates — the closure captures &flag.
|
||||
// Available() re-evaluates -- the closure captures &flag.
|
||||
if len(r.Available()) != 2 {
|
||||
t.Errorf("expected 2 available (toggle is now false), got %d", len(r.Available()))
|
||||
}
|
||||
@@ -288,11 +288,11 @@ func TestRegistryAvailableReentrySafety(t *testing.T) {
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool {
|
||||
called = true
|
||||
// Call All() from inside CheckFn — must not deadlock.
|
||||
// Call All() from inside CheckFn -- must not deadlock.
|
||||
_ = r.All()
|
||||
// Call ByToolset from inside CheckFn — must not deadlock.
|
||||
// Call ByToolset from inside CheckFn -- must not deadlock.
|
||||
_ = r.ByToolset("")
|
||||
// Call Register from inside CheckFn — must not deadlock
|
||||
// Call Register from inside CheckFn -- must not deadlock
|
||||
// (was the original deadlock trigger when lock was held).
|
||||
_ = r.Register(ToolEntry{Name: "nested-reg", Handler: noopHandler})
|
||||
return true
|
||||
@@ -322,7 +322,7 @@ func TestRegistryRegisterDefensiveCopy(t *testing.T) {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
// Mutate the original schema and env — must not affect registry.
|
||||
// Mutate the original schema and env -- must not affect registry.
|
||||
schema["key"] = "mutated"
|
||||
env[0] = "MUTATED"
|
||||
|
||||
@@ -331,10 +331,10 @@ func TestRegistryRegisterDefensiveCopy(t *testing.T) {
|
||||
t.Fatalf("expected 1 tool, got %d", len(all))
|
||||
}
|
||||
if all[0].Schema["key"] != "original" {
|
||||
t.Errorf("Schema[key] = %v, want 'original' — caller mutation leaked into registry", all[0].Schema["key"])
|
||||
t.Errorf("Schema[key] = %v, want 'original' -- caller mutation leaked into registry", all[0].Schema["key"])
|
||||
}
|
||||
if all[0].RequiresEnv[0] != "ORIGINAL" {
|
||||
t.Errorf("RequiresEnv[0] = %q, want 'ORIGINAL' — caller mutation leaked into registry", all[0].RequiresEnv[0])
|
||||
t.Errorf("RequiresEnv[0] = %q, want 'ORIGINAL' -- caller mutation leaked into registry", all[0].RequiresEnv[0])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package tools is the central tool subsystem for archie-core. It defines
|
||||
// the ToolEntry data type that every tool — built-in, MCP, or plugin —
|
||||
// the ToolEntry data type that every tool -- built-in, MCP, or plugin --
|
||||
// registers with. The registry (17.2) and guardrails (17.10–17.15) are
|
||||
// built on top of this type.
|
||||
package tools
|
||||
@@ -26,14 +26,14 @@ type Handler func(ctx context.Context, input map[string]any) (output any, err er
|
||||
type CheckFn func() bool
|
||||
|
||||
// SchemaOverrideFn mutates a tool's JSON Schema at runtime. Use it to
|
||||
// inject dynamic values — for example, enumerating MCP server names or
|
||||
// inject dynamic values -- for example, enumerating MCP server names or
|
||||
// filesystem paths that aren't known until the daemon starts. A nil
|
||||
// override means the schema is static.
|
||||
type SchemaOverrideFn func(schema JSONSchema) JSONSchema
|
||||
|
||||
// ToolEntry is the foundational data type for the tools subsystem. Every
|
||||
// tool — built-in, MCP server, plugin-provided, or dynamically registered
|
||||
// — is represented by a ToolEntry. Fields with `json:"-"` tags are
|
||||
// tool -- built-in, MCP server, plugin-provided, or dynamically registered
|
||||
// -- is represented by a ToolEntry. Fields with `json:"-"` tags are
|
||||
// runtime-only (not serialized).
|
||||
type ToolEntry struct {
|
||||
// Name uniquely identifies this tool (e.g. "read_file", "write_file",
|
||||
@@ -54,7 +54,7 @@ type ToolEntry struct {
|
||||
// Must be non-nil for the tool to be functional.
|
||||
Handler Handler `json:"-"`
|
||||
|
||||
// CheckFn reports whether the tool is currently available — for
|
||||
// CheckFn reports whether the tool is currently available -- for
|
||||
// example, an MCP server might be offline, or a required binary might
|
||||
// not be installed. A nil CheckFn means always available.
|
||||
CheckFn CheckFn `json:"-"`
|
||||
@@ -65,6 +65,11 @@ type ToolEntry struct {
|
||||
// (the check only matters at invocation time).
|
||||
RequiresEnv []string `json:"requires_env,omitempty"`
|
||||
|
||||
// Classification is a bitmask describing the tool's behavioral
|
||||
// characteristics (idempotent, mutating, etc.). Zero means no
|
||||
// special classification. See [ToolClassification] for valid flags.
|
||||
Classification ToolClassification `json:"classification,omitempty"`
|
||||
|
||||
// IsAsync distinguishes synchronous tools (complete immediately) from
|
||||
// asynchronous ones (start a background operation and return a handle
|
||||
// for polling). Default (false) is synchronous.
|
||||
|
||||
@@ -148,15 +148,15 @@ func TestToolEntryResolvedSchema(t *testing.T) {
|
||||
|
||||
func TestToolEntryClone(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "original",
|
||||
Toolset: "test",
|
||||
Schema: JSONSchema{"key": "value"},
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return true },
|
||||
RequiresEnv: []string{"X", "Y"},
|
||||
IsAsync: true,
|
||||
Description: "a test tool",
|
||||
Emoji: "🧪",
|
||||
Name: "original",
|
||||
Toolset: "test",
|
||||
Schema: JSONSchema{"key": "value"},
|
||||
Handler: noopHandler,
|
||||
CheckFn: func() bool { return true },
|
||||
RequiresEnv: []string{"X", "Y"},
|
||||
IsAsync: true,
|
||||
Description: "a test tool",
|
||||
Emoji: "🧪",
|
||||
MaxResultSizeChars: 4096,
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ func TestToolEntryClone(t *testing.T) {
|
||||
t.Errorf("IsAsync = %v, want %v", clone.IsAsync, e.IsAsync)
|
||||
}
|
||||
|
||||
// Handler and CheckFn are shared (function pointers — not deep-copied).
|
||||
// Handler and CheckFn are shared (function pointers -- not deep-copied).
|
||||
// This is documented behavior.
|
||||
|
||||
// RequiresEnv is an independent copy.
|
||||
@@ -199,7 +199,7 @@ func TestToolEntryCloneDeepNested(t *testing.T) {
|
||||
"name": JSONSchema{"type": "string"},
|
||||
},
|
||||
"required": []any{"name"},
|
||||
"tags": []string{"a", "b"},
|
||||
"tags": []string{"a", "b"},
|
||||
},
|
||||
}
|
||||
clone := e.Clone()
|
||||
@@ -231,17 +231,17 @@ func TestToolEntryCloneDeepNested(t *testing.T) {
|
||||
|
||||
func TestToolEntryJSONRoundTrip(t *testing.T) {
|
||||
e := ToolEntry{
|
||||
Name: "greet",
|
||||
Toolset: "demo",
|
||||
Schema: JSONSchema{"type": "object", "properties": JSONSchema{"name": JSONSchema{"type": "string"}}},
|
||||
Handler: noopHandler, // json:"-" — excluded
|
||||
CheckFn: func() bool { return true }, // json:"-" — excluded
|
||||
RequiresEnv: []string{"GREET_NAME"},
|
||||
IsAsync: true,
|
||||
Description: "Sends a greeting",
|
||||
Emoji: "👋",
|
||||
MaxResultSizeChars: 1000,
|
||||
DynamicSchemaOverrides: nil, // json:"-" — excluded
|
||||
Name: "greet",
|
||||
Toolset: "demo",
|
||||
Schema: JSONSchema{"type": "object", "properties": JSONSchema{"name": JSONSchema{"type": "string"}}},
|
||||
Handler: noopHandler, // json:"-" -- excluded
|
||||
CheckFn: func() bool { return true }, // json:"-" -- excluded
|
||||
RequiresEnv: []string{"GREET_NAME"},
|
||||
IsAsync: true,
|
||||
Description: "Sends a greeting",
|
||||
Emoji: "👋",
|
||||
MaxResultSizeChars: 1000,
|
||||
DynamicSchemaOverrides: nil, // json:"-" -- excluded
|
||||
}
|
||||
|
||||
data, err := json.Marshal(e)
|
||||
@@ -317,7 +317,7 @@ func TestToolEntryZeroValue(t *testing.T) {
|
||||
t.Error("zero ToolEntry should fail Validate")
|
||||
}
|
||||
if !e.Available() {
|
||||
// nil CheckFn = available — this is correct even for zero value.
|
||||
// nil CheckFn = available -- this is correct even for zero value.
|
||||
}
|
||||
if e.ResolvedSchema() != nil {
|
||||
t.Error("zero ToolEntry should have nil resolved schema")
|
||||
@@ -332,6 +332,6 @@ func TestToolEntryJSONSchemaIsNilByDefault(t *testing.T) {
|
||||
}
|
||||
// Schema field omitted when nil.
|
||||
if strings.Contains(string(data), `"schema"`) {
|
||||
t.Log("schema present in JSON (either null or omitted) — both are acceptable")
|
||||
t.Log("schema present in JSON (either null or omitted) -- both are acceptable")
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@
|
||||
<body>
|
||||
<header>
|
||||
<h1>archie</h1>
|
||||
<span class="sub">autonomous project agent — <span id="conn" class="muted">connecting…</span></span>
|
||||
<span class="sub">autonomous project agent -- <span id="conn" class="muted">connecting…</span></span>
|
||||
</header>
|
||||
<main>
|
||||
<div class="cards" id="cards"></div>
|
||||
@@ -99,7 +99,7 @@
|
||||
</section>
|
||||
|
||||
<section id="timeline">
|
||||
<h2>Task timeline — <span id="timeline-title"></span></h2>
|
||||
<h2>Task timeline -- <span id="timeline-title"></span></h2>
|
||||
<div class="section-table"><table id="timeline-table"><thead><tr>
|
||||
<th>time</th><th>kind</th><th>stage</th><th>detail</th>
|
||||
</tr></thead><tbody></tbody></table></div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package webui is archied's observability dashboard: task board,
|
||||
// per-task timelines, workflow/stage metrics, and a live event tail
|
||||
// over SSE. Read-only — the daemon is steered through GitHub, not here.
|
||||
// over SSE. Read-only -- the daemon is steered through GitHub, not here.
|
||||
// Bind it to localhost or a tailnet address; it has no auth.
|
||||
package webui
|
||||
|
||||
|
||||
@@ -224,7 +224,7 @@ func TestIndexEscapesSingleQuotesInOnclick(t *testing.T) {
|
||||
}
|
||||
|
||||
// The onclick template must use escJS (not esc) for owner and
|
||||
// repo — the values interpolated into the single-quoted JS str.
|
||||
// repo -- the values interpolated into the single-quoted JS str.
|
||||
if !strings.Contains(body, "escJS(t.owner)") {
|
||||
t.Error("onclick does not use escJS for owner")
|
||||
}
|
||||
@@ -244,7 +244,7 @@ func TestIndexEscDoesNotEscapeSingleQuotes(t *testing.T) {
|
||||
}
|
||||
body := w.Body.String()
|
||||
|
||||
// esc() must NOT escape single quotes — it's used for HTML
|
||||
// esc() must NOT escape single quotes -- it's used for HTML
|
||||
// content/attribute contexts where apostrophes are legitimate
|
||||
// (e.g. issue titles like "Don't panic").
|
||||
idx := strings.Index(body, "const esc =")
|
||||
@@ -264,7 +264,7 @@ func TestIndexEscDoesNotEscapeSingleQuotes(t *testing.T) {
|
||||
}
|
||||
charClass := snippet[reStart : reStart+reEnd]
|
||||
if strings.Contains(charClass, "'") {
|
||||
t.Error("esc() regex escapes single quotes — this would cause backslash artifacts in HTML text")
|
||||
t.Error("esc() regex escapes single quotes -- this would cause backslash artifacts in HTML text")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// AgentStage is the reusable bridge from a workflow stage to an
|
||||
// agentloop run. Every LLM-driven stage in any workflow (implement's
|
||||
// planner/builder, tdd's test-writer/fixer, feasibility's analyst)
|
||||
// is an AgentStage with a different mission, gate, and result handler —
|
||||
// is an AgentStage with a different mission, gate, and result handler --
|
||||
// never a new engine.
|
||||
type AgentStage struct {
|
||||
Name string
|
||||
@@ -33,7 +33,7 @@ type AgentStage struct {
|
||||
// MaxSteps overrides the configured step budget when > 0 (planner
|
||||
// stages are cheaper than builder stages).
|
||||
MaxSteps int
|
||||
// ProtectGlobs blocks write/edit on matching paths for this stage —
|
||||
// ProtectGlobs blocks write/edit on matching paths for this stage --
|
||||
// an environmental constraint, not a prompt rule (TDD's fix stage
|
||||
// protects the committed repro tests; every builder stage protects
|
||||
// the repo's generated files). The returned globs are combined
|
||||
@@ -48,7 +48,7 @@ type AgentStage struct {
|
||||
// ReviewResult gates agent output before OnResult forwards it to
|
||||
// human channels. The daemon calls this hook to review stage output
|
||||
// (issue comments, PR bodies) before human delivery. Return an
|
||||
// error to block the stage. Nil means pass-through — no review.
|
||||
// error to block the stage. Nil means pass-through -- no review.
|
||||
// PRD §1: daemon reviews agent responses before forwarding.
|
||||
ReviewResult func(*TaskContext, agentexec.Result) error
|
||||
}
|
||||
@@ -207,7 +207,7 @@ func missionWithSkill(tc *TaskContext, mission string) string {
|
||||
|
||||
// loadSkillBody loads the SKILL.md body and plugins for the current
|
||||
// workflow from the worktree's .agents/skills/ directory. Skills declare
|
||||
// their workflow in metadata.archie.workflow — no hardcoded mapping.
|
||||
// their workflow in metadata.archie.workflow -- no hardcoded mapping.
|
||||
// When metadata.archie.plugins is non-empty, only the listed plugin files
|
||||
// are loaded in declared order; otherwise all *.go files are globbed.
|
||||
func loadSkillBody(tc *TaskContext) string {
|
||||
|
||||
@@ -175,7 +175,7 @@ func TestFeasibilityRejectsNullFitValue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── regression: Gap 5 — daemon review step ──────────────────────────
|
||||
// ── regression: Gap 5 -- daemon review step ──────────────────────────
|
||||
|
||||
func TestReviewResultBlocksOnResultWhenRejected(t *testing.T) {
|
||||
// Gap 5: no daemon review step before human delivery.
|
||||
@@ -183,7 +183,7 @@ func TestReviewResultBlocksOnResultWhenRejected(t *testing.T) {
|
||||
// to human channels. When ReviewResult returns an error, the stage
|
||||
// must fail and OnResult must NOT be called. When ReviewResult
|
||||
// returns nil, OnResult IS called. Currently ReviewResult exists
|
||||
// but no workflow uses it — the review step is never exercised.
|
||||
// but no workflow uses it -- the review step is never exercised.
|
||||
runner := &fakeAgentRunner{result: agentexec.Result{
|
||||
Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed,
|
||||
Summary: "sensitive output", TokensUsed: 1,
|
||||
@@ -215,7 +215,7 @@ func TestReviewResultBlocksOnResultWhenRejected(t *testing.T) {
|
||||
}
|
||||
if onResultCalled {
|
||||
t.Error("Gap 5: ReviewResult rejected the output but OnResult was still called. " +
|
||||
"ReviewResult must gate OnResult — rejected output must not reach human channels.")
|
||||
"ReviewResult must gate OnResult -- rejected output must not reach human channels.")
|
||||
}
|
||||
|
||||
// Test 2: ReviewResult approves → OnResult IS called.
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
// against the project's direction, close it with reasons when it
|
||||
// doesn't fit, otherwise produce a PRD, deliver it to Sam (issue
|
||||
// comment + notify webhook), and hand the task to waiting_human. The
|
||||
// daemon watches for Sam's reply and — LLM-judged, not keyword-matched —
|
||||
// daemon watches for Sam's reply and -- LLM-judged, not keyword-matched --
|
||||
// requeues approved features under the implement workflow or closes
|
||||
// rejected ones. Routed via the "feature" label.
|
||||
func Feasibility() Workflow {
|
||||
@@ -61,7 +61,7 @@ func Feasibility() Workflow {
|
||||
}
|
||||
tc.decision = &decision{Fit: *captured.Fit, Reasons: captured.Reasons}
|
||||
if !tc.decision.Fit {
|
||||
comment := fmt.Sprintf("**archie assessed this feature as not a fit — closing as won't-do.**\n\n%s\n\n_Reopen and re-assign if you disagree._", tc.decision.Reasons)
|
||||
comment := fmt.Sprintf("**archie assessed this feature as not a fit -- closing as won't-do.**\n\n%s\n\n_Reopen and re-assign if you disagree._", tc.decision.Reasons)
|
||||
if err := tc.Forge.CloseIssue(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, comment); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -96,7 +96,7 @@ func Feasibility() Workflow {
|
||||
// channel the daemon watches) plus the notify webhook (n8n →
|
||||
// email).
|
||||
{Name: "deliver", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
body := fmt.Sprintf("**archie's PRD — awaiting your go/no-go.** Reply on this issue; I'll read your answer.\n\n%s", tc.Task.Plan)
|
||||
body := fmt.Sprintf("**archie's PRD -- awaiting your go/no-go.** Reply on this issue; I'll read your answer.\n\n%s", tc.Task.Plan)
|
||||
commentID, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -25,19 +25,19 @@ func StageBaselineGate() Stage {
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
tc.Log.Warn("baseline red — auto-fixing pre-existing gate failure",
|
||||
tc.Log.Warn("baseline red -- auto-fixing pre-existing gate failure",
|
||||
"cmd", strings.Join(argv, " "),
|
||||
"err", clip(string(out), 200))
|
||||
|
||||
// Run builder to fix the failure via TDD.
|
||||
mission := fmt.Sprintf(
|
||||
"The baseline gate check `%s` failed on the repository %s at the base commit "+
|
||||
"(before any feature work). This is a pre-existing issue — not caused by your work. "+
|
||||
"(before any feature work). This is a pre-existing issue -- not caused by your work. "+
|
||||
"Fix it using TDD:\n\n"+
|
||||
"1. Write a test that proves the failure exists\n"+
|
||||
"2. Run the test — it should FAIL (confirming the bug)\n"+
|
||||
"2. Run the test -- it should FAIL (confirming the bug)\n"+
|
||||
"3. Fix the root cause\n"+
|
||||
"4. Run the test — it should PASS\n"+
|
||||
"4. Run the test -- it should PASS\n"+
|
||||
"5. Repeat until the gate `%s` passes for all packages\n\n"+
|
||||
"Gate output:\n%s\n\n"+
|
||||
"When the gate passes, call finish with status \"passed\".",
|
||||
@@ -67,7 +67,7 @@ func StageBaselineGate() Stage {
|
||||
return fmt.Errorf("baseline-fix agent run: %w", agentErr)
|
||||
}
|
||||
if res.Status != agentexec.StatusPassed {
|
||||
return fmt.Errorf("baseline red — %s fails and builder could not auto-fix (status: %s)",
|
||||
return fmt.Errorf("baseline red -- %s fails and builder could not auto-fix (status: %s)",
|
||||
strings.Join(argv, " "), res.Status)
|
||||
}
|
||||
|
||||
@@ -112,14 +112,14 @@ func Implement() Workflow {
|
||||
"<issue number=%d>\n# %s\n\n%s\n</issue>\n\n"+
|
||||
"Explore the codebase with your read-only tools, then call finish with status "+
|
||||
"\"passed\" and the plan as the summary: files to touch, the approach, acceptance "+
|
||||
"criteria, and what tests should prove it. Keep the plan tightly scoped to the issue — "+
|
||||
"criteria, and what tests should prove it. Keep the plan tightly scoped to the issue -- "+
|
||||
"call finish with status \"blocked\" if the issue is too vague or too large for one PR.",
|
||||
tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body,
|
||||
)
|
||||
},
|
||||
OnResult: func(tc *TaskContext, res agentexec.Result) error {
|
||||
tc.Task.Plan = res.Summary
|
||||
body := fmt.Sprintf("**archie's plan** (review now if you want to veto — building starts immediately):\n\n%s", res.Summary)
|
||||
body := fmt.Sprintf("**archie's plan** (review now if you want to veto -- building starts immediately):\n\n%s", res.Summary)
|
||||
if _, err := tc.Forge.Comment(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil {
|
||||
tc.Log.Warn("failed to post plan comment", "err", err)
|
||||
}
|
||||
@@ -134,13 +134,13 @@ func Implement() Workflow {
|
||||
return GateFromRepo(tc.Repo, tc.Cfg.Budgets)
|
||||
},
|
||||
ExtraRules: "Files matching the repository's protected suffixes (e.g. generated code) are " +
|
||||
"write-blocked — edit their sources instead; the gate regenerates them.",
|
||||
"write-blocked -- edit their sources instead; the gate regenerates them.",
|
||||
Mission: func(tc *TaskContext) string {
|
||||
return fmt.Sprintf(
|
||||
"Implement this GitHub issue on the repository %s, following the plan below.\n\n"+
|
||||
"<issue number=%d>\n# %s\n\n%s\n</issue>\n\n<plan>\n%s\n</plan>\n\n"+
|
||||
"Make the smallest change that satisfies the issue and the plan's acceptance criteria. "+
|
||||
"Do not run git — the orchestrator commits and pushes for you. When done, call finish "+
|
||||
"Do not run git -- the orchestrator commits and pushes for you. When done, call finish "+
|
||||
"with status \"passed\" and a summary written for the human who will review the pull "+
|
||||
"request: what changed, why, and how it was verified.",
|
||||
tc.Repo.FullName(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Plan,
|
||||
|
||||
@@ -25,7 +25,7 @@ func (f *fakeForge) Comment(ctx context.Context, owner, repo string, number int,
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// Remaining forge.Forge stubs — only CloseIssue and Comment are used by StageCommitPush.
|
||||
// Remaining forge.Forge stubs -- only CloseIssue and Comment are used by StageCommitPush.
|
||||
func (f *fakeForge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// ── regression: Gap 7 — plugins discovered but not executed ─────────
|
||||
// ── regression: Gap 7 -- plugins discovered but not executed ─────────
|
||||
|
||||
func TestSkillPluginsAvailableDuringStageExecution(t *testing.T) {
|
||||
// Gap 7: skill.Discover() populates Skill.Plugins but nothing calls
|
||||
@@ -24,7 +24,7 @@ func TestSkillPluginsAvailableDuringStageExecution(t *testing.T) {
|
||||
// accessible via the TaskContext.
|
||||
//
|
||||
// Additionally (Gap 8): when metadata.archie.plugins lists specific
|
||||
// plugin files, only those are loaded — unlisted *.go files are ignored.
|
||||
// plugin files, only those are loaded -- unlisted *.go files are ignored.
|
||||
|
||||
dir := t.TempDir()
|
||||
skillsDir := filepath.Join(dir, ".agents", "skills", "archie-wf-tdd")
|
||||
@@ -61,7 +61,7 @@ func Run(input string) string {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Write an unlisted plugin — it must NOT be loaded.
|
||||
// Write an unlisted plugin -- it must NOT be loaded.
|
||||
if err := os.WriteFile(filepath.Join(pluginsDir, "extra.go"), []byte(`package main
|
||||
|
||||
func Run(input string) string {
|
||||
@@ -89,7 +89,7 @@ func Run(input string) string {
|
||||
// Load the skill body (existing behavior).
|
||||
body := loadSkillBody(tc)
|
||||
if body == "" {
|
||||
t.Fatal("skill body not loaded — worktree setup is wrong")
|
||||
t.Fatal("skill body not loaded -- worktree setup is wrong")
|
||||
}
|
||||
|
||||
// Gap 7 assertion: loadSkillBody must also populate skill plugins
|
||||
@@ -105,12 +105,12 @@ func Run(input string) string {
|
||||
// Gap 8 assertion: only the frontmatter-listed plugin must be loaded.
|
||||
// The unlisted extra.go must NOT appear in SkillPlugins.
|
||||
if len(tc.SkillPlugins) != 1 {
|
||||
t.Errorf("Gap 8: got %d plugins, want 1 — loadSkillBody must honor "+
|
||||
t.Errorf("Gap 8: got %d plugins, want 1 -- loadSkillBody must honor "+
|
||||
"metadata.archie.plugins and exclude unlisted *.go files", len(tc.SkillPlugins))
|
||||
}
|
||||
for _, p := range tc.SkillPlugins {
|
||||
if p.Name == "extra" {
|
||||
t.Error("Gap 8: unlisted plugin 'extra' was loaded — " +
|
||||
t.Error("Gap 8: unlisted plugin 'extra' was loaded -- " +
|
||||
"loadSkillBody must only load plugins declared in metadata.archie.plugins")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ type SkillWorkflow struct {
|
||||
// specific cloned worktree so that per-repo skills are discovered
|
||||
// without restarting the daemon.
|
||||
func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry, error) {
|
||||
// Copy base — never mutate the caller's registry.
|
||||
// Copy base -- never mutate the caller's registry.
|
||||
reg := make(workflow.Registry, len(base))
|
||||
maps.Copy(reg, base)
|
||||
if err := mergeSkillWorkflows(worktree, reg); err != nil {
|
||||
@@ -102,9 +102,9 @@ func mergeSkillWorkflows(worktree string, reg workflow.Registry) error {
|
||||
}
|
||||
if len(wf.Stages) > 0 {
|
||||
// Only warn when TWO SKILLS declare the same workflow name.
|
||||
// Overriding a built-in name is routine — don't log.
|
||||
// Overriding a built-in name is routine -- don't log.
|
||||
if prevSkill, dup := seenFromSkill[entry.Workflow]; dup {
|
||||
slog.Default().Warn("duplicate workflow name across skills — overriding",
|
||||
slog.Default().Warn("duplicate workflow name across skills -- overriding",
|
||||
"workflow", entry.Workflow,
|
||||
"skill", entry.Dir,
|
||||
"previous_skill", prevSkill,
|
||||
@@ -141,7 +141,7 @@ func BuildWorkflow(worktree string, entry SkillWorkflow) (workflow.Workflow, err
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
// Each plugin file is package main defining Stage() — they must be
|
||||
// Each plugin file is package main defining Stage() -- they must be
|
||||
// evaluated in separate interpreters to avoid symbol collisions.
|
||||
stages := make([]workflow.Stage, 0, len(names))
|
||||
for _, name := range names {
|
||||
|
||||
@@ -88,7 +88,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
t.Errorf("stage[1].Name = %q, want world", wf.Stages[1].Name)
|
||||
}
|
||||
|
||||
// Run the workflow — stages must execute in order.
|
||||
// Run the workflow -- stages must execute in order.
|
||||
tc := &workflow.TaskContext{BuildSummary: ""}
|
||||
for _, s := range wf.Stages {
|
||||
if err := s.Run(context.Background(), tc); err != nil {
|
||||
@@ -101,7 +101,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
}
|
||||
|
||||
func TestBuildWorkflowMissingSkillReturnsEmptyWorkflow(t *testing.T) {
|
||||
// Missing plugins directory is not an error — same pattern as
|
||||
// Missing plugins directory is not an error -- same pattern as
|
||||
// wfeval.Discover. Returns a Workflow with no stages.
|
||||
entry := SkillWorkflow{Workflow: "nonexistent", Dir: "nonexistent"}
|
||||
wf, err := BuildWorkflow(t.TempDir(), entry)
|
||||
@@ -124,7 +124,7 @@ func TestBuildRegistryFromSkillCatalog(t *testing.T) {
|
||||
|
||||
dir := t.TempDir()
|
||||
|
||||
// Skill 1: archie-wf-greet — plugin-defined workflow.
|
||||
// Skill 1: archie-wf-greet -- plugin-defined workflow.
|
||||
greetDir := filepath.Join(dir, ".agents", "skills", "archie-wf-greet", "plugins")
|
||||
if err := os.MkdirAll(greetDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -158,7 +158,7 @@ Greet the user.
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Skill 2: archie-wf-implement — overrides the built-in implement workflow.
|
||||
// Skill 2: archie-wf-implement -- overrides the built-in implement workflow.
|
||||
implDir := filepath.Join(dir, ".agents", "skills", "archie-wf-custom-impl", "plugins")
|
||||
if err := os.MkdirAll(implDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -207,9 +207,9 @@ Custom implementation workflow.
|
||||
t.Errorf("Workflow.Name = %q, want greet", wf.Name)
|
||||
}
|
||||
if len(wf.Stages) == 0 {
|
||||
t.Error("workflow 'greet' has no stages — plugin stages not loaded")
|
||||
t.Error("workflow 'greet' has no stages -- plugin stages not loaded")
|
||||
}
|
||||
// Run it — stages must execute.
|
||||
// Run it -- stages must execute.
|
||||
tc := &workflow.TaskContext{BuildSummary: ""}
|
||||
for _, s := range wf.Stages {
|
||||
if err := s.Run(context.Background(), tc); err != nil {
|
||||
@@ -237,7 +237,7 @@ Custom implementation workflow.
|
||||
}
|
||||
}
|
||||
if tc.BuildSummary != "custom-impl-ran" {
|
||||
t.Errorf("BuildSummary = %q, want 'custom-impl-ran' — skill override did not take effect", tc.BuildSummary)
|
||||
t.Errorf("BuildSummary = %q, want 'custom-impl-ran' -- skill override did not take effect", tc.BuildSummary)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -317,7 +317,7 @@ Utility content.
|
||||
// There is no workflow called "utils" because the skill didn't declare one.
|
||||
if _, ok := reg["utils"]; ok {
|
||||
t.Error("BuildRegistry registered 'utils' as a workflow, but the skill " +
|
||||
"did not declare metadata.archie.workflow — only skills that declare " +
|
||||
"did not declare metadata.archie.workflow -- only skills that declare " +
|
||||
"a workflow should produce registry entries")
|
||||
}
|
||||
|
||||
@@ -400,7 +400,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
// Worktree workflow added.
|
||||
wf, ok := aug["custom"]
|
||||
if !ok {
|
||||
t.Fatal("'custom' workflow not found in augmented registry — worktree skill was not discovered")
|
||||
t.Fatal("'custom' workflow not found in augmented registry -- worktree skill was not discovered")
|
||||
}
|
||||
if wf.Name != "custom" {
|
||||
t.Errorf("Workflow.Name = %q, want custom", wf.Name)
|
||||
@@ -485,7 +485,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
t.Errorf("stage[0].Name = %q, want 'repo-plan' from worktree override", wf.Stages[0].Name)
|
||||
}
|
||||
|
||||
// Run it — must use worktree version.
|
||||
// Run it -- must use worktree version.
|
||||
tc := &workflow.TaskContext{BuildSummary: ""}
|
||||
if err := wf.Stages[0].Run(context.Background(), tc); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -496,7 +496,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
}
|
||||
|
||||
func TestAugmentRegistryDoesNotModifyBase(t *testing.T) {
|
||||
// AugmentRegistry returns a NEW registry — the caller's base must
|
||||
// AugmentRegistry returns a NEW registry -- the caller's base must
|
||||
// not be mutated.
|
||||
base := workflow.Registry{"keep": {Name: "keep"}}
|
||||
worktree := t.TempDir()
|
||||
@@ -514,7 +514,7 @@ func TestAugmentRegistryDoesNotModifyBase(t *testing.T) {
|
||||
// Mutating augmented must not affect base.
|
||||
aug["keep"] = workflow.Workflow{Name: "modified"}
|
||||
if base["keep"].Name != "keep" {
|
||||
t.Error("AugmentRegistry mutated the base registry — must return a copy")
|
||||
t.Error("AugmentRegistry mutated the base registry -- must return a copy")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,7 +530,7 @@ func TestAugmentRegistryNonexistentWorktreeReturnsBase(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAugmentRegistryWorktreeWithNoSkillsReturnsBase(t *testing.T) {
|
||||
// A worktree without .agents/skills/ must not error — returns
|
||||
// A worktree without .agents/skills/ must not error -- returns
|
||||
// a copy of the base unchanged.
|
||||
worktree := t.TempDir()
|
||||
base := workflow.Registry{"default": {Name: "default"}}
|
||||
@@ -545,7 +545,7 @@ func TestAugmentRegistryWorktreeWithNoSkillsReturnsBase(t *testing.T) {
|
||||
|
||||
func TestAugmentRegistryWorktreeSkillWithNoStagesDoesNotOverride(t *testing.T) {
|
||||
// A skill that declares a workflow but has no plugins must not
|
||||
// override the base entry — it would produce an empty workflow.
|
||||
// override the base entry -- it would produce an empty workflow.
|
||||
worktree := t.TempDir()
|
||||
skillDir := filepath.Join(worktree, ".agents", "skills", "archie-wf-empty")
|
||||
if err := os.MkdirAll(skillDir, 0o755); err != nil {
|
||||
@@ -574,7 +574,7 @@ No plugins here.
|
||||
|
||||
wf := aug["implement"]
|
||||
if len(wf.Stages) == 0 {
|
||||
t.Error("worktree skill with no stages overrode base — must keep base when skill is empty")
|
||||
t.Error("worktree skill with no stages overrode base -- must keep base when skill is empty")
|
||||
}
|
||||
if wf.Stages[0].Name != "builtin" {
|
||||
t.Error("base stage was replaced by empty worktree skill")
|
||||
@@ -622,7 +622,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
|
||||
base := workflow.Registry{"default": {Name: "default"}}
|
||||
|
||||
// Run 10 concurrent augmentations — none should panic or corrupt state.
|
||||
// Run 10 concurrent augmentations -- none should panic or corrupt state.
|
||||
errs := make(chan error, 10)
|
||||
for range 10 {
|
||||
go func() {
|
||||
@@ -651,7 +651,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
}
|
||||
|
||||
func TestAugmentRegistryBrokenSkillMDIsSkipped(t *testing.T) {
|
||||
// A SKILL.md with invalid YAML must not crash augmentation — the
|
||||
// A SKILL.md with invalid YAML must not crash augmentation -- the
|
||||
// skill is simply skipped (skill.Catalog skips parse errors).
|
||||
worktree := t.TempDir()
|
||||
skillDir := filepath.Join(worktree, ".agents", "skills", "archie-wf-broken")
|
||||
@@ -680,7 +680,7 @@ func TestAugmentRegistryWorktreeWithNoSkillsDir(t *testing.T) {
|
||||
// A worktree that exists but has no .agents/ directory at all
|
||||
// must not error.
|
||||
worktree := t.TempDir()
|
||||
// Don't create .agents/skills/ — just a bare worktree.
|
||||
// Don't create .agents/skills/ -- just a bare worktree.
|
||||
if err := os.WriteFile(filepath.Join(worktree, "README.md"), []byte(`# repo`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -696,14 +696,14 @@ func TestAugmentRegistryWorktreeWithNoSkillsDir(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAugmentRegistryNilBaseReturnsEmpty(t *testing.T) {
|
||||
// A nil base registry must be treated as empty — not panic.
|
||||
// A nil base registry must be treated as empty -- not panic.
|
||||
worktree := t.TempDir()
|
||||
aug, err := AugmentRegistry(worktree, nil)
|
||||
if err != nil {
|
||||
t.Fatal("AugmentRegistry errored with nil base:", err)
|
||||
}
|
||||
if aug == nil {
|
||||
t.Error("AugmentRegistry returned nil for nil base — want empty registry")
|
||||
t.Error("AugmentRegistry returned nil for nil base -- want empty registry")
|
||||
}
|
||||
if len(aug) != 0 {
|
||||
t.Errorf("got %d entries with nil base and no skills, want 0", len(aug))
|
||||
@@ -754,7 +754,7 @@ func TestBuildWorkflowSkipsBrokenPlugin(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// First plugin — valid.
|
||||
// First plugin -- valid.
|
||||
if err := os.WriteFile(filepath.Join(pluginsDir, "01-setup.go"), []byte(`package main
|
||||
|
||||
import (
|
||||
@@ -772,14 +772,14 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Second plugin — BROKEN (syntax error).
|
||||
// Second plugin -- BROKEN (syntax error).
|
||||
if err := os.WriteFile(filepath.Join(pluginsDir, "02-broken.go"), []byte(`package main
|
||||
this is %% NOT VALID GO @@@@
|
||||
`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Third plugin — valid.
|
||||
// Third plugin -- valid.
|
||||
if err := os.WriteFile(filepath.Join(pluginsDir, "03-teardown.go"), []byte(`package main
|
||||
|
||||
import (
|
||||
@@ -1244,7 +1244,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
|
||||
|
||||
func TestBuildRegistrySkipsBrokenSkill(t *testing.T) {
|
||||
// R2: a skill with broken plugins must not prevent other skills
|
||||
// from registering — and must not block daemon startup.
|
||||
// from registering -- and must not block daemon startup.
|
||||
|
||||
dir := t.TempDir()
|
||||
|
||||
@@ -1281,7 +1281,7 @@ Good.
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Skill 2: broken plugins — ALL plugins are broken.
|
||||
// Skill 2: broken plugins -- ALL plugins are broken.
|
||||
badDir := filepath.Join(dir, ".agents", "skills", "archie-wf-bad", "plugins")
|
||||
if err := os.MkdirAll(badDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -1311,11 +1311,11 @@ Broken.
|
||||
|
||||
// Good workflow must still be registered.
|
||||
if _, ok := reg["good"]; !ok {
|
||||
t.Error("'good' workflow missing — broken skill blocked registry build")
|
||||
t.Error("'good' workflow missing -- broken skill blocked registry build")
|
||||
}
|
||||
// Bad workflow must not be registered (it had no valid stages).
|
||||
if _, ok := reg["bad"]; ok {
|
||||
// It might fall back to built-in "bad" — that's fine.
|
||||
// It might fall back to built-in "bad" -- that's fine.
|
||||
// But it should NOT be the empty workflow from the broken skill.
|
||||
t.Log("'bad' workflow present (may be built-in fallback)")
|
||||
}
|
||||
|
||||
+10
-10
@@ -31,7 +31,7 @@ func StagePrepareWorktree() Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
// StageCommit commits everything in the worktree without pushing —
|
||||
// StageCommit commits everything in the worktree without pushing --
|
||||
// used mid-workflow so a PR tells its story in multiple commits (TDD:
|
||||
// failing tests first, fix second). An empty tree parks.
|
||||
func StageCommit(name string, message func(*TaskContext) string) Stage {
|
||||
@@ -49,19 +49,19 @@ func StageCommit(name string, message func(*TaskContext) string) Stage {
|
||||
|
||||
// StageCommitPush commits everything in the worktree and pushes the
|
||||
// branch. When the builder completed with no changes (BuildNoChanges is
|
||||
// set), the issue is already resolved — close it with a comment instead
|
||||
// set), the issue is already resolved -- close it with a comment instead
|
||||
// of erroring on an empty tree.
|
||||
func StageCommitPush(message func(*TaskContext) string) Stage {
|
||||
return Stage{Name: "commit-push", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.BuildNoChanges {
|
||||
body := fmt.Sprintf("**archie closed this issue — no changes required.**\n\n%s", tc.BuildSummary)
|
||||
body := fmt.Sprintf("**archie closed this issue -- no changes required.**\n\n%s", tc.BuildSummary)
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil {
|
||||
tc.Log.Warn("no-op close comment failed", "err", err)
|
||||
}
|
||||
if err := tc.Forge.CloseIssue(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
tc.Outcome = Outcome{Status: store.StatusMerged, Detail: "closed — no changes required"}
|
||||
tc.Outcome = Outcome{Status: store.StatusMerged, Detail: "closed -- no changes required"}
|
||||
return nil
|
||||
}
|
||||
commit := StageCommit("commit-push", message)
|
||||
@@ -72,7 +72,7 @@ func StageCommitPush(message func(*TaskContext) string) Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
// StageDiffCap parks tasks whose diff exceeds the configured line cap —
|
||||
// StageDiffCap parks tasks whose diff exceeds the configured line cap --
|
||||
// oversized changes need human pre-approval, not an auto-opened PR.
|
||||
func StageDiffCap() Stage {
|
||||
return Stage{Name: "diff-cap", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
@@ -86,7 +86,7 @@ func StageDiffCap() Stage {
|
||||
if lines > tc.Cfg.DiffCapLines {
|
||||
tc.Outcome = Outcome{
|
||||
Status: store.StatusParked,
|
||||
Detail: fmt.Sprintf("diff is %d changed lines (cap %d) — split the issue or approve manually", lines, tc.Cfg.DiffCapLines),
|
||||
Detail: fmt.Sprintf("diff is %d changed lines (cap %d) -- split the issue or approve manually", lines, tc.Cfg.DiffCapLines),
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -95,7 +95,7 @@ func StageDiffCap() Stage {
|
||||
|
||||
// StageRepoStages runs every custom stage the repo defines under
|
||||
// .archie/stages/*.go (Yaegi-interpreted via TaskContext.CustomStages),
|
||||
// in the order the loader returns them — a no-op when no loader is wired
|
||||
// in the order the loader returns them -- a no-op when no loader is wired
|
||||
// up or the repo defines none. A custom stage that sets tc.Outcome ends
|
||||
// the workflow there, same as any built-in stage.
|
||||
func StageRepoStages() Stage {
|
||||
@@ -120,7 +120,7 @@ func StageRepoStages() Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
// StageYaegiGate evaluates the repo's optional .archie/gate.go — a
|
||||
// StageYaegiGate evaluates the repo's optional .archie/gate.go -- a
|
||||
// Yaegi-interpreted Go file inspecting the committed diff for
|
||||
// project-specific rules shell gate commands can't express (AST checks,
|
||||
// diff scanning). A missing script is a no-op. Error-level findings
|
||||
@@ -170,7 +170,7 @@ func StageYaegiGate() Stage {
|
||||
// OpenPR opens the task's pull request, records its number, and sets
|
||||
// the terminal pr_open outcome. Stages that need to act after the PR
|
||||
// exists (e.g. posting evidence comments) call this and then do so in
|
||||
// the same stage — the engine stops at the first stage with an outcome.
|
||||
// the same stage -- the engine stops at the first stage with an outcome.
|
||||
func OpenPR(ctx context.Context, tc *TaskContext, body string) error {
|
||||
t := tc.Task
|
||||
title := fmt.Sprintf("%s (archie)", t.Title)
|
||||
@@ -204,7 +204,7 @@ func Bootstrap() Workflow {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
content := fmt.Sprintf("# archie bootstrap\n\nIssue: #%d — %s\nTime: %s\n\nThis file proves the archie pipeline (poll → worktree → push → PR) works for this repository.\n",
|
||||
content := fmt.Sprintf("# archie bootstrap\n\nIssue: #%d -- %s\nTime: %s\n\nThis file proves the archie pipeline (poll → worktree → push → PR) works for this repository.\n",
|
||||
tc.Task.IssueNumber, tc.Task.Title, time.Now().UTC().Format(time.RFC3339))
|
||||
return os.WriteFile(filepath.Join(dir, "bootstrap.md"), []byte(content), 0o644)
|
||||
}},
|
||||
|
||||
@@ -27,8 +27,8 @@ func runGit(t *testing.T, dir string, args ...string) {
|
||||
|
||||
// gitRepoWithOriginRef creates a repo with a base commit, then labels
|
||||
// that commit "origin/<base>" (a plain local branch standing in for a
|
||||
// remote-tracking ref) so Manager.Diff/ChangedFiles — which always diff
|
||||
// against "origin/<base>" — resolve without a real clone/push round trip.
|
||||
// remote-tracking ref) so Manager.Diff/ChangedFiles -- which always diff
|
||||
// against "origin/<base>" -- resolve without a real clone/push round trip.
|
||||
func gitRepoWithOriginRef(t *testing.T, base string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
|
||||
// TDD is the bugfix workflow: prove the bug with failing tests before
|
||||
// fixing it. The repro stage's gate INVERTS the test command
|
||||
// (ExpectFailure) — the run cannot proceed until the new tests fail for
|
||||
// the right reason — and the fix stage restores the repo's full gate.
|
||||
// (ExpectFailure) -- the run cannot proceed until the new tests fail for
|
||||
// the right reason -- and the fix stage restores the repo's full gate.
|
||||
// Routed via the "bug" label.
|
||||
func TDD() Workflow {
|
||||
return Workflow{
|
||||
@@ -49,7 +49,7 @@ func TDD() Workflow {
|
||||
Role: "builder",
|
||||
// The inverted gate: code-quality commands must still
|
||||
// pass, but the test command (last in repo.Gate) MUST
|
||||
// fail — proof the repro captures the bug.
|
||||
// fail -- proof the repro captures the bug.
|
||||
Gate: func(tc *TaskContext) agentexec.Gate {
|
||||
return tddReproGate(tc.Repo, tc.Cfg.Budgets)
|
||||
},
|
||||
@@ -67,18 +67,18 @@ func TDD() Workflow {
|
||||
},
|
||||
}.Stage(),
|
||||
|
||||
// Capture the failing test run — the proof the repro
|
||||
// Capture the failing test run -- the proof the repro
|
||||
// reproduces the bug, posted on the PR later.
|
||||
{Name: "capture-proof", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
argv := testCommandArgv(tc.Repo)
|
||||
if len(argv) == 0 {
|
||||
return fmt.Errorf("tdd: repo %s has no gate configured — cannot capture repro proof (add at least one [[repos.gate]] command, with the test runner last)", tc.Repo.FullName())
|
||||
return fmt.Errorf("tdd: repo %s has no gate configured -- cannot capture repro proof (add at least one [[repos.gate]] command, with the test runner last)", tc.Repo.FullName())
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
|
||||
cmd.Dir = tc.Dir
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err == nil {
|
||||
return fmt.Errorf("repro tests unexpectedly pass after commit — the bug is not captured")
|
||||
return fmt.Errorf("repro tests unexpectedly pass after commit -- the bug is not captured")
|
||||
}
|
||||
tc.ReproProof = clip(string(out), 4000)
|
||||
return nil
|
||||
@@ -95,7 +95,7 @@ func TDD() Workflow {
|
||||
return GateFromRepo(tc.Repo, tc.Cfg.Budgets)
|
||||
},
|
||||
// Environmental, not advisory: the fix stage cannot touch
|
||||
// test files at all — the committed repro is the spec.
|
||||
// test files at all -- the committed repro is the spec.
|
||||
ProtectGlobs: func(tc *TaskContext) []string {
|
||||
glob := tc.Repo.ResolvedTestGlob()
|
||||
if glob == "" {
|
||||
@@ -104,7 +104,7 @@ func TDD() Workflow {
|
||||
return []string{glob}
|
||||
},
|
||||
ExtraRules: "The repro tests written in the previous stage are the bug's specification. " +
|
||||
"Test files are write-protected in this stage — make them pass by fixing the code they exercise.",
|
||||
"Test files are write-protected in this stage -- make them pass by fixing the code they exercise.",
|
||||
Mission: func(tc *TaskContext) string {
|
||||
return fmt.Sprintf(
|
||||
"Fix the bug in the repository %s. Failing repro tests are already committed; make them pass.\n\n"+
|
||||
@@ -149,7 +149,7 @@ func TDD() Workflow {
|
||||
|
||||
// tddReproGate builds the inverted gate for the repro-tests stage:
|
||||
// every command from repo.Gate runs normally except the last one (the
|
||||
// test runner, by convention), which gets ExpectFailure — the repro
|
||||
// test runner, by convention), which gets ExpectFailure -- the repro
|
||||
// must fail the tests to prove the bug exists.
|
||||
func tddReproGate(repo config.Repo, budgets config.Budgets) agentexec.Gate {
|
||||
if len(repo.Gate) == 0 {
|
||||
|
||||
@@ -24,7 +24,7 @@ const stagesDir = ".archie/stages"
|
||||
|
||||
// Discover loads every .archie/stages/*.go file in dir and returns the
|
||||
// workflow.Stage each exports, in filename order. A missing directory is
|
||||
// not an error — it returns (nil, nil), meaning no custom stages are
|
||||
// not an error -- it returns (nil, nil), meaning no custom stages are
|
||||
// configured for this repo.
|
||||
func Discover(dir string) ([]workflow.Stage, error) {
|
||||
entries, err := os.ReadDir(filepath.Join(dir, stagesDir))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package workflow is archied's extensible pipeline engine. A Workflow
|
||||
// is an ordered list of stages over a shared TaskContext; stages are
|
||||
// either deterministic steps (git, gate, PR, comments) or agent stages
|
||||
// (agentloop runs). New workflows compose from the shared step library —
|
||||
// (agentloop runs). New workflows compose from the shared step library --
|
||||
// adding one must never require reimplementing the engine or the steps.
|
||||
package workflow
|
||||
|
||||
@@ -58,7 +58,7 @@ type TaskContext struct {
|
||||
// CustomStages discovers a repo's per-repo custom stages (Yaegi-
|
||||
// interpreted from .archie/stages/*.go in the given worktree
|
||||
// directory), returning them in the order they should run. Wired up
|
||||
// by the composition root (cmd/archied) — nil disables discovery, so
|
||||
// by the composition root (cmd/archied) -- nil disables discovery, so
|
||||
// StageRepoStages is a no-op. Kept as an injected function rather
|
||||
// than a direct import to avoid workflow depending on its own
|
||||
// generated Yaegi symbol table (an import cycle).
|
||||
@@ -75,10 +75,10 @@ type TaskContext struct {
|
||||
// Dir/Branch are set by the prepare step.
|
||||
Dir string
|
||||
Branch string
|
||||
// BuildSummary is the builder agent's finish summary — the PR body.
|
||||
// BuildSummary is the builder agent's finish summary -- the PR body.
|
||||
BuildSummary string
|
||||
// BuildNoChanges is set when the builder returned StatusPassed but
|
||||
// made no file changes — the fix already exists or the issue is a
|
||||
// made no file changes -- the fix already exists or the issue is a
|
||||
// no-op. StageCommitPush closes the issue instead of erroring.
|
||||
BuildNoChanges bool
|
||||
// ReproProof is the captured failing-test output from a TDD repro
|
||||
@@ -153,7 +153,7 @@ func Route(t *store.Task, reg Registry) Workflow {
|
||||
}
|
||||
case "bootstrap":
|
||||
// Diagnostics: exercise the full pipeline deterministically
|
||||
// (no LLM spend) — invites, clone, push, PR, labels.
|
||||
// (no LLM spend) -- invites, clone, push, PR, labels.
|
||||
if wf, ok := reg["bootstrap"]; ok {
|
||||
return wf
|
||||
}
|
||||
@@ -175,7 +175,7 @@ func Route(t *store.Task, reg Registry) Workflow {
|
||||
}
|
||||
|
||||
// Run executes the workflow: stages in order, task persisted after each,
|
||||
// errors park the task with a comment on the issue — never silently.
|
||||
// errors park the task with a comment on the issue -- never silently.
|
||||
func Run(ctx context.Context, wf Workflow, tc *TaskContext) {
|
||||
t := tc.Task
|
||||
t.Workflow = wf.Name
|
||||
@@ -204,7 +204,7 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) {
|
||||
return
|
||||
}
|
||||
t.ParkReason = fmt.Sprintf("stage %s: %v", stage.Name, err)
|
||||
log.Warn("stage failed — parking", "stage", stage.Name, "err", err)
|
||||
log.Warn("stage failed -- parking", "stage", stage.Name, "err", err)
|
||||
park(ctx, tc, t.ParkReason)
|
||||
return
|
||||
}
|
||||
@@ -233,7 +233,7 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
|
||||
// stateLabelFor maps a terminal workflow status to its forge label by
|
||||
// looking up the configured [dispatch.labels]; empty clears (done states
|
||||
// — the issue closes or the PR speaks).
|
||||
// -- the issue closes or the PR speaks).
|
||||
func stateLabelFor(d config.Dispatch, status string) string {
|
||||
switch status {
|
||||
case store.StatusPROpen:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package worktree owns archied's git operations: fresh clone per task,
|
||||
// branch, commit as the bot identity, push, diff stats, cleanup. The
|
||||
// daemon performs these deterministically — the model's shell tool never
|
||||
// daemon performs these deterministically -- the model's shell tool never
|
||||
// drives git.
|
||||
package worktree
|
||||
|
||||
@@ -119,7 +119,7 @@ func (m *Manager) prepare(ctx context.Context, owner, repo, base string, issue i
|
||||
}
|
||||
}
|
||||
if _, err := m.git(ctx, dir, "reset", "--hard", "origin/"+base); err != nil {
|
||||
_ = err // Non-fatal — the branch may not have been pushed yet.
|
||||
_ = err // Non-fatal -- the branch may not have been pushed yet.
|
||||
}
|
||||
return dir, branch, nil
|
||||
}
|
||||
@@ -349,7 +349,7 @@ func (m *Manager) Push(ctx context.Context, dir, branch string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ChangedLines reports lines added+deleted vs the base branch — the
|
||||
// ChangedLines reports lines added+deleted vs the base branch -- the
|
||||
// input to the diff-size cap.
|
||||
func (m *Manager) ChangedLines(ctx context.Context, dir, base string) (int, error) {
|
||||
out, err := m.git(ctx, dir, "diff", "--shortstat", "origin/"+base+"...HEAD")
|
||||
|
||||
@@ -224,7 +224,7 @@ func TestAskpassWrittenOnce(t *testing.T) {
|
||||
t.Fatalf("paths differ: %q vs %q", p1, p2)
|
||||
}
|
||||
|
||||
// Mod time must be unchanged — file was not rewritten.
|
||||
// Mod time must be unchanged -- file was not rewritten.
|
||||
fi2, err := os.Stat(p2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -307,7 +307,7 @@ func TestPrepareResumesAfterInterruptedClone(t *testing.T) {
|
||||
t.Fatalf("working tree missing README.md after prepare: %v", err)
|
||||
}
|
||||
|
||||
// CommitAll must work — the sentinel is excluded from git tracking.
|
||||
// CommitAll must work -- the sentinel is excluded from git tracking.
|
||||
changed, err := m.CommitAll(ctx, dir2, "noop")
|
||||
if err != nil || changed {
|
||||
t.Fatalf("clean CommitAll = (%v, %v), want (false, nil)", changed, err)
|
||||
@@ -318,7 +318,7 @@ func TestPrepareResumesAfterInterruptedClone(t *testing.T) {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
|
||||
// A second Prepare call must short-circuit via the sentinel — no re-clone.
|
||||
// A second Prepare call must short-circuit via the sentinel -- no re-clone.
|
||||
dir3, _, err := m.Prepare(ctx, "acme", "interrupt", "main", 1, "feat: interrupted", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("second prepare: %v", err)
|
||||
@@ -610,7 +610,7 @@ func TestPushRejected(t *testing.T) {
|
||||
}
|
||||
|
||||
// Now the first worktree's branch is behind origin/branch.
|
||||
// Make a change and try to push — it should be rejected.
|
||||
// Make a change and try to push -- it should be rejected.
|
||||
if err := os.WriteFile(filepath.Join(dir, "third.txt"), []byte("third\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package worktreerpc lets archie-agent request the two worktree
|
||||
// operations that touch the network — clone/fetch (Prepare) and push
|
||||
// (Push) — over core NATS request/reply, instead of holding the forge
|
||||
// operations that touch the network -- clone/fetch (Prepare) and push
|
||||
// (Push) -- over core NATS request/reply, instead of holding the forge
|
||||
// credential itself. archied remains the sole holder of
|
||||
// worktree.Manager.Token and performs both against the host worktree
|
||||
// directory (the same files the agent container has bind-mounted at
|
||||
@@ -29,7 +29,7 @@ const (
|
||||
)
|
||||
|
||||
// PushRequest identifies the task's worktree by owner/repo/issue rather
|
||||
// than trusting a path from the (sandboxed) agent — the server resolves
|
||||
// than trusting a path from the (sandboxed) agent -- the server resolves
|
||||
// the directory itself via worktree.Manager.Dir.
|
||||
type PushRequest struct {
|
||||
Owner string `json:"owner"`
|
||||
|
||||
@@ -34,7 +34,7 @@ func connect(t *testing.T, url string) *nats.Conn {
|
||||
}
|
||||
|
||||
// newLocalRemote creates a bare repo with one commit on main, reachable
|
||||
// via file://<host>/<owner>/<repo>.git — mirrors worktree_test.go's helper.
|
||||
// via file://<host>/<owner>/<repo>.git -- mirrors worktree_test.go's helper.
|
||||
func newLocalRemote(t *testing.T, owner, repo string) string {
|
||||
t.Helper()
|
||||
host := t.TempDir()
|
||||
@@ -178,7 +178,7 @@ func TestClientPropagatesServerError(t *testing.T) {
|
||||
t.Cleanup(unsub)
|
||||
|
||||
client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second}
|
||||
// No worktree ever prepared at this dir — push must fail.
|
||||
// No worktree ever prepared at this dir -- push must fail.
|
||||
err = client.Push(context.Background(), "acme", "nonexistent", 999, "some-branch")
|
||||
if err == nil {
|
||||
t.Fatal("expected Push to propagate the server-side git error")
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
// plugins, skill scripts). Each surface differs in what symbol tables it
|
||||
// loads, what export it resolves, and how it invokes that export, but
|
||||
// all of them build an interpreter the same way and must recover a
|
||||
// panic from interpreted code — including a panic during the call
|
||||
// itself, not just during eval — rather than let it take down the
|
||||
// panic from interpreted code -- including a panic during the call
|
||||
// itself, not just during eval -- rather than let it take down the
|
||||
// daemon.
|
||||
package yaegiutil
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
|
||||
// New returns a Yaegi interpreter with the standard library and any
|
||||
// extraSymbols loaded. Each interpreted file must get its own
|
||||
// interpreter when it declares package main — Yaegi cannot co-evaluate
|
||||
// interpreter when it declares package main -- Yaegi cannot co-evaluate
|
||||
// two package-main files with colliding symbols (e.g. two Stage()
|
||||
// functions) in the same interpreter.
|
||||
func New(opts interp.Options, extraSymbols ...map[string]map[string]reflect.Value) (*interp.Interpreter, error) {
|
||||
@@ -37,7 +37,7 @@ func New(opts interp.Options, extraSymbols ...map[string]map[string]reflect.Valu
|
||||
|
||||
// Resolve evaluates src in i and type-asserts exportPath's value
|
||||
// (e.g. "main.Stage", "gate.Check") to T. It does not itself recover
|
||||
// panics — wrap the call that invokes the returned T in Safe, since a
|
||||
// panics -- wrap the call that invokes the returned T in Safe, since a
|
||||
// panic can happen either during Eval (e.g. an init()) or during the
|
||||
// caller's later invocation of the resolved function.
|
||||
func Resolve[T any](i *interp.Interpreter, src, exportPath string) (result T, err error) {
|
||||
@@ -55,7 +55,7 @@ func Resolve[T any](i *interp.Interpreter, src, exportPath string) (result T, er
|
||||
return fn, nil
|
||||
}
|
||||
|
||||
// Safe runs fn and recovers any panic — interpreted code is untrusted
|
||||
// Safe runs fn and recovers any panic -- interpreted code is untrusted
|
||||
// relative to the daemon's own logic, so a nil dereference or
|
||||
// out-of-range index inside it must become an error, not a crash.
|
||||
// label identifies the interpreted source in the resulting error.
|
||||
|
||||
Reference in new issue
Block a user