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:
sam committed 2026-07-26 09:53:33 +10:00
1 parent 16d6cd62b7
commit f6d51416f0
112 files changed
+587 -582

No files matched your search

+3 -3
View File
@@ -19,9 +19,9 @@ metadata:
This skill adds frontend linting to the gate stage. After Go checks pass,
the gate runs:
1. `stylelint "**/*.css"` — catches syntax errors, invalid properties,
1. `stylelint "**/*.css"` -- catches syntax errors, invalid properties,
duplicate selectors, calc() misuse, missing units
2. `htmlhint "**/*.html"` — catches unclosed tags, mismatched pairs,
2. `htmlhint "**/*.html"` -- catches unclosed tags, mismatched pairs,
duplicate IDs, inline style abuse, missing viewport meta
Both must exit 0. If either fails, the stage parks with the lint output.
@@ -38,6 +38,6 @@ Both must exit 0. If either fails, the stage parks with the lint output.
["htmlhint", "**/*.html"],
]
```
3. Or declare `workflow: frontend` in the skill frontmatter — archie-core
3. Or declare `workflow: frontend` in the skill frontmatter -- archie-core
loads the skill body and the agent knows to run these during build
+5 -5
View File
@@ -20,7 +20,7 @@ what a correct gate looks like and how to diagnose failures.
## Standard gate (Tau and similar Go projects)
Run in this exact order. archie-core does NOT run these — the `ai-sdk/agentloop` gate
Run in this exact order. archie-core does NOT run these -- the `ai-sdk/agentloop` gate
does. This list is what you should configure in `config.toml`:
```toml
@@ -47,9 +47,9 @@ The agent should re-run them after making changes.
### golangci-lint
Common failures and fixes:
- `unused` — remove the unused function or add `//nolint:unused`
- `errcheck` — handle the error or assign to `_`
- `gosec` — review the security finding; never blindly suppress
- `unused` -- remove the unused function or add `//nolint:unused`
- `errcheck` -- handle the error or assign to `_`
- `gosec` -- review the security finding; never blindly suppress
### go test -race
Data races are non-deterministic. If `-race` fails:
@@ -65,6 +65,6 @@ golangci-lint run --tests=false --enable-only=unused,staticcheck ./changed/pkg/.
## When the TDD workflow runs
During `repro-tests`, the test command's expectations are INVERTED — it must FAIL.
During `repro-tests`, the test command's expectations are INVERTED -- it must FAIL.
During `fix`, the full gate runs normally and test files are write-protected.
The agent cannot modify tests in the fix stage; it must fix the code to make them pass.
+4 -4
View File
@@ -75,11 +75,11 @@ pnpm install --frozen-lockfile
- Import order: let eslint fix it with `--fix`
### tsc / typecheck
- `TS2345`: type mismatch — fix the argument or the signature
- `TS2339`: property doesn't exist — check the type definition
- `TS2345`: type mismatch -- fix the argument or the signature
- `TS2339`: property doesn't exist -- check the type definition
- `Cannot find module`: check the import path or install the package
### vitest / jest
- Test timeout: the test is hanging — check async/await, mocks, or network calls
- Snapshot mismatch: the output changed — update the snapshot if the change is intentional
- Test timeout: the test is hanging -- check async/await, mocks, or network calls
- Snapshot mismatch: the output changed -- update the snapshot if the change is intentional
- Assertion failure: fix the code, not the test
+9 -9
View File
@@ -65,16 +65,16 @@ pip install -e ".[dev]"
## Common gate failures
### ruff
- `F401`: unused import — remove it
- `E501`: line too long — break the line
- `I001`: import order — let ruff fix it with `ruff check --fix`
- `F401`: unused import -- remove it
- `E501`: line too long -- break the line
- `I001`: import order -- let ruff fix it with `ruff check --fix`
### mypy
- Missing type annotation on public function — add it
- `Cannot determine type` — add explicit annotation
- Import errors — check the package is installed in the venv
- Missing type annotation on public function -- add it
- `Cannot determine type` -- add explicit annotation
- Import errors -- check the package is installed in the venv
### pytest
- Test discovery failed — check `__init__.py` files and test naming
- Import errors — verify the package is installed (`pip install -e .`)
- Assertion failures — fix the code, not the test
- Test discovery failed -- check `__init__.py` files and test naming
- Import errors -- verify the package is installed (`pip install -e .`)
- Assertion failures -- fix the code, not the test
+3 -3
View File
@@ -25,7 +25,7 @@ The planner agent explores the codebase read-only and produces:
- The expected vs actual behaviour
- Which test cases would prove the bug exists
No code is written. The plan is stored but not posted — the repro proof speaks louder.
No code is written. The plan is stored but not posted -- the repro proof speaks louder.
## Stage 2: Repro Tests (write failing tests only)
@@ -66,9 +66,9 @@ This means the test doesn't actually capture the bug. Check:
- Are there test setup issues (missing imports, wrong package)?
### The fix stage modifies test files
This shouldn't happen — test files are write-protected. If it does, the agent is
This shouldn't happen -- test files are write-protected. If it does, the agent is
bypassing the constraint. The worktree should be inspected.
### The gate is misconfigured
If the repo has no `[[repos.gate]]` entries, TDD cannot run — it needs at least
If the repo has no `[[repos.gate]]` entries, TDD cannot run -- it needs at least
one gate command, with the test runner last.
+1 -1
View File
@@ -1,6 +1,6 @@
# Builds and pushes the archied and archie-agent images on every merge
# to main. carina's watchtower container (see docker-compose.yml) picks
# up the new images and restarts the running daemons — this workflow
# up the new images and restarts the running daemons -- this workflow
# never touches carina directly.
name: deploy
+3 -3
View File
@@ -5,7 +5,7 @@ This project uses **bd** (beads) for issue tracking. Run `bd prime` for full wor
> **Architecture in one line:** Issues live in a local Dolt database
> (`.beads/dolt/`); cross-machine sync uses `bd dolt push/pull` (a
> git-compatible protocol), stored under `refs/dolt/data` on your git
> remote — separate from `refs/heads/*` where your code lives.
> remote -- separate from `refs/heads/*` where your code lives.
> `.beads/issues.jsonl` is a passive export, not the wire protocol.
>
> See [SYNC_CONCEPTS.md](https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md)
@@ -63,9 +63,9 @@ bd close <id> # Complete work
### Rules
- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists
- Use `bd` for ALL task tracking -- do NOT use TodoWrite, TaskCreate, or markdown TODO lists
- Run `bd prime` for detailed command reference and session close protocol
- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files
- Use `bd remember` for persistent knowledge -- do NOT use MEMORY.md files
**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md for details and anti-patterns.
+19 -19
View File
@@ -31,7 +31,7 @@ queued → running(workflow:stage) → pr_open → merged | rejected
parked
```
**Crash recovery:** tasks left in `running` are re-queued on startup. Parks are never silent — every park posts a comment with the reason and gate output.
**Crash recovery:** tasks left in `running` are re-queued on startup. Parks are never silent -- every park posts a comment with the reason and gate output.
**PR reconciliation:** the daemon polls open PRs, checks GitHub state (`merged`/`closed`), transitions the task, and cleans up worktrees.
@@ -42,7 +42,7 @@ queued → running(workflow:stage) → pr_open → merged | rejected
- `Workflow` = named list of `Stage`s
- `Stage` = `Name` + `Run(ctx, *TaskContext) error`
- `TaskContext` = mutable bag: Task, Repo, Config, Forge, Store, Agent runner, worktree dir/branch, scratch fields
- `Outcome` = terminal decision (status + detail) — ends the workflow immediately
- `Outcome` = terminal decision (status + detail) -- ends the workflow immediately
- `Registry` = `map[string]Workflow`
### Routing (`Route`)
@@ -61,7 +61,7 @@ Stages execute sequentially. After each stage:
- Outcome set → finish (transition task, update labels)
- Neither → continue to next stage
A workflow that ends without an outcome parks — definition bugs must not vanish silently.
A workflow that ends without an outcome parks -- definition bugs must not vanish silently.
## Workflows
@@ -91,7 +91,7 @@ prepare → baseline-gate → plan(planner, read-only) → build(builder, gated)
prepare → baseline-gate → analyse(planner) → repro-tests(builder, inverted gate) → capture-proof → commit-repro → fix(builder, normal gate, test files protected) → commit-push → diff-cap → open-pr + repro-evidence
```
- **repro-tests:** the quality gate is **inverted** — the test command must FAIL. Proven failure is required.
- **repro-tests:** the quality gate is **inverted** -- the test command must FAIL. Proven failure is required.
- **capture-proof:** runs the test command deterministically, captures the failing output
- **commit-repro:** commits the failing tests as the first commit
- **fix:** test files are **environmentally write-protected** (not prompt-ruled). The agent fixes code, not tests.
@@ -130,42 +130,42 @@ State labels (`archie:queued`, `archie:working`, etc.) are created on demand, re
## Worktree Manager
Every task gets a fresh clone — no persistent state between runs. The model never runs git.
Every task gets a fresh clone -- no persistent state between runs. The model never runs git.
```
~/.local/share/archie/work/<owner>-<repo>/issue-<N>/
```
Token auth via a generated `GIT_ASKPASS` helper script — the token never appears in `.git/config` or process argv.
Token auth via a generated `GIT_ASKPASS` helper script -- the token never appears in `.git/config` or process argv.
## Config
Daemon-level TOML (`~/.config/archie/config.toml`):
- `[forge]` — type (github), host, token env var
- `[dispatch]` — trigger (assignee/label/either), labels, ack reaction
- `[[repos]]` — owner, name, base branch, gate commands, protected paths, ecosystem
- `[models]` — planner, builder, triage (provider/model refs)
- `[providers]` — LLM provider configs
- `[agent]` — execution mode (`inprocess` or `subprocess`), worker command, environment allowlist
- `[budgets]` — max steps, max tokens, wall clock, gate max failures
- `[web]` — dashboard listen address
- `[notify]` — webhook URL for notifications
- `[forge]` -- type (github), host, token env var
- `[dispatch]` -- trigger (assignee/label/either), labels, ack reaction
- `[[repos]]` -- owner, name, base branch, gate commands, protected paths, ecosystem
- `[models]` -- planner, builder, triage (provider/model refs)
- `[providers]` -- LLM provider configs
- `[agent]` -- execution mode (`inprocess` or `subprocess`), worker command, environment allowlist
- `[budgets]` -- max steps, max tokens, wall clock, gate max failures
- `[web]` -- dashboard listen address
- `[notify]` -- webhook URL for notifications
Subprocess mode is a migration transport boundary, not a security sandbox: the worker still runs under the daemon UID and can access daemon-readable host resources. The "daemon never runs untrusted code" boundary requires the later container runner with a separate user, a restricted filesystem and process namespace, and explicit mounts.
Per-repo gates are command lists: `[[repos.gate]] = ["go", "vet", "./..."]`. The last command is the test runner (by convention — TDD inverts it).
Per-repo gates are command lists: `[[repos.gate]] = ["go", "vet", "./..."]`. The last command is the test runner (by convention -- TDD inverts it).
## Observability
Every lifecycle event flows through an internal event bus:
- SQLite event log (every event stamped with a row ID)
- Live dashboard via SSE (server-sent events)
- Bounded subscriber buffers — slow consumers drop events, never block the daemon
- Bounded subscriber buffers -- slow consumers drop events, never block the daemon
## Key Design Decisions
1. **Environmental constraints over prompt rules.** The gate, test-file protection, and diff cap are code enforcement — not "please don't do that" in the system prompt.
1. **Environmental constraints over prompt rules.** The gate, test-file protection, and diff cap are code enforcement -- not "please don't do that" in the system prompt.
2. **The model never runs git.** Worktree operations are deterministic steps, not agent tools.
3. **Tokens as cost, not features.** Token usage is tracked per task and emitted in observability events but never budgeted beyond the agent loop's own limits.
4. **Label-driven routing.** Workflow selection is a switch statement, not an LLM call. A triage LLM is used only for the human reply judgment in waiting_human.
@@ -192,4 +192,4 @@ Every lifecycle event flows through an internal event bus:
- Gitea forge implementation
- More ecosystems
- Notification integrations beyond n8n webhook
- Skills (SKILL.md support — see `.archie/skills/`)
- Skills (SKILL.md support -- see `.archie/skills/`)
+2 -2
View File
@@ -18,9 +18,9 @@ bd close <id> # Complete work
### Rules
- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists
- Use `bd` for ALL task tracking -- do NOT use TodoWrite, TaskCreate, or markdown TODO lists
- Run `bd prime` for detailed command reference and session close protocol
- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files
- Use `bd remember` for persistent knowledge -- do NOT use MEMORY.md files
**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md for details and anti-patterns.
+3 -3
View File
@@ -1,7 +1,7 @@
// Command archie-agent is a long-running NATS-connected worker. It answers
// two request shapes: single-stage archie.agent.> requests over the
// ARCHIE_TASKS JetStream stream (the legacy per-stage protocol), and full
// task handoffs on archie.taskrun.> (core NATS, queue-grouped) — where it
// task handoffs on archie.taskrun.> (core NATS, queue-grouped) -- where it
// runs workflow.Route/workflow.Run itself, proxying Store/Forge/worktree
// operations back to archied over NATS instead of holding those
// credentials directly.
@@ -189,7 +189,7 @@ func run() int {
// bootTaskID reads the boot-time task.json brief the daemon writes into
// the worktree before container acquire (container.WriteTaskJSON) and
// returns its ID. Returns (0, false) when the file is absent, unparseable,
// or has no ID — any of which mean "shared pool mode, no dedicated task."
// or has no ID -- any of which mean "shared pool mode, no dedicated task."
func bootTaskID(mountDir string, log *slog.Logger) (int64, bool) {
data, err := os.ReadFile(filepath.Join(mountDir, "task.json"))
if err != nil {
@@ -197,7 +197,7 @@ func bootTaskID(mountDir string, log *slog.Logger) (int64, bool) {
}
var payload container.TaskPayload
if err := json.Unmarshal(data, &payload); err != nil {
log.Warn("task.json present but unparseable — falling back to shared queue subscription", "err", err)
log.Warn("task.json present but unparseable -- falling back to shared queue subscription", "err", err)
return 0, false
}
if payload.ID <= 0 {
+2 -2
View File
@@ -13,14 +13,14 @@ import (
func TestBootTaskID(t *testing.T) {
log := slog.New(slog.DiscardHandler)
t.Run("no task.json — shared pool mode", func(t *testing.T) {
t.Run("no task.json -- shared pool mode", func(t *testing.T) {
id, ok := bootTaskID(t.TempDir(), log)
if ok || id != 0 {
t.Fatalf("bootTaskID() = (%d, %v), want (0, false)", id, ok)
}
})
t.Run("valid task.json — dedicated per-task mode", func(t *testing.T) {
t.Run("valid task.json -- dedicated per-task mode", func(t *testing.T) {
dir := t.TempDir()
data, err := json.Marshal(container.TaskPayload{ID: 42, Owner: "acme", Repo: "widget"})
if err != nil {
+3 -3
View File
@@ -29,7 +29,7 @@ const rpcTimeout = 60 * time.Second
// operations run directly against the container's bind-mounted worktree.
//
// Prepare deliberately discards the RPC response's directory (the
// daemon's host-side path) and returns localDir instead — archied and
// daemon's host-side path) and returns localDir instead -- archied and
// archie-agent see the same files at different paths.
type hybridTrees struct {
push *worktreerpc.Client
@@ -72,7 +72,7 @@ var _ workflow.Trees = (*hybridTrees)(nil)
// runTask builds a workflow.Registry from the container's own mounted
// worktree, routes and runs req.Task's entire workflow, and reports the
// terminal outcome. Store/Forge/worktree-push calls proxy back to archied
// over nc; Store is archied's sole authority for task state — the
// over nc; Store is archied's sole authority for task state -- the
// returned Response.Task is a best-effort snapshot for logging only.
func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunner agentexec.RunnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) {
registry, err := skillbuild.BuildRegistry(workDir)
@@ -118,7 +118,7 @@ func runTask(ctx context.Context, req taskrun.Request, nc *natsio.Conn, newRunne
// handleTaskRun decodes a taskrun.Request from msg, runs it via runTask
// against the container's fixed worktree mount, and replies with the
// outcome. Errors are reported in the reply, not returned — there's no
// outcome. Errors are reported in the reply, not returned -- there's no
// caller to return them to; this is a NATS subscription callback.
func handleTaskRun(ctx context.Context, msg *natsio.Msg, nc *natsio.Conn, log *slog.Logger) {
var req taskrun.Request
+1 -1
View File
@@ -166,7 +166,7 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) {
BaseURL: "file://" + host,
}
// The daemon always prepares the worktree before container acquire —
// The daemon always prepares the worktree before container acquire --
// reproduce that here so the container's bind mount has real content.
hostDir, _, err := daemonTrees.Prepare(ctx, "acme", "widget", "main", 1, task.Title, "", "bootstrap")
if err != nil {
+4 -4
View File
@@ -122,7 +122,7 @@ func run() int {
}()
}
// NATS client (optional — SQLite flow unchanged when [nats] is absent).
// NATS client (optional -- SQLite flow unchanged when [nats] is absent).
var natsClient *nats.Client
if cfg.NATS.URL != "" {
natsToken, err := configuredNATSToken(cfg.NATS, os.Getenv)
@@ -139,7 +139,7 @@ func run() int {
log.Info("nats connected", "url", cfg.NATS.URL)
}
// Container pool (optional — no containers when [containers] is absent).
// Container pool (optional -- no containers when [containers] is absent).
var containerPool *container.Pool
var storeBackend storage.Backend
if cfg.Containers.Enabled {
@@ -175,7 +175,7 @@ func run() int {
storeBackend = storage.NewDockerBackend(dockerCli)
}
// Gateways (optional — absent [chat.telegram] disables). Multi-agent
// Gateways (optional -- absent [chat.telegram] disables). Multi-agent
// collaboration PRD phase C (docs/prds/multi-agent-collaboration.md).
if cfg.Chat.Telegram.TokenEnv != "" {
tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv)
@@ -237,7 +237,7 @@ func run() int {
log.Info("workflow registry built", "workflows", len(registry))
// Load daemon plugins from the configured plugin directory (Layer 2).
// Failed plugins are skipped — the daemon starts with the remaining set.
// Failed plugins are skipped -- the daemon starts with the remaining set.
var pluginReg *plugin.Registry
if cfg.PluginDir != "" {
plugins, err := plugin.LoadDir(cfg.PluginDir, pluginextract.Symbols)
+2 -2
View File
@@ -1,6 +1,6 @@
# Docker Compose overlay: only fields that differ from the base config.
# The daemon loads both — base config.toml first, then this file on top
# (config.LoadOverlay) — so config.toml (the same file inprocess mode
# The daemon loads both -- base config.toml first, then this file on top
# (config.LoadOverlay) -- so config.toml (the same file inprocess mode
# reads) stays the single source of truth for bot_user, forge, dispatch,
# models, providers, budgets, and repos. See docker-compose.yml's
# `-config` / `-config-overlay` flags and volume mounts.
+1 -1
View File
@@ -45,7 +45,7 @@ command = "archie-agent" # executable path for subprocess mode (not used in n
# The worker still runs as the daemon user until the Docker sandbox phase lands.
# env = ["GOCACHE"] # extra environment variable names forwarded to the worker
[web] # observability dashboard (read-only, no auth — keep it local/tailnet)
[web] # observability dashboard (read-only, no auth -- keep it local/tailnet)
listen = "127.0.0.1:8484" # "off" disables
[notify] # optional webhook for human-in-the-loop moments (n8n -> email)
+4 -4
View File
@@ -1,18 +1,18 @@
# archied — design notes
# archied -- design notes
Archie is a resident daemon that keeps personal projects moving: it polls GitHub for issues labelled
`archie`, works each one in an isolated fresh-clone worktree through a routed **workflow**, and opens a
pull request for human review. Sam reviews and merges; the machine grinds in between.
Guiding principle: **environmental constraints over prompt instructions.** Agents don't get asked nicely
to write good code — the quality gate (vet/build/test/lint, configurable per repo and per workflow stage)
to write good code -- the quality gate (vet/build/test/lint, configurable per repo and per workflow stage)
refuses to let a run succeed until it passes. The gate mechanics live in `ai-sdk/agentloop`; this repo
owns orchestration only.
## Workflows, not a pipeline
`internal/workflow` is the engine: a Workflow is an ordered list of stages over a shared TaskContext;
stages are deterministic steps (worktree, gate, diff cap, PR, comments — the shared step library in
stages are deterministic steps (worktree, gate, diff cap, PR, comments -- the shared step library in
`steps.go`) or agent stages (`agentloop.Run` with a stage-specific mission/toolset/gate). Routing is
label-driven (`bug` → tdd, `feature` → feasibility, default → implement), refinable by an LLM triage
stage. Adding a workflow must never require touching the engine or reimplementing steps.
@@ -31,7 +31,7 @@ Planned workflows:
`queued → running(workflow:stage) → waiting_human | pr_open → merged | parked | rejected | closed_wont_do`
SQLite (`internal/store`), WAL, one row per issue with a transitions audit table. Crash recovery:
`running` tasks re-queue on startup with attempt++. Parks are never silent — every park comments on the
`running` tasks re-queue on startup with attempt++. Parks are never silent -- every park comments on the
issue with the reason and gate output.
## Rejected alternative: building on tau's peer-agent runtime
+12 -12
View File
@@ -1,4 +1,4 @@
# archie-core Skills System — PRD
# archie-core Skills System -- PRD
**Author:** Archie (Hermes agent)
**Date:** 2026-07-18
@@ -21,7 +21,7 @@ Every project can ship an `archie.yaml` that defines how archie-core should beha
### 1.1 Discovery
```
.archie.yaml (root of repo — highest precedence)
.archie.yaml (root of repo -- highest precedence)
archie.yaml (repo root)
.archie/archie.yaml (subdirectory, one level deep)
```
@@ -54,7 +54,7 @@ connection:
base: main
draft: false
# Skills — playbooks archie-core loads to know how to work
# Skills -- playbooks archie-core loads to know how to work
skills:
paths:
- .archie/skills/ # project-local skills
@@ -62,7 +62,7 @@ skills:
remotes:
- github.com/sam/archie-skills@v1 # shared skill library
# Sandbox — what's available in the container
# Sandbox -- what's available in the container
sandbox:
image: ghcr.io/sam/archie-sandbox:latest
tools:
@@ -75,7 +75,7 @@ sandbox:
env:
GOFLAGS: "-mod=readonly"
# Gates — archie-core must pass these before committing
# Gates -- archie-core must pass these before committing
gates:
test:
run: go test -race -count=1 ./...
@@ -89,7 +89,7 @@ gates:
run: task deadcode
optional: true
# Quality pipeline — which gates run when
# Quality pipeline -- which gates run when
quality:
pre_commit: [test, lint, format]
pre_push: [deadcode]
@@ -171,9 +171,9 @@ All five steps must exit 0. If `task deadcode` fails on unrelated packages,
scope it to only changed packages: `golangci-lint run --tests=false --enable-only=unused,staticcheck ./changed/pkg/...`
## Common failures
- `golangci-lint`: unused function — remove it or add `//nolint:unused` comment
- `go test -race`: data race — protect with mutex or channel
- `task deadcode`: pre-existing dead code in unrelated package — scope to changed packages
- `golangci-lint`: unused function -- remove it or add `//nolint:unused` comment
- `go test -race`: data race -- protect with mutex or channel
- `task deadcode`: pre-existing dead code in unrelated package -- scope to changed packages
```
### 2.3 Skill metadata (arcie-specific)
@@ -258,15 +258,15 @@ arcie-core can delegate implementation to different LLM engines. The workflow fi
```yaml
engines:
- type: claude # Claude Code CLI — full agent loop
- type: claude # Claude Code CLI -- full agent loop
model: sonnet
budget_usd: 5.00
- type: tau # Tau — Sam's native Go agent
- type: tau # Tau -- Sam's native Go agent
model: gpt-4o
budget_usd: 2.00
- type: codex # OpenAI Codex CLI
model: gpt-5.1-codex-max
- type: raw # Direct LLM — no agent loop, single prompt
- type: raw # Direct LLM -- no agent loop, single prompt
model: gpt-4o-mini
```
+5 -5
View File
@@ -1,4 +1,4 @@
# archie-core Workflows & Skills — Product Requirements Document
# archie-core Workflows & Skills -- Product Requirements Document
**Author:** Archie (Hermes agent)
**Date:** 2026-07-18
@@ -19,7 +19,7 @@ This PRD defines a workflow and skills system for archie-core. Workflow files de
A project declares its workflow in `archie.yaml` at the project root. archie-core discovers it the same way Task (Taskfile) and devcontainers do:
```
.archie.yaml (root of repo — highest precedence)
.archie.yaml (root of repo -- highest precedence)
archie.yaml (repo root)
.archie/archie.yaml (subdirectory, one level deep)
```
@@ -29,7 +29,7 @@ If no file is found, archie-core uses built-in defaults (read, write, bash).
### 1.2 Schema
```yaml
# archie.yaml — complete schema
# archie.yaml -- complete schema
version: "1"
# Project identity
@@ -74,7 +74,7 @@ sandbox:
GOFLAGS: "-mod=readonly"
CGO_ENABLED: "0"
# Gates — ordered checkpoints that must pass
# Gates -- ordered checkpoints that must pass
gates:
test:
run: go test -race -count=1 ./...
@@ -95,7 +95,7 @@ gates:
optional: true # non-blocking gate
description: "Dead code check (advisory)"
# Quality pipeline — ordered sequence of gate groups
# Quality pipeline -- ordered sequence of gate groups
quality:
pre_commit:
- test
+4 -4
View File
@@ -459,7 +459,7 @@
<div>
<p class="eyebrow"><span class="live-dot" aria-hidden="true"></span>Implemented topology · v2</p>
<h1>archie-core</h1>
<p class="subtitle">Single-daemon architecture: poll GitHub for labelled issues, route through label-driven workflows, run gated AI agent loops via ai-sdk, and deliver reviewed PRs — all in-process with SQLite crash recovery and an SSE observability dashboard.</p>
<p class="subtitle">Single-daemon architecture: poll GitHub for labelled issues, route through label-driven workflows, run gated AI agent loops via ai-sdk, and deliver reviewed PRs -- all in-process with SQLite crash recovery and an SSE observability dashboard.</p>
</div>
<div class="legend" aria-label="Component legend">
<span class="chip" style="--chip-color: var(--slate)">External</span>
@@ -761,17 +761,17 @@
<article class="insight" style="--accent: var(--green)">
<p class="insight-kicker">01 · Task flow</p>
<h2>Label-driven, in-process execution</h2>
<p>archied polls GitHub for issues matching the configured trigger (assignee, label, or either). Each issue becomes a SQLite-tracked task, claimed one at a time, and routed to a workflow by issue labels — no LLM involved in routing. All stages run sequentially inside the daemon process.</p>
<p>archied polls GitHub for issues matching the configured trigger (assignee, label, or either). Each issue becomes a SQLite-tracked task, claimed one at a time, and routed to a workflow by issue labels -- no LLM involved in routing. All stages run sequentially inside the daemon process.</p>
</article>
<article class="insight" style="--accent: var(--orange)">
<p class="insight-kicker">02 · Failure boundaries</p>
<h2>Environmental constraints, not prompt rules</h2>
<p>The quality gate, test-file protection (TDD fix stage), and diff-size cap are code enforcement — not "please don't do that" in the system prompt. Crashed daemons re-queue stale running tasks on startup. Parks are never silent: every parked task posts a comment with the reason and gate output.</p>
<p>The quality gate, test-file protection (TDD fix stage), and diff-size cap are code enforcement -- not "please don't do that" in the system prompt. Crashed daemons re-queue stale running tasks on startup. Parks are never silent: every parked task posts a comment with the reason and gate output.</p>
</article>
<article class="insight" style="--accent: var(--cyan)">
<p class="insight-kicker">03 · Design decisions</p>
<h2>Deterministic git, fresh worktrees</h2>
<p>The model never runs git — worktree operations (clone, branch, commit, push, diff, cleanup) are deterministic steps, not agent tools. Every task gets a fresh clone under <code>~/.local/share/archie/work/</code>. Tokens are tracked per task and emitted in observability events, but not budgeted beyond the agent loop's own limits.</p>
<p>The model never runs git -- worktree operations (clone, branch, commit, push, diff, cleanup) are deterministic steps, not agent tools. Every task gets a fresh clone under <code>~/.local/share/archie/work/</code>. Tokens are tracked per task and emitted in observability events, but not budgeted beyond the agent loop's own limits.</p>
</article>
</section>
+20 -20
View File
@@ -7,7 +7,7 @@ changing anything that contradicts a prior decision.
---
## 2026-07-23 — Forge-agnostic issue creation via CreateIssue
## 2026-07-23 -- Forge-agnostic issue creation via CreateIssue
**Decision**: Add `CreateIssue(ctx, owner, repo, title, body, labels)
(int, error)` to the `forge.Forge` interface. Every forge backend
@@ -21,11 +21,11 @@ calls one method regardless of the underlying ticketing system.
**Future**: A `beads` forge backend will implement `CreateIssue` by
calling `bd create`. This makes beads the internal/default issue tracker
while Gitea/GitHub are external forges. The agent doesn't know which
it's talking to — the daemon resolves the forge from repo config.
it's talking to -- the daemon resolves the forge from repo config.
---
## 2026-07-23 — Dolt and Beads for agent-native issue tracking
## 2026-07-23 -- Dolt and Beads for agent-native issue tracking
**Decision**: Install dolt (version-controlled SQL) and beads (`bd`,
a graph-based issue tracker for AI agents) as the foundation for
@@ -35,9 +35,9 @@ multi-repo scaling and multi-agent coordination.
class dependency tracking, JSON output for programmatic use, and hash-
based IDs that prevent merge conflicts in multi-agent workflows. It's
built on Dolt which gives cell-level merge, native branching, and
remote sync — the same primitives git gives code but applied to issues.
remote sync -- the same primitives git gives code but applied to issues.
**Context**: Gas Town (`~/gt/`) is cloned for reference — it implements
**Context**: Gas Town (`~/gt/`) is cloned for reference -- it implements
a multi-agent workspace on top of beads. The archie-core scaling
strategy will follow a similar model: a coordinator daemon with per-repo
agents, all sharing a beads-backed task graph.
@@ -47,7 +47,7 @@ in archie-core (`.beads/`). Six issues seeded for the scaling roadmap.
---
## 2026-07-23 — Token budgets must be generous, not predictive
## 2026-07-23 -- Token budgets must be generous, not predictive
**Decision**: Set `max_tokens` to 100,000,000 (100M). Do not attempt to
predict what a task needs without data. Lower limits later based on
@@ -61,7 +61,7 @@ lines) need proportionally more.
**Context**: The planner burned 357K tokens just to discover a fix
already existed. The builder hit 1M at step 25 of 90. Neither task was
unreasonable — they were just exploring a large codebase.
unreasonable -- they were just exploring a large codebase.
**Future**: Track actual token consumption per workflow/stage/repo. Use
that data to set informed limits. Build compaction or checkpointing so
@@ -69,7 +69,7 @@ a killed agent can resume rather than restart.
---
## 2026-07-23 — baseline-fix: auto-repair pre-existing gate failures
## 2026-07-23 -- baseline-fix: auto-repair pre-existing gate failures
**Decision**: When `StageBaselineGate` detects a red gate (gofumpt, go
vet, etc. failing on clean main), launch the builder to fix the
@@ -77,7 +77,7 @@ failures via TDD rather than parking. Only park if the builder cannot
fix them.
**Reasoning**: A red baseline means the repo was broken before archie
touched it. Parking creates an infinite loop — the next retry hits the
touched it. Parking creates an infinite loop -- the next retry hits the
same failure. The agent should fix pre-existing issues, not fail on them.
**Implementation**: `StageBaselineGate` now calls `tc.Agent.Run()` with
@@ -86,7 +86,7 @@ this required wiring `tc.Agent` (the runner) through the stage context.
---
## 2026-07-23 — No hardcoded MaxSteps in workflow stages
## 2026-07-23 -- No hardcoded MaxSteps in workflow stages
**Decision**: Remove all hardcoded `MaxSteps` values from workflow
stages. Every stage inherits from `[budgets].max_steps` in the config.
@@ -99,7 +99,7 @@ repos. The config should be the single source of truth.
---
## 2026-07-23 — No-op detection: close issues when build has 0 changes
## 2026-07-23 -- No-op detection: close issues when build has 0 changes
**Decision**: When the builder completes with `StatusPassed` and 0 file
changes, close the issue with a comment rather than parking on "worktree
@@ -120,7 +120,7 @@ sets `Outcome = Merged` to stop the workflow.
---
## 2026-07-23 — assignee trigger over label trigger
## 2026-07-23 -- assignee trigger over label trigger
**Decision**: Default to `trigger = "assignee"` instead of `trigger =
"label"`. The daemon only claims issues explicitly assigned to the bot
@@ -132,13 +132,13 @@ promiscuous for repos shared between humans and agents.
---
## 2026-07-23 — DeepSeek v4 Pro as primary model
## 2026-07-23 -- DeepSeek v4 Pro as primary model
**Decision**: Use `deepseek/deepseek-v4-pro` as the planner and builder
model. Qwythos-9B (local llama.cpp) is the fallback for offline/cheap
tasks.
**Reasoning**: Qwythos couldn't complete the plan stage for tau — 0
**Reasoning**: Qwythos couldn't complete the plan stage for tau -- 0
iterations, timed_out. DeepSeek completed it in 21 iterations. Large
repos need a larger model.
@@ -147,7 +147,7 @@ env var from Bitwarden Secrets Manager (bws).
---
## 2026-07-22 — v1.0.0 tagged
## 2026-07-22 -- v1.0.0 tagged
**Decision**: Tagged `v1.0.0` at commit incorporating the daemon/agent
split, NATS JetStream, Docker sandbox, Yaegi plugins, agentskills.io
@@ -155,7 +155,7 @@ skills, and Gitea forge support.
---
## 2026-07-22 — Docker Compose stack with NATS + containers
## 2026-07-22 -- Docker Compose stack with NATS + containers
**Decision**: The production deployment uses `docker-compose.yml` with
NATS, archied, and archie-agent containers. Config at `config.docker.toml`.
@@ -168,10 +168,10 @@ NATS, archied, and archie-agent containers. Config at `config.docker.toml`.
---
## 2026-07-22 — Worktree Prepare before Container Acquire
## 2026-07-22 -- Worktree Prepare before Container Acquire
**Decision**: Clone the worktree (`Trees.Prepare()`) before acquiring
a Docker container. Made `Prepare()` idempotent — skips if `.git`
a Docker container. Made `Prepare()` idempotent -- skips if `.git`
already exists.
**Reasoning**: Docker bind-mounts fail with "bind source path does not
@@ -181,12 +181,12 @@ didn't exist on the host.
---
## 2026-07-22 — Gofumpt and Go tools must be on PATH
## 2026-07-22 -- Gofumpt and Go tools must be on PATH
**Decision**: The daemon's `exec.Command` for gate checks inherits the
process PATH. `~/go/bin` (where `gofumpt`, `golangci-lint`, etc. live)
must be in the PATH before starting the daemon.
**Symptom**: `baseline red — gofumpt -w . fails` but manual run passes.
**Symptom**: `baseline red -- gofumpt -w . fails` but manual run passes.
Root cause: `which gofumpt` returns nothing because `~/go/bin` isn't on
PATH in Hermes sessions.
+4 -4
View File
@@ -2,7 +2,7 @@
**Author:** Archie (Hermes agent)
**Date:** 2026-07-21 (implementation status updated 2026-07-22)
**Status:** Final (substantially implemented — remaining aspirational items are pluggable storage backends and Layer 2 daemon plugin loader)
**Status:** Final (substantially implemented -- remaining aspirational items are pluggable storage backends and Layer 2 daemon plugin loader)
---
@@ -19,9 +19,9 @@ This document describes a target end state. The table below is the ground truth;
| `/data/` volume, `task.json` | **Partial** | `container.WriteTaskJSON()` writes task payload to the worktree before container acquire. The container pool bind-mounts the isolated task worktree at `/data/worktree`; configured repos also receive a persistent `/data/repo` Docker volume. Task payload travels over NATS as the primary channel; `/data/task.json` is a boot-time brief for the container. |
| `[containers]` config block | **Implemented** | `ContainerConfig` struct in config.go: enabled, image, max_concurrency, max_uptime, pull_policy. Validated on load. |
| Yaegi extensibility (gates, custom stages, skill scripts) | **Implemented** | Three surfaces: `.archie/gate.go`, `.archie/stages/*.go`, skill scripts via `run_go_script` tool. All in-process via Yaegi with generated symbol tables and panic recovery. Full detail in `docs/prds/yaegi-plugin-system.md`. |
| Layer 1: skill-bundled plugins | **Implemented** | `skill.DiscoverPlugins()` scans `.agents/skills/<name>/plugins/*.go`. `skill.Plugin.Run()` executes them via Yaegi. `skillbuild.BuildWorkflow()` constructs `workflow.Workflow` from plugin-defined stages. `TaskContext.SkillPlugins` makes them available during stage execution. `skillbuild.BuildRegistry()` replaces the hardcoded `workflow.Registry` with catalog-driven construction — skills define workflows, plugins define stages. |
| Layer 2: core daemon plugins | **Partial** | `internal/plugin/plugin.go`: `Plugin` interface (`Name()`, `Version()`), `Registry` type, `LoadDir()` using Yaegi to interpret `.go` files. No `~/.config/archie/plugins/` loader wired into `cmd/archied/main.go` yet — the interface and registry exist but are not connected to the daemon's startup. |
| Skills (agentskills.io spec) | **Implemented** | `internal/skill/skill.go`: parses SKILL.md YAML frontmatter, discovers skills from `.agents/skills/*/SKILL.md`, extracts body. Skills follow `archie-wf-*` naming convention. Progressive disclosure: `Catalog()` (Tier 1 — frontmatter-only scan, ~100 tokens per entry), `LoadBody()` (Tier 2 — full body on activation), `Discover()` (Tier 3 — full parse with plugins). `metadata.archie.workflow` declares skill→workflow affinity. `skill.SkillForWorkflow()` is catalog-driven, no hardcoded maps. `skillbuild.BuildRegistry()` constructs the daemon's workflow registry from the catalog. |
| Layer 1: skill-bundled plugins | **Implemented** | `skill.DiscoverPlugins()` scans `.agents/skills/<name>/plugins/*.go`. `skill.Plugin.Run()` executes them via Yaegi. `skillbuild.BuildWorkflow()` constructs `workflow.Workflow` from plugin-defined stages. `TaskContext.SkillPlugins` makes them available during stage execution. `skillbuild.BuildRegistry()` replaces the hardcoded `workflow.Registry` with catalog-driven construction -- skills define workflows, plugins define stages. |
| Layer 2: core daemon plugins | **Partial** | `internal/plugin/plugin.go`: `Plugin` interface (`Name()`, `Version()`), `Registry` type, `LoadDir()` using Yaegi to interpret `.go` files. No `~/.config/archie/plugins/` loader wired into `cmd/archied/main.go` yet -- the interface and registry exist but are not connected to the daemon's startup. |
| Skills (agentskills.io spec) | **Implemented** | `internal/skill/skill.go`: parses SKILL.md YAML frontmatter, discovers skills from `.agents/skills/*/SKILL.md`, extracts body. Skills follow `archie-wf-*` naming convention. Progressive disclosure: `Catalog()` (Tier 1 -- frontmatter-only scan, ~100 tokens per entry), `LoadBody()` (Tier 2 -- full body on activation), `Discover()` (Tier 3 -- full parse with plugins). `metadata.archie.workflow` declares skill→workflow affinity. `skill.SkillForWorkflow()` is catalog-driven, no hardcoded maps. `skillbuild.BuildRegistry()` constructs the daemon's workflow registry from the catalog. |
| Worktree/repo management | **Implemented** | Each issue keeps an isolated worktree. Repos with `persistent_storage = true` use a per-repo bare Git object cache to avoid repeated full network clones; caches and Archie-owned repo volumes expire via `containers.volume_ttl`. |
| Config schema | **Closer to sec.4** | `[agent]` block: mode (inprocess/subprocess/nats) + command + env. `[nats]` block: url + token_env. `[containers]` block: enabled, image, max_concurrency, max_uptime, volume_ttl, pull_policy. Per-repo `persistent_storage` is supported as a boolean Docker-volume/Git-cache opt-in. |
+9 -9
View File
@@ -36,9 +36,9 @@ Hermes gateway (`gateway/run.py`, GatewayRunner) manages full lifecycle: adapter
| Feature | archie-core status | Priority |
|---|---|---|
| Adapter lifecycle (connect/disconnect/reconnect) | None — 3-method Gateway interface | **P0** |
| MessageEvent data model (types, media, reply context) | None — 3-field Message struct | **P0** |
| SendResult with retry/error classification | None — fire-and-forget | **P1** |
| Adapter lifecycle (connect/disconnect/reconnect) | None -- 3-method Gateway interface | **P0** |
| MessageEvent data model (types, media, reply context) | None -- 3-field Message struct | **P0** |
| SendResult with retry/error classification | None -- fire-and-forget | **P1** |
| Session management (SessionSource + AsyncSessionStore) | None | **P0** |
| Platform config (Platform enum, PlatformConfig) | None | **P0** |
| Streaming delivery (token streaming with edit/draft) | None | **P1** |
@@ -54,7 +54,7 @@ Hermes has 30+ platform adapters: Telegram, Discord, Slack, Matrix, WhatsApp, Si
| Feature | archie-core status | Priority |
|---|---|---|
| BasePlatformAdapter ABC (20+ methods, capability flags) | None — 3-method Gateway interface | **P0** |
| BasePlatformAdapter ABC (20+ methods, capability flags) | None -- 3-method Gateway interface | **P0** |
| Platform adapter registry + plugin discovery | None | **P0** |
| Media handling (image/video/audio/document send) | None | **P1** |
| Typing indicators | None | **P2** |
@@ -110,7 +110,7 @@ Hermes has: 60+ CLI commands, TUI interface, command registry with plugin contri
| Feature | archie-core status | Priority |
|---|---|---|
| Interactive CLI with command registry | None — 4 flags | **P1** |
| Interactive CLI with command registry | None -- 4 flags | **P1** |
| Config subcommands (get/set/unset/edit/wizard) | None | **P1** |
| .env file support | None | **P2** |
| Self-update mechanism | None | **P2** |
@@ -171,10 +171,10 @@ Hermes has: FastAPI web server (Vite/React frontend), OpenAI-compatible API serv
## Total: ~60 feature gaps across 11 subsystems
**P0 (must-have for baseline parity):** 7 items — adapter lifecycle, message model, session management, platform config, tool registry, MCP client, memory provider ABC
**P0 (must-have for baseline parity):** 7 items -- adapter lifecycle, message model, session management, platform config, tool registry, MCP client, memory provider ABC
**P1 (near-term):** 13 items — send result, streaming, dedup, media handling, guardrails, progressive disclosure, tool persistence, session hooks, history store, pairing/auth, CLI, config subcommands, profiles, readiness
**P1 (near-term):** 13 items -- send result, streaming, dedup, media handling, guardrails, progressive disclosure, tool persistence, session hooks, history store, pairing/auth, CLI, config subcommands, profiles, readiness
**P2 (medium-term):** 22 items — interactive UX, subagents, browser/search/file tools, compression, session splitting, slash access, secrets CLI, cron, dashboard, API server, delivery, drain, scale-to-zero
**P2 (medium-term):** 22 items -- interactive UX, subagents, browser/search/file tools, compression, session splitting, slash access, secrets CLI, cron, dashboard, API server, delivery, drain, scale-to-zero
**P3 (future):** 3 items — billing, OAuth, desktop app
**P3 (future):** 3 items -- billing, OAuth, desktop app
+2 -2
View File
@@ -161,7 +161,7 @@ pieces where isolation adds cost without benefit:
Decision rationale: per-identity goroutines guarantee failure isolation (one
identity's forge outage cannot block another's poll tick), each identity
gets its own forge rate-limit domain, and the existing `Daemon` struct maps
cleanly — each goroutine holds a thin `Identity` value (forge client + config
cleanly -- each goroutine holds a thin `Identity` value (forge client + config
subset + worktree manager + NATS subject prefix) and dispatches tasks with
an `identity_name` column on the task row. The shared NATS connection
multiplexes subjects by identity prefix; the shared store already handles
@@ -170,7 +170,7 @@ the identity name so agent containers (which consume from NATS) route
responses back to the correct daemon identity.
This design resolves the open question in section 4 of the original PRD
draft (per-identity goroutine vs single loop iterating identities — the
draft (per-identity goroutine vs single loop iterating identities -- the
former, for failure isolation).
## 5. Priority / phasing
+11 -11
View File
@@ -1,4 +1,4 @@
# archie-core TypeScript Plugin Engine — PRD
# archie-core TypeScript Plugin Engine -- PRD
**Author:** Archie (Hermes agent)
**Date:** 2026-07-21
@@ -8,7 +8,7 @@
## Summary
A TypeScript-based plugin engine that lets repositories ship interpreted, dynamically-loaded workflow extensions. Plugins are `.ts` files placed in `.archie/workflows/`. archie-core discovers them on its next poll cycle, transpiles them to JavaScript via esbuild, and executes them in an embedded [goja](https://github.com/dop251/goja) runtime — a pure-Go ECMAScript interpreter with zero CGO dependencies.
A TypeScript-based plugin engine that lets repositories ship interpreted, dynamically-loaded workflow extensions. Plugins are `.ts` files placed in `.archie/workflows/`. archie-core discovers them on its next poll cycle, transpiles them to JavaScript via esbuild, and executes them in an embedded [goja](https://github.com/dop251/goja) runtime -- a pure-Go ECMAScript interpreter with zero CGO dependencies.
---
@@ -20,7 +20,7 @@ TypeScript is the most widely understood language among developers writing autom
Having a TypeScript-native plugin engine means:
- Plugin authors get familiar syntax, type safety, and IDE support
- No separate toolchain — just `.ts` files in a folder
- No separate toolchain -- just `.ts` files in a folder
- Skills, gates, and workflow stages share the same language
### Why goja
@@ -29,12 +29,12 @@ Having a TypeScript-native plugin engine means:
|---|---|
| V8 CGO bindings | Requires CGO, ~50MB static libraries, platform-specific builds |
| QuickJS CGO | Requires CGO, smaller than V8 but still a C dependency |
| QJS (Wazero) | Pure Go WASM, but sandboxed — can't expose Go functions efficiently |
| QJS (Wazero) | Pure Go WASM, but sandboxed -- can't expose Go functions efficiently |
| Ramune | Heavy dependency, bundles an entire TypeScript 7 compiler |
| Node.js subprocess | Process overhead per execution, IPC serialization cost |
goja is a pure-Go ECMAScript 5.1+ interpreter at ~20k lines. It:
- Has **zero CGO** — cross-compiles everywhere Go does
- Has **zero CGO** -- cross-compiles everywhere Go does
- Passes nearly all TC39 Test262 tests for ES5.1 + significant ES6 coverage
- Can run Babel and the TypeScript compiler itself (proven capability)
- Provides direct Go↔JS interop via `Set()`/`Get()`/`Runtime.RunString()`
@@ -114,7 +114,7 @@ export function check(ctx: GateContext): Finding[] {
if (line.includes("panic(")) {
findings.push({
level: "error",
message: "new panic() call — use error returns instead"
message: "new panic() call -- use error returns instead"
});
}
}
@@ -128,7 +128,7 @@ export function check(ctx: GateContext): Finding[] {
findings.push({
level: "warn",
file: file,
message: "time.Sleep in non-test code — use time.Ticker instead"
message: "time.Sleep in non-test code -- use time.Ticker instead"
});
}
}
@@ -217,7 +217,7 @@ All file operations are **jailed to the worktree**. `archie.readFile("/etc/passw
### Reload cycle
Plugins are loaded fresh on every poll cycle — archie-core already fresh-clones per task. No hot-reload complexity, no cache invalidation. The worktree is the source of truth.
Plugins are loaded fresh on every poll cycle -- archie-core already fresh-clones per task. No hot-reload complexity, no cache invalidation. The worktree is the source of truth.
For the rare case where a plugin errors at parse/transpile time, archie-core comments on the issue with the diagnostic and parks the task. The plugin author fixes the `.ts` file and requeues.
@@ -294,7 +294,7 @@ func (l *Loader) LoadPlugins(worktreeDir string) ([]Plugin, error) {
dir := filepath.Join(worktreeDir, ".archie", "workflows")
entries, err := os.ReadDir(dir)
if os.IsNotExist(err) {
return nil, nil // no plugins — not an error
return nil, nil // no plugins -- not an error
}
if err != nil {
return nil, err
@@ -388,7 +388,7 @@ goja natively supports ES5.1 with significant ES6 features. Modern syntax like `
| Generators | ❌ not supported |
| `Proxy` | ❌ not supported |
For gate scripts, this is fine — gates are synchronous by nature. If async is genuinely needed later, the Bun backend (via `tsgo`) is the escape hatch.
For gate scripts, this is fine -- gates are synchronous by nature. If async is genuinely needed later, the Bun backend (via `tsgo`) is the escape hatch.
### Performance
@@ -417,7 +417,7 @@ Plugins can't `import` from npm or other files. They're self-contained modules.
| **Plugin folder** | `.archie/workflows/` | `.archie/workflows/` |
| **Best for** | Custom stages needing Go's stdlib, tight daemon integration | Custom gates and scripts where author familiarity matters |
**Recommendation: support both.** They solve different problems. Yaegi for repo owners who want full Go power in their custom stages. goja for repo owners who want to write gates and scripts in TypeScript. Both load from `.archie/workflows/` — archie-core discovers which engine to use by file extension (`.go` → Yaegi, `.ts` → goja+esbuild).
**Recommendation: support both.** They solve different problems. Yaegi for repo owners who want full Go power in their custom stages. goja for repo owners who want to write gates and scripts in TypeScript. Both load from `.archie/workflows/` -- archie-core discovers which engine to use by file extension (`.go` → Yaegi, `.ts` → goja+esbuild).
---
+24 -24
View File
@@ -1,4 +1,4 @@
# archie-core Yaegi Plugin System — PRD
# archie-core Yaegi Plugin System -- PRD
**Author:** Archie (Hermes agent)
**Date:** 2026-07-21
@@ -23,11 +23,11 @@ Embed the [Yaegi](https://github.com/traefik/yaegi) Go interpreter to let archie
- "All public functions in `pkg/api/` must be documented"
- "No `time.Sleep` in production code paths"
These are rules that need to read the diff, parse Go ASTs, or walk the worktree — things shell scripts can do but shouldn't have to.
These are rules that need to read the diff, parse Go ASTs, or walk the worktree -- things shell scripts can do but shouldn't have to.
### Why not shell scripts?
Shell scripts for gates are fine until they're not. They can't import the archie-core types, can't use the Go parser, and are a second language to maintain alongside the daemon. Yaegi runs Go — the same language as the daemon, the same language as the repos archie-core works on.
Shell scripts for gates are fine until they're not. They can't import the archie-core types, can't use the Go parser, and are a second language to maintain alongside the daemon. Yaegi runs Go -- the same language as the daemon, the same language as the repos archie-core works on.
### Why not Go's native `plugin` package?
@@ -37,7 +37,7 @@ Go's `plugin` package (`.so` files) requires:
- No unload
- Painful distribution
Yaegi interprets `.go` source files directly — no compilation step, portable everywhere, loads from filesystem paths.
Yaegi interprets `.go` source files directly -- no compilation step, portable everywhere, loads from filesystem paths.
### Production precedent
@@ -52,7 +52,7 @@ Yaegi interprets `.go` source files directly — no compilation step, portable e
| Surface | Location | When loaded | What it does |
|---|---|---|---|
| **Custom gate functions** | `.archie/gate.go` | During the gate stage (after shell commands) | Returns `[]Finding` — each finding has severity, message, file, line |
| **Custom gate functions** | `.archie/gate.go` | During the gate stage (after shell commands) | Returns `[]Finding` -- each finding has severity, message, file, line |
| **Custom workflow stages** | `.archie/stages/<name>.go` | When the workflow references the stage name | Returns a `workflow.Stage` implementation |
| **Skill scripts** | `.archie/skills/<skill>/scripts/*.go` | When the parent skill is activated | Called by the skill's instructions |
@@ -61,7 +61,7 @@ Yaegi interprets `.go` source files directly — no compilation step, portable e
The most important extension surface. After the shell-based gate passes, archie-core loads and evaluates `.archie/gate.go` in the worktree directory. The script exposes a `Check` function:
```go
// .archie/gate.go — per-repo gate rules interpreted at runtime
// .archie/gate.go -- per-repo gate rules interpreted at runtime
package gate
import (
@@ -104,7 +104,7 @@ func Check(ctx GateContext) []Finding {
if strings.Contains(line, "panic(") {
findings = append(findings, Finding{
Level: "error",
Message: "new panic() call — use error returns instead",
Message: "new panic() call -- use error returns instead",
})
}
}
@@ -124,7 +124,7 @@ func Check(ctx GateContext) []Finding {
findings = append(findings, Finding{
Level: "warn",
File: f,
Message: "time.Sleep in non-test code — use time.Ticker or context.WithTimeout instead",
Message: "time.Sleep in non-test code -- use time.Ticker or context.WithTimeout instead",
})
}
}
@@ -205,7 +205,7 @@ Via `i.Use()`, the daemon pre-loads symbols that interpreted code can import:
| `archie-core/internal/gate` | `GateContext`, `Finding`, `Block` |
| `stdlib` | Full Go standard library (stdlib.Symbols) |
Generated with `yaegi extract` — same approach Traefik and Vikunja use. A `//go:generate yaegi extract ...` line in the source triggers symbol table generation during `go generate`.
Generated with `yaegi extract` -- same approach Traefik and Vikunja use. A `//go:generate yaegi extract ...` line in the source triggers symbol table generation during `go generate`.
---
@@ -213,10 +213,10 @@ Generated with `yaegi extract` — same approach Traefik and Vikunja use. A `//g
From Yaegi's own docs:
- **No assembly files** (`.s` not supported)
- **No CGo** (can't call C code — the daemon is pure Go, so this doesn't matter)
- **No compiler/linker directives** (no `//go:embed`, etc. — fine for gate scripts)
- **Interfaces from pre-compiled code can't be added dynamically** — the daemon must pre-compile wrapper types for any interface interpreted code needs to implement
- **Slower than compiled code** — gate scripts run once per commit, not in hot paths; negligible impact
- **No CGo** (can't call C code -- the daemon is pure Go, so this doesn't matter)
- **No compiler/linker directives** (no `//go:embed`, etc. -- fine for gate scripts)
- **Interfaces from pre-compiled code can't be added dynamically** -- the daemon must pre-compile wrapper types for any interface interpreted code needs to implement
- **Slower than compiled code** -- gate scripts run once per commit, not in hot paths; negligible impact
The Vikunja PR documents a specific Yaegi quirk: **typed factory functions required.** You can't do `v.Interface().(MyInterface)` on a value returned from interpreted code. Each interface needs its own factory:
@@ -229,31 +229,31 @@ func NewReportable() Reportable { return &MyGate{} }
## Implementation phases
### Phase 1: Gate functions — implemented
### Phase 1: Gate functions -- implemented
- `yaegi` added as a dependency
- Symbol table for `GateContext`, `Finding` generated via `yaegi extract` into `internal/gate/gateextract` (a separate package from `internal/gate` itself, avoiding the self-import cycle extracting a package's own symbols creates)
- `internal/gate/gateeval.Evaluate`: loads `.archie/gate.go` from the worktree, interprets it, calls `Check()`; panics are recovered
- Wired in as `workflow.StageYaegiGate`, run after the final commit in both the `implement` and `tdd` workflows
- Error findings park the task; warn findings are logged only
### Phase 2: Custom stages — implemented
### Phase 2: Custom stages -- implemented
- Symbol table for `workflow.Stage`/`TaskContext`/`Outcome` generated into `internal/workflow/wfextract`
- `internal/workflow/wfeval.Discover` scans `.archie/stages/*.go` in filename order and calls each file's exported `Stage()` function
- `TaskContext.CustomStages` is an injected `func(dir string) ([]Stage, error)` — the composition root (`cmd/archied`) wires it to `wfeval.Discover`, keeping `internal/workflow` decoupled from its own generated symbol table
- `TaskContext.CustomStages` is an injected `func(dir string) ([]Stage, error)` -- the composition root (`cmd/archied`) wires it to `wfeval.Discover`, keeping `internal/workflow` decoupled from its own generated symbol table
- `workflow.StageRepoStages` runs discovered stages in order right after the worktree is prepared, in both `implement` and `tdd`
- Simplification vs. the original sketch: stages are auto-discovered and always run (like `.archie/gate.go`) rather than referenced by name from `config.toml` — the workflow engine has no data-driven stage graph today, so wiring arbitrary named stages into arbitrary positions would need a larger config-driven rework. Auto-run-in-order covers the PRD's actual use case (a repo-defined pre-flight/setup hook) without it.
- Simplification vs. the original sketch: stages are auto-discovered and always run (like `.archie/gate.go`) rather than referenced by name from `config.toml` -- the workflow engine has no data-driven stage graph today, so wiring arbitrary named stages into arbitrary positions would need a larger config-driven rework. Auto-run-in-order covers the PRD's actual use case (a repo-defined pre-flight/setup hook) without it.
### Phase 3: Skill scripts — implemented
### Phase 3: Skill scripts -- implemented
- `internal/skillscript.Run` interprets a `.go` file via `i.EvalPath`, which (like `go run`) evaluates and calls its `main()`; stdout/stderr are captured via `interp.Options`
- Uses `stdlib.Symbols` + `stdlib/unrestricted.Symbols` (not just `stdlib`) — `os/exec` lives in the unrestricted set, and the PRD's own example script shells out via `os/exec`
- No archie-core-specific symbol table needed here — skill scripts only touch the Go standard library
- Uses `stdlib.Symbols` + `stdlib/unrestricted.Symbols` (not just `stdlib`) -- `os/exec` lives in the unrestricted set, and the PRD's own example script shells out via `os/exec`
- No archie-core-specific symbol table needed here -- skill scripts only touch the Go standard library
- Exposed to the agent loop as a new `run_go_script` tool (`internal/agentexec/inprocess.go`), available in every agent stage; path is validated to stay inside the workspace
- This is how "the skill's instructions reference a script" cashes out concretely: the agent calls `run_go_script` with the path instead of needing a Go toolchain in the sandbox
### Phase 4: Hot reload — not needed, by construction
- All three loaders (`gate.Evaluate`, `wfeval.Discover`, `skillscript.Run`) read their `.go` source from disk on every call — no in-memory cache exists anywhere in the implementation
### Phase 4: Hot reload -- not needed, by construction
- All three loaders (`gate.Evaluate`, `wfeval.Discover`, `skillscript.Run`) read their `.go` source from disk on every call -- no in-memory cache exists anywhere in the implementation
- Every task additionally gets a fresh `git clone` (`worktree.Manager.Prepare` removes and re-clones the worktree directory per task)
- Consequently every stage already re-reads `.archie/gate.go`, `.archie/stages/*.go`, and skill scripts fresh, every run — there is no stale state a file watcher would ever need to invalidate
- Consequently every stage already re-reads `.archie/gate.go`, `.archie/stages/*.go`, and skill scripts fresh, every run -- there is no stale state a file watcher would ever need to invalidate
- A file-watching daemon-runtime reload mechanism would add machinery with nothing to do given this architecture; revisit only if the daemon starts reusing long-lived worktrees across tasks
---
@@ -262,6 +262,6 @@ func NewReportable() Reportable { return &MyGate{} }
1. **Symbol table generation:** Run `yaegi extract` as a `go generate` step, or generate on daemon startup?
2. **Error handling:** If the interpreted gate panics or times out, park the task? Or fall back to shell-only gate?
3. **Budget:** Interpreted gate scripts run in the gate stage — should they have their own timeout/step budget?
3. **Budget:** Interpreted gate scripts run in the gate stage -- should they have their own timeout/step budget?
4. **Template system:** Should archie-core ship with common gate templates (e.g. `go: no panic, no Sleep, no hardcoded paths`)?
5. **Remote gates:** Could `.archie/gate.go` be pulled from a shared remote registry, like skills?
+7 -7
View File
@@ -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.")
}
}
+1 -1
View File
@@ -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 {
+2 -2
View File
@@ -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)
}
+5 -5
View File
@@ -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),
+2 -2
View File
@@ -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)
+8 -8
View File
@@ -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":
+4 -4
View File
@@ -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)
+1 -1
View File
@@ -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"}},
+13 -13
View File
@@ -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)
+13 -13
View File
@@ -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, "")
+5 -5
View File
@@ -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()
+6 -6
View File
@@ -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
View File
@@ -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
+3 -3
View File
@@ -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)
+3 -3
View File
@@ -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 -1
View File
@@ -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
+6 -6
View File
@@ -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)
+2 -2
View File
@@ -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{})
}
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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))
+1 -1
View File
@@ -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
+8 -8
View File
@@ -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
}
+5 -5
View File
@@ -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:
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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 {
+4 -4
View File
@@ -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)
}
+2 -2
View File
@@ -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
+2 -2
View File
@@ -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 {
+3 -3
View File
@@ -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 {
+2 -2
View File
@@ -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 {
+1 -1
View File
@@ -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
+8 -8
View File
@@ -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{})
+7 -7
View File
@@ -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()
+2 -2
View File
@@ -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
+12 -12
View File
@@ -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 {
+5 -5
View File
@@ -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")
}
+2 -2
View File
@@ -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.
}
}
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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)
}
+3 -3
View File
@@ -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.
+3 -3
View File
@@ -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})
+3 -3
View File
@@ -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")
+15 -15
View File
@@ -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
@@ -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 {
+6 -6
View File
@@ -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")
}
}
+1 -1
View File
@@ -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.
+3 -3
View File
@@ -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 {
+5 -5
View File
@@ -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
}
+4 -4
View File
@@ -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)
+1 -1
View File
@@ -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
View File
@@ -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
}
+5 -5
View File
@@ -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)
+3 -3
View File
@@ -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, `
+1 -1
View File
@@ -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 ──────────────────────────────────────────────
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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"`
+2 -2
View File
@@ -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)
}
+8 -8
View File
@@ -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
+11 -11
View File
@@ -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 {
+1 -1
View File
@@ -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.
+4 -4
View File
@@ -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
+7 -7
View File
@@ -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])
}
}
+10 -5
View File
@@ -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.
+24 -24
View File
@@ -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")
}
}
+2 -2
View File
@@ -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 -1
View File
@@ -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
+3 -3
View File
@@ -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")
}
}
+4 -4
View File
@@ -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 {
+3 -3
View File
@@ -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.
+3 -3
View File
@@ -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
+9 -9
View File
@@ -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,
+1 -1
View File
@@ -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
}
+6 -6
View File
@@ -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")
}
}
+4 -4
View File
@@ -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 {
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more