From f6d51416f06c9d4491ef102f93eff65fb6156219 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 26 Jul 2026 09:53:33 +1000 Subject: [PATCH] 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). --- .agents/skills/archie-wf-frontend/SKILL.md | 6 +-- .agents/skills/archie-wf-go-gate/SKILL.md | 10 ++-- .agents/skills/archie-wf-node/SKILL.md | 8 +-- .agents/skills/archie-wf-python/SKILL.md | 18 +++---- .agents/skills/archie-wf-tdd/SKILL.md | 6 +-- .gitea/workflows/deploy.yml | 2 +- AGENTS.md | 6 +-- ARCHITECTURE.md | 38 ++++++------- CLAUDE.md | 4 +- cmd/archie-agent/main.go | 6 +-- cmd/archie-agent/main_test.go | 4 +- cmd/archie-agent/taskrun.go | 6 +-- cmd/archie-agent/taskrun_test.go | 2 +- cmd/archied/main.go | 8 +-- config.docker.toml | 4 +- config.example.toml | 2 +- docs/DESIGN.md | 8 +-- docs/archie-core-skills-prd-v2.md | 24 ++++----- docs/archie-core-skills-prd.md | 10 ++-- docs/archie-core-v2-architecture.html | 8 +-- docs/decisions.md | 40 +++++++------- docs/prds/archie-core-v2-architecture.md | 8 +-- docs/prds/hermes-gap-analysis.md | 18 +++---- docs/prds/multi-agent-collaboration.md | 4 +- docs/prds/typescript-plugin-engine.md | 22 ++++---- docs/prds/yaegi-plugin-system.md | 48 ++++++++--------- internal/agentexec/nats_test.go | 14 ++--- internal/agentexec/providers.go | 2 +- internal/agentexec/skill_test.go | 4 +- internal/channels/telegram/telegram.go | 10 ++-- internal/channels/telegram/telegram_test.go | 4 +- internal/config/config.go | 16 +++--- internal/config/config_test.go | 8 +-- internal/config/ecosystem.go | 2 +- internal/config/feature_config.go | 26 ++++----- internal/config/feature_config_test.go | 26 ++++----- internal/container/pool.go | 10 ++-- internal/container/pool_test.go | 12 ++--- internal/daemon/daemon.go | 40 +++++++------- internal/daemon/daemon_test.go | 6 +-- internal/events/events.go | 6 +-- internal/forge/forge.go | 2 +- internal/forge/github.go | 12 ++--- internal/forgerpc/forgerpc.go | 4 +- internal/forgerpc/forgerpc_test.go | 2 +- internal/gate/gateeval/yaegi.go | 8 +-- internal/gate/gateeval/yaegi_test.go | 2 +- internal/gateway/adapter.go | 16 +++--- internal/gateway/gateway.go | 10 ++-- internal/gateway/messageevent_test.go | 2 +- internal/gateway/messagetype.go | 2 +- internal/gateway/session_store_test.go | 8 +-- internal/gateway/tasks.go | 4 +- internal/memory/builtin/provider.go | 4 +- internal/memory/builtin/provider_test.go | 6 +-- internal/memory/builtin/store.go | 4 +- internal/memory/lifecycle.go | 2 +- internal/memory/manager.go | 16 +++--- internal/memory/manager_test.go | 14 ++--- internal/memory/provider.go | 4 +- internal/memory/scrubber/scrubber.go | 24 ++++----- internal/memory/scrubber/scrubber_test.go | 10 ++-- internal/memory/sync.go | 4 +- internal/nats/client_test.go | 2 +- internal/nats/subjects.go | 2 +- internal/natsrpc/natsrpc.go | 6 +-- internal/nell/adapter.go | 6 +-- internal/plugin/plugin.go | 6 +-- internal/plugin/plugin_test.go | 30 +++++------ ...amcharles93-archie-core-internal-plugin.go | 2 +- internal/skill/catalog_test.go | 12 ++--- internal/skill/frontmatter_test.go | 2 +- internal/skill/plugin.go | 6 +-- internal/skill/skill.go | 10 ++-- internal/skillscript/yaegi.go | 8 +-- internal/skillscript/yaegi_test.go | 2 +- internal/storage/storage.go | 36 ++++++------- internal/storage/storage_test.go | 10 ++-- internal/store/events.go | 6 +-- internal/store/interface.go | 2 +- internal/storerpc/storerpc.go | 2 +- internal/taskrun/taskrun.go | 2 +- internal/tools/mcp/framing.go | 4 +- internal/tools/mcp/transport.go | 16 +++--- internal/tools/mcp/transport_test.go | 22 ++++---- internal/tools/mcp/types.go | 2 +- internal/tools/registry.go | 8 +-- internal/tools/registry_test.go | 14 ++--- internal/tools/toolentry.go | 15 ++++-- internal/tools/toolentry_test.go | 48 ++++++++--------- internal/webui/index.html | 4 +- internal/webui/webui.go | 2 +- internal/webui/webui_test.go | 6 +-- internal/workflow/agent.go | 8 +-- internal/workflow/agent_test.go | 6 +-- internal/workflow/feasibility.go | 6 +-- internal/workflow/implement.go | 18 +++---- internal/workflow/implement_test.go | 2 +- internal/workflow/plugin_test.go | 12 ++--- internal/workflow/skillbuild/skillbuild.go | 8 +-- .../workflow/skillbuild/skillbuild_test.go | 54 +++++++++---------- internal/workflow/steps.go | 20 +++---- internal/workflow/steps_test.go | 4 +- internal/workflow/tdd.go | 18 +++---- internal/workflow/wfeval/yaegi.go | 2 +- internal/workflow/workflow.go | 16 +++--- internal/worktree/worktree.go | 6 +-- internal/worktree/worktree_test.go | 8 +-- internal/worktreerpc/worktreerpc.go | 6 +-- internal/worktreerpc/worktreerpc_test.go | 4 +- internal/yaegiutil/yaegiutil.go | 10 ++-- task.json | 2 +- 112 files changed, 587 insertions(+), 582 deletions(-) diff --git a/.agents/skills/archie-wf-frontend/SKILL.md b/.agents/skills/archie-wf-frontend/SKILL.md index 3b93b7195..8aea520ff 100644 --- a/.agents/skills/archie-wf-frontend/SKILL.md +++ b/.agents/skills/archie-wf-frontend/SKILL.md @@ -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 diff --git a/.agents/skills/archie-wf-go-gate/SKILL.md b/.agents/skills/archie-wf-go-gate/SKILL.md index 154c0272b..8897b279b 100644 --- a/.agents/skills/archie-wf-go-gate/SKILL.md +++ b/.agents/skills/archie-wf-go-gate/SKILL.md @@ -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. diff --git a/.agents/skills/archie-wf-node/SKILL.md b/.agents/skills/archie-wf-node/SKILL.md index 4074d647e..0c80c93c4 100644 --- a/.agents/skills/archie-wf-node/SKILL.md +++ b/.agents/skills/archie-wf-node/SKILL.md @@ -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 diff --git a/.agents/skills/archie-wf-python/SKILL.md b/.agents/skills/archie-wf-python/SKILL.md index c4bcda440..018f0984e 100644 --- a/.agents/skills/archie-wf-python/SKILL.md +++ b/.agents/skills/archie-wf-python/SKILL.md @@ -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 diff --git a/.agents/skills/archie-wf-tdd/SKILL.md b/.agents/skills/archie-wf-tdd/SKILL.md index e0729df9b..56a21d374 100644 --- a/.agents/skills/archie-wf-tdd/SKILL.md +++ b/.agents/skills/archie-wf-tdd/SKILL.md @@ -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. diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index fd47ede44..30e06de81 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index d6d964451..3d9204ea4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 # 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. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 73af9250e..626c07f54 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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/-/issue-/ ``` -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/`) diff --git a/CLAUDE.md b/CLAUDE.md index db14bd118..d7e74a14c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,9 +18,9 @@ bd close # 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. diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go index 89fc59cfe..015ac0fa7 100644 --- a/cmd/archie-agent/main.go +++ b/cmd/archie-agent/main.go @@ -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 { diff --git a/cmd/archie-agent/main_test.go b/cmd/archie-agent/main_test.go index 9a19bf8f0..d3c7f8cd6 100644 --- a/cmd/archie-agent/main_test.go +++ b/cmd/archie-agent/main_test.go @@ -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 { diff --git a/cmd/archie-agent/taskrun.go b/cmd/archie-agent/taskrun.go index 136992bd9..043decd0c 100644 --- a/cmd/archie-agent/taskrun.go +++ b/cmd/archie-agent/taskrun.go @@ -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 diff --git a/cmd/archie-agent/taskrun_test.go b/cmd/archie-agent/taskrun_test.go index e22b42a3d..c20a7b371 100644 --- a/cmd/archie-agent/taskrun_test.go +++ b/cmd/archie-agent/taskrun_test.go @@ -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 { diff --git a/cmd/archied/main.go b/cmd/archied/main.go index ddd3352d4..8f71fe5a1 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -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) diff --git a/config.docker.toml b/config.docker.toml index 4cd5abb13..3cbacb6b7 100644 --- a/config.docker.toml +++ b/config.docker.toml @@ -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. diff --git a/config.example.toml b/config.example.toml index 7d50e1b11..45a627e2b 100644 --- a/config.example.toml +++ b/config.example.toml @@ -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) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index e22443653..74ba8dc4e 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -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 diff --git a/docs/archie-core-skills-prd-v2.md b/docs/archie-core-skills-prd-v2.md index bab28005c..31526ed69 100644 --- a/docs/archie-core-skills-prd-v2.md +++ b/docs/archie-core-skills-prd-v2.md @@ -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 ``` diff --git a/docs/archie-core-skills-prd.md b/docs/archie-core-skills-prd.md index 28bd52c91..41b96e007 100644 --- a/docs/archie-core-skills-prd.md +++ b/docs/archie-core-skills-prd.md @@ -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 diff --git a/docs/archie-core-v2-architecture.html b/docs/archie-core-v2-architecture.html index fedb1b887..23e393018 100644 --- a/docs/archie-core-v2-architecture.html +++ b/docs/archie-core-v2-architecture.html @@ -459,7 +459,7 @@

Implemented topology · v2

archie-core

-

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.

+

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.

External @@ -761,17 +761,17 @@

01 · Task flow

Label-driven, in-process execution

-

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.

+

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.

02 · Failure boundaries

Environmental constraints, not prompt rules

-

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.

+

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.

03 · Design decisions

Deterministic git, fresh worktrees

-

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 ~/.local/share/archie/work/. Tokens are tracked per task and emitted in observability events, but not budgeted beyond the agent loop's own limits.

+

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 ~/.local/share/archie/work/. Tokens are tracked per task and emitted in observability events, but not budgeted beyond the agent loop's own limits.

diff --git a/docs/decisions.md b/docs/decisions.md index a31165e49..f237ce2e0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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. diff --git a/docs/prds/archie-core-v2-architecture.md b/docs/prds/archie-core-v2-architecture.md index addeac3ce..e7807ac2a 100644 --- a/docs/prds/archie-core-v2-architecture.md +++ b/docs/prds/archie-core-v2-architecture.md @@ -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//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//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. | diff --git a/docs/prds/hermes-gap-analysis.md b/docs/prds/hermes-gap-analysis.md index 53e704f4c..090a3a45e 100644 --- a/docs/prds/hermes-gap-analysis.md +++ b/docs/prds/hermes-gap-analysis.md @@ -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 diff --git a/docs/prds/multi-agent-collaboration.md b/docs/prds/multi-agent-collaboration.md index 574e59742..a8688674b 100644 --- a/docs/prds/multi-agent-collaboration.md +++ b/docs/prds/multi-agent-collaboration.md @@ -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 diff --git a/docs/prds/typescript-plugin-engine.md b/docs/prds/typescript-plugin-engine.md index 9eb81be53..f2b9282e9 100644 --- a/docs/prds/typescript-plugin-engine.md +++ b/docs/prds/typescript-plugin-engine.md @@ -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). --- diff --git a/docs/prds/yaegi-plugin-system.md b/docs/prds/yaegi-plugin-system.md index a144751ce..da9c4a191 100644 --- a/docs/prds/yaegi-plugin-system.md +++ b/docs/prds/yaegi-plugin-system.md @@ -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/.go` | When the workflow references the stage name | Returns a `workflow.Stage` implementation | | **Skill scripts** | `.archie/skills//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? diff --git a/internal/agentexec/nats_test.go b/internal/agentexec/nats_test.go index 8a2f88a8f..8d34eb5b6 100644 --- a/internal/agentexec/nats_test.go +++ b/internal/agentexec/nats_test.go @@ -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..system and // are never forwarded to humans. Response messages go to // archie.agent..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.") } } diff --git a/internal/agentexec/providers.go b/internal/agentexec/providers.go index b8b80707a..b5310202a 100644 --- a/internal/agentexec/providers.go +++ b/internal/agentexec/providers.go @@ -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 { diff --git a/internal/agentexec/skill_test.go b/internal/agentexec/skill_test.go index 7d2c00fc3..ec8ec6775 100644 --- a/internal/agentexec/skill_test.go +++ b/internal/agentexec/skill_test.go @@ -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) } diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index e4ae80e29..9c1f88079 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -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, "🤖 Archie Gateway\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), diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index c63788b31..567f0908c 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -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) diff --git a/internal/config/config.go b/internal/config/config.go index 4c9e0c36c..b2feeb3a5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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": diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c3d43dc65..4ecc145fd 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -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) diff --git a/internal/config/ecosystem.go b/internal/config/ecosystem.go index 1ba212fce..81241897d 100644 --- a/internal/config/ecosystem.go +++ b/internal/config/ecosystem.go @@ -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"}}, diff --git a/internal/config/feature_config.go b/internal/config/feature_config.go index 555c56ad9..779942267 100644 --- a/internal/config/feature_config.go +++ b/internal/config/feature_config.go @@ -11,7 +11,7 @@ import ( ) // knownFeatureNames is the set of recognised config..yaml feature files. -// Any config..yaml file whose is not in this set is rejected — +// Any config..yaml file whose 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) diff --git a/internal/config/feature_config_test.go b/internal/config/feature_config_test.go index 40ea7ea4b..fc47b2e8b 100644 --- a/internal/config/feature_config_test.go +++ b/internal/config/feature_config_test.go @@ -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 applies files from // 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, "") diff --git a/internal/container/pool.go b/internal/container/pool.go index fe4582dbc..f9895ff47 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -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() diff --git a/internal/container/pool_test.go b/internal/container/pool_test.go index ea47a6d40..520378c93 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -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 /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") } diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index d0ae5986a..cbb0bc130 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -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. 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 diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 178d1575e..c845ce0fd 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -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) diff --git a/internal/events/events.go b/internal/events/events.go index c54a66487..3d1e3c4b1 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -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 diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 19fec9f1a..87da7b8a9 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -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 diff --git a/internal/forge/github.go b/internal/forge/github.go index f7462f1cb..530eb7103 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -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) diff --git a/internal/forgerpc/forgerpc.go b/internal/forgerpc/forgerpc.go index 489465537..e80aaa681 100644 --- a/internal/forgerpc/forgerpc.go +++ b/internal/forgerpc/forgerpc.go @@ -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{}) } diff --git a/internal/forgerpc/forgerpc_test.go b/internal/forgerpc/forgerpc_test.go index 66aa71a75..9576d7b42 100644 --- a/internal/forgerpc/forgerpc_test.go +++ b/internal/forgerpc/forgerpc_test.go @@ -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 diff --git a/internal/gate/gateeval/yaegi.go b/internal/gate/gateeval/yaegi.go index 181328871..14f1c5375 100644 --- a/internal/gate/gateeval/yaegi.go +++ b/internal/gate/gateeval/yaegi.go @@ -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)) diff --git a/internal/gate/gateeval/yaegi_test.go b/internal/gate/gateeval/yaegi_test.go index 39f464b02..558cffca5 100644 --- a/internal/gate/gateeval/yaegi_test.go +++ b/internal/gate/gateeval/yaegi_test.go @@ -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 diff --git a/internal/gateway/adapter.go b/internal/gateway/adapter.go index 6413027e5..25ce6b66b 100644 --- a/internal/gateway/adapter.go +++ b/internal/gateway/adapter.go @@ -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 } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b56b05a52..bb834c124 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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: diff --git a/internal/gateway/messageevent_test.go b/internal/gateway/messageevent_test.go index ea0edf87b..9d7c1ba2b 100644 --- a/internal/gateway/messageevent_test.go +++ b/internal/gateway/messageevent_test.go @@ -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, diff --git a/internal/gateway/messagetype.go b/internal/gateway/messagetype.go index 047a1549c..fcbd95165 100644 --- a/internal/gateway/messagetype.go +++ b/internal/gateway/messagetype.go @@ -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 { diff --git a/internal/gateway/session_store_test.go b/internal/gateway/session_store_test.go index e49440591..3b1d9f1a8 100644 --- a/internal/gateway/session_store_test.go +++ b/internal/gateway/session_store_test.go @@ -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) } diff --git a/internal/gateway/tasks.go b/internal/gateway/tasks.go index e4e78c90f..7a422a5c9 100644 --- a/internal/gateway/tasks.go +++ b/internal/gateway/tasks.go @@ -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 diff --git a/internal/memory/builtin/provider.go b/internal/memory/builtin/provider.go index 37f718558..7398ec6a5 100644 --- a/internal/memory/builtin/provider.go +++ b/internal/memory/builtin/provider.go @@ -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 { diff --git a/internal/memory/builtin/provider_test.go b/internal/memory/builtin/provider_test.go index 5fd60a98b..f450a109d 100644 --- a/internal/memory/builtin/provider_test.go +++ b/internal/memory/builtin/provider_test.go @@ -300,7 +300,7 @@ func TestProvider_FrozenSnapshot_NotUpdatedOnWrite(t *testing.T) { t.Fatalf("snapshot should be wrapped in 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 { diff --git a/internal/memory/builtin/store.go b/internal/memory/builtin/store.go index ee663bae9..ed6920899 100644 --- a/internal/memory/builtin/store.go +++ b/internal/memory/builtin/store.go @@ -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 { diff --git a/internal/memory/lifecycle.go b/internal/memory/lifecycle.go index 8edb88ae5..8ea360248 100644 --- a/internal/memory/lifecycle.go +++ b/internal/memory/lifecycle.go @@ -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 diff --git a/internal/memory/manager.go b/internal/memory/manager.go index 06d8c0a72..e474b4c68 100644 --- a/internal/memory/manager.go +++ b/internal/memory/manager.go @@ -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{}) diff --git a/internal/memory/manager_test.go b/internal/memory/manager_test.go index a6e66511c..48e1c2520 100644 --- a/internal/memory/manager_test.go +++ b/internal/memory/manager_test.go @@ -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() diff --git a/internal/memory/provider.go b/internal/memory/provider.go index 1c81c161a..0801998a0 100644 --- a/internal/memory/provider.go +++ b/internal/memory/provider.go @@ -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 diff --git a/internal/memory/scrubber/scrubber.go b/internal/memory/scrubber/scrubber.go index 0ac057802..39509f08b 100644 --- a/internal/memory/scrubber/scrubber.go +++ b/internal/memory/scrubber/scrubber.go @@ -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 — write everything before it, then enter memory block. + // Found -- 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 — write the '<' and continue after it. + // Not -- 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 — write everything. + // Not a prefix of -- 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 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 (which would close the block) or // (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 { diff --git a/internal/memory/scrubber/scrubber_test.go b/internal/memory/scrubber/scrubber_test.go index 0451300cc..4d48ecdf6 100644 --- a/internal/memory/scrubber/scrubber_test.go +++ b/internal/memory/scrubber/scrubber_test.go @@ -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 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 more") if result != "text 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 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: "content more", - // "" is not "" — it doesn't close the block. + // "" is not "" -- it doesn't close the block. // Everything inside the memory block is stripped until the real // 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") } diff --git a/internal/memory/sync.go b/internal/memory/sync.go index 7515dfa0b..fa0d0dfc7 100644 --- a/internal/memory/sync.go +++ b/internal/memory/sync.go @@ -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. } } diff --git a/internal/nats/client_test.go b/internal/nats/client_test.go index 53806ff1a..46069ead1 100644 --- a/internal/nats/client_test.go +++ b/internal/nats/client_test.go @@ -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) diff --git a/internal/nats/subjects.go b/internal/nats/subjects.go index 9106231cd..5add4933f 100644 --- a/internal/nats/subjects.go +++ b/internal/nats/subjects.go @@ -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) } diff --git a/internal/natsrpc/natsrpc.go b/internal/natsrpc/natsrpc.go index a2e3861c7..9735c3201 100644 --- a/internal/natsrpc/natsrpc.go +++ b/internal/natsrpc/natsrpc.go @@ -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. diff --git a/internal/nell/adapter.go b/internal/nell/adapter.go index 6d3128da1..3f5180caf 100644 --- a/internal/nell/adapter.go +++ b/internal/nell/adapter.go @@ -4,7 +4,7 @@ // "::". 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}) diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go index b53cbee2d..300633bae 100644 --- a/internal/plugin/plugin.go +++ b/internal/plugin/plugin.go @@ -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") diff --git a/internal/plugin/plugin_test.go b/internal/plugin/plugin_test.go index d03a764ea..a72bc29e9 100644 --- a/internal/plugin/plugin_test.go +++ b/internal/plugin/plugin_test.go @@ -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 diff --git a/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go b/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go index cf697a86e..efe560b31 100644 --- a/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go +++ b/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go @@ -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 { diff --git a/internal/skill/catalog_test.go b/internal/skill/catalog_test.go index 289779596..54a85e8e2 100644 --- a/internal/skill/catalog_test.go +++ b/internal/skill/catalog_test.go @@ -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") } } diff --git a/internal/skill/frontmatter_test.go b/internal/skill/frontmatter_test.go index 5ce318e43..2c7fb4dea 100644 --- a/internal/skill/frontmatter_test.go +++ b/internal/skill/frontmatter_test.go @@ -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. diff --git a/internal/skill/plugin.go b/internal/skill/plugin.go index c8061d667..b64ed5072 100644 --- a/internal/skill/plugin.go +++ b/internal/skill/plugin.go @@ -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//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 { diff --git a/internal/skill/skill.go b/internal/skill/skill.go index 7fa77b0e1..2fad425db 100644 --- a/internal/skill/skill.go +++ b/internal/skill/skill.go @@ -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 } diff --git a/internal/skillscript/yaegi.go b/internal/skillscript/yaegi.go index 78687a95c..60631990d 100644 --- a/internal/skillscript/yaegi.go +++ b/internal/skillscript/yaegi.go @@ -1,7 +1,7 @@ // Package skillscript runs skill-bundled Go scripts (.agents/skills//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) diff --git a/internal/skillscript/yaegi_test.go b/internal/skillscript/yaegi_test.go index 8f35ac29b..399fa5678 100644 --- a/internal/skillscript/yaegi_test.go +++ b/internal/skillscript/yaegi_test.go @@ -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() {} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 1cc37812d..51b9e7a11 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -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 } diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index 6b980f60a..7c7201db0 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -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) diff --git a/internal/store/events.go b/internal/store/events.go index c6437ec9b..a9739849b 100644 --- a/internal/store/events.go +++ b/internal/store/events.go @@ -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, ` diff --git a/internal/store/interface.go b/internal/store/interface.go index 3ba90d73e..7228ce1ac 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -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 ────────────────────────────────────────────── diff --git a/internal/storerpc/storerpc.go b/internal/storerpc/storerpc.go index 678117717..73ce328a8 100644 --- a/internal/storerpc/storerpc.go +++ b/internal/storerpc/storerpc.go @@ -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 diff --git a/internal/taskrun/taskrun.go b/internal/taskrun/taskrun.go index 16b08bbee..2aa5fe0c5 100644 --- a/internal/taskrun/taskrun.go +++ b/internal/taskrun/taskrun.go @@ -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"` diff --git a/internal/tools/mcp/framing.go b/internal/tools/mcp/framing.go index d5c9a01d1..17d1fc14d 100644 --- a/internal/tools/mcp/framing.go +++ b/internal/tools/mcp/framing.go @@ -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) } diff --git a/internal/tools/mcp/transport.go b/internal/tools/mcp/transport.go index b642d8f01..e173a8c94 100644 --- a/internal/tools/mcp/transport.go +++ b/internal/tools/mcp/transport.go @@ -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 diff --git a/internal/tools/mcp/transport_test.go b/internal/tools/mcp/transport_test.go index 45c8b9322..c719cbd04 100644 --- a/internal/tools/mcp/transport_test.go +++ b/internal/tools/mcp/transport_test.go @@ -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 { diff --git a/internal/tools/mcp/types.go b/internal/tools/mcp/types.go index 142c6a7c9..530231de4 100644 --- a/internal/tools/mcp/types.go +++ b/internal/tools/mcp/types.go @@ -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. diff --git a/internal/tools/registry.go b/internal/tools/registry.go index 4e28bcd14..8051040fa 100644 --- a/internal/tools/registry.go +++ b/internal/tools/registry.go @@ -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 diff --git a/internal/tools/registry_test.go b/internal/tools/registry_test.go index f22b865d8..7f6aa50cb 100644 --- a/internal/tools/registry_test.go +++ b/internal/tools/registry_test.go @@ -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]) } } diff --git a/internal/tools/toolentry.go b/internal/tools/toolentry.go index 2272f0c5a..42e53a083 100644 --- a/internal/tools/toolentry.go +++ b/internal/tools/toolentry.go @@ -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. diff --git a/internal/tools/toolentry_test.go b/internal/tools/toolentry_test.go index 1f7c6c1ff..ebf5591e7 100644 --- a/internal/tools/toolentry_test.go +++ b/internal/tools/toolentry_test.go @@ -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") } } diff --git a/internal/webui/index.html b/internal/webui/index.html index 0103100da..a20893262 100644 --- a/internal/webui/index.html +++ b/internal/webui/index.html @@ -80,7 +80,7 @@

archie

- autonomous project agent — connecting… + autonomous project agent -- connecting…
@@ -99,7 +99,7 @@
-

Task timeline —

+

Task timeline --

timekindstagedetail
diff --git a/internal/webui/webui.go b/internal/webui/webui.go index e069349b7..4b97cf629 100644 --- a/internal/webui/webui.go +++ b/internal/webui/webui.go @@ -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 diff --git a/internal/webui/webui_test.go b/internal/webui/webui_test.go index f63c59117..6f0b46935 100644 --- a/internal/webui/webui_test.go +++ b/internal/webui/webui_test.go @@ -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") } } diff --git a/internal/workflow/agent.go b/internal/workflow/agent.go index 9676d6a88..7fa1d2e27 100644 --- a/internal/workflow/agent.go +++ b/internal/workflow/agent.go @@ -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 { diff --git a/internal/workflow/agent_test.go b/internal/workflow/agent_test.go index d57970f9a..1e3fb2390 100644 --- a/internal/workflow/agent_test.go +++ b/internal/workflow/agent_test.go @@ -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. diff --git a/internal/workflow/feasibility.go b/internal/workflow/feasibility.go index 5271ccd61..38a60ad4a 100644 --- a/internal/workflow/feasibility.go +++ b/internal/workflow/feasibility.go @@ -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 diff --git a/internal/workflow/implement.go b/internal/workflow/implement.go index 9d04948f6..3b2411ce3 100644 --- a/internal/workflow/implement.go +++ b/internal/workflow/implement.go @@ -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 { "\n# %s\n\n%s\n\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"+ "\n# %s\n\n%s\n\n\n\n%s\n\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, diff --git a/internal/workflow/implement_test.go b/internal/workflow/implement_test.go index 9b2067eb6..45b99ce1e 100644 --- a/internal/workflow/implement_test.go +++ b/internal/workflow/implement_test.go @@ -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 } diff --git a/internal/workflow/plugin_test.go b/internal/workflow/plugin_test.go index 14a289d36..be3f29624 100644 --- a/internal/workflow/plugin_test.go +++ b/internal/workflow/plugin_test.go @@ -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") } } diff --git a/internal/workflow/skillbuild/skillbuild.go b/internal/workflow/skillbuild/skillbuild.go index 6ad5c6e15..40e85a743 100644 --- a/internal/workflow/skillbuild/skillbuild.go +++ b/internal/workflow/skillbuild/skillbuild.go @@ -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 { diff --git a/internal/workflow/skillbuild/skillbuild_test.go b/internal/workflow/skillbuild/skillbuild_test.go index dbe546ee5..927e1032c 100644 --- a/internal/workflow/skillbuild/skillbuild_test.go +++ b/internal/workflow/skillbuild/skillbuild_test.go @@ -88,7 +88,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { t.Errorf("stage[1].Name = %q, want world", wf.Stages[1].Name) } - // Run the workflow — stages must execute in order. + // Run the workflow -- stages must execute in order. tc := &workflow.TaskContext{BuildSummary: ""} for _, s := range wf.Stages { if err := s.Run(context.Background(), tc); err != nil { @@ -101,7 +101,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { } func TestBuildWorkflowMissingSkillReturnsEmptyWorkflow(t *testing.T) { - // Missing plugins directory is not an error — same pattern as + // Missing plugins directory is not an error -- same pattern as // wfeval.Discover. Returns a Workflow with no stages. entry := SkillWorkflow{Workflow: "nonexistent", Dir: "nonexistent"} wf, err := BuildWorkflow(t.TempDir(), entry) @@ -124,7 +124,7 @@ func TestBuildRegistryFromSkillCatalog(t *testing.T) { dir := t.TempDir() - // Skill 1: archie-wf-greet — plugin-defined workflow. + // Skill 1: archie-wf-greet -- plugin-defined workflow. greetDir := filepath.Join(dir, ".agents", "skills", "archie-wf-greet", "plugins") if err := os.MkdirAll(greetDir, 0o755); err != nil { t.Fatal(err) @@ -158,7 +158,7 @@ Greet the user. t.Fatal(err) } - // Skill 2: archie-wf-implement — overrides the built-in implement workflow. + // Skill 2: archie-wf-implement -- overrides the built-in implement workflow. implDir := filepath.Join(dir, ".agents", "skills", "archie-wf-custom-impl", "plugins") if err := os.MkdirAll(implDir, 0o755); err != nil { t.Fatal(err) @@ -207,9 +207,9 @@ Custom implementation workflow. t.Errorf("Workflow.Name = %q, want greet", wf.Name) } if len(wf.Stages) == 0 { - t.Error("workflow 'greet' has no stages — plugin stages not loaded") + t.Error("workflow 'greet' has no stages -- plugin stages not loaded") } - // Run it — stages must execute. + // Run it -- stages must execute. tc := &workflow.TaskContext{BuildSummary: ""} for _, s := range wf.Stages { if err := s.Run(context.Background(), tc); err != nil { @@ -237,7 +237,7 @@ Custom implementation workflow. } } if tc.BuildSummary != "custom-impl-ran" { - t.Errorf("BuildSummary = %q, want 'custom-impl-ran' — skill override did not take effect", tc.BuildSummary) + t.Errorf("BuildSummary = %q, want 'custom-impl-ran' -- skill override did not take effect", tc.BuildSummary) } }) @@ -317,7 +317,7 @@ Utility content. // There is no workflow called "utils" because the skill didn't declare one. if _, ok := reg["utils"]; ok { t.Error("BuildRegistry registered 'utils' as a workflow, but the skill " + - "did not declare metadata.archie.workflow — only skills that declare " + + "did not declare metadata.archie.workflow -- only skills that declare " + "a workflow should produce registry entries") } @@ -400,7 +400,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { // Worktree workflow added. wf, ok := aug["custom"] if !ok { - t.Fatal("'custom' workflow not found in augmented registry — worktree skill was not discovered") + t.Fatal("'custom' workflow not found in augmented registry -- worktree skill was not discovered") } if wf.Name != "custom" { t.Errorf("Workflow.Name = %q, want custom", wf.Name) @@ -485,7 +485,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { t.Errorf("stage[0].Name = %q, want 'repo-plan' from worktree override", wf.Stages[0].Name) } - // Run it — must use worktree version. + // Run it -- must use worktree version. tc := &workflow.TaskContext{BuildSummary: ""} if err := wf.Stages[0].Run(context.Background(), tc); err != nil { t.Fatal(err) @@ -496,7 +496,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { } func TestAugmentRegistryDoesNotModifyBase(t *testing.T) { - // AugmentRegistry returns a NEW registry — the caller's base must + // AugmentRegistry returns a NEW registry -- the caller's base must // not be mutated. base := workflow.Registry{"keep": {Name: "keep"}} worktree := t.TempDir() @@ -514,7 +514,7 @@ func TestAugmentRegistryDoesNotModifyBase(t *testing.T) { // Mutating augmented must not affect base. aug["keep"] = workflow.Workflow{Name: "modified"} if base["keep"].Name != "keep" { - t.Error("AugmentRegistry mutated the base registry — must return a copy") + t.Error("AugmentRegistry mutated the base registry -- must return a copy") } } @@ -530,7 +530,7 @@ func TestAugmentRegistryNonexistentWorktreeReturnsBase(t *testing.T) { } func TestAugmentRegistryWorktreeWithNoSkillsReturnsBase(t *testing.T) { - // A worktree without .agents/skills/ must not error — returns + // A worktree without .agents/skills/ must not error -- returns // a copy of the base unchanged. worktree := t.TempDir() base := workflow.Registry{"default": {Name: "default"}} @@ -545,7 +545,7 @@ func TestAugmentRegistryWorktreeWithNoSkillsReturnsBase(t *testing.T) { func TestAugmentRegistryWorktreeSkillWithNoStagesDoesNotOverride(t *testing.T) { // A skill that declares a workflow but has no plugins must not - // override the base entry — it would produce an empty workflow. + // override the base entry -- it would produce an empty workflow. worktree := t.TempDir() skillDir := filepath.Join(worktree, ".agents", "skills", "archie-wf-empty") if err := os.MkdirAll(skillDir, 0o755); err != nil { @@ -574,7 +574,7 @@ No plugins here. wf := aug["implement"] if len(wf.Stages) == 0 { - t.Error("worktree skill with no stages overrode base — must keep base when skill is empty") + t.Error("worktree skill with no stages overrode base -- must keep base when skill is empty") } if wf.Stages[0].Name != "builtin" { t.Error("base stage was replaced by empty worktree skill") @@ -622,7 +622,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { base := workflow.Registry{"default": {Name: "default"}} - // Run 10 concurrent augmentations — none should panic or corrupt state. + // Run 10 concurrent augmentations -- none should panic or corrupt state. errs := make(chan error, 10) for range 10 { go func() { @@ -651,7 +651,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { } func TestAugmentRegistryBrokenSkillMDIsSkipped(t *testing.T) { - // A SKILL.md with invalid YAML must not crash augmentation — the + // A SKILL.md with invalid YAML must not crash augmentation -- the // skill is simply skipped (skill.Catalog skips parse errors). worktree := t.TempDir() skillDir := filepath.Join(worktree, ".agents", "skills", "archie-wf-broken") @@ -680,7 +680,7 @@ func TestAugmentRegistryWorktreeWithNoSkillsDir(t *testing.T) { // A worktree that exists but has no .agents/ directory at all // must not error. worktree := t.TempDir() - // Don't create .agents/skills/ — just a bare worktree. + // Don't create .agents/skills/ -- just a bare worktree. if err := os.WriteFile(filepath.Join(worktree, "README.md"), []byte(`# repo`), 0o644); err != nil { t.Fatal(err) } @@ -696,14 +696,14 @@ func TestAugmentRegistryWorktreeWithNoSkillsDir(t *testing.T) { } func TestAugmentRegistryNilBaseReturnsEmpty(t *testing.T) { - // A nil base registry must be treated as empty — not panic. + // A nil base registry must be treated as empty -- not panic. worktree := t.TempDir() aug, err := AugmentRegistry(worktree, nil) if err != nil { t.Fatal("AugmentRegistry errored with nil base:", err) } if aug == nil { - t.Error("AugmentRegistry returned nil for nil base — want empty registry") + t.Error("AugmentRegistry returned nil for nil base -- want empty registry") } if len(aug) != 0 { t.Errorf("got %d entries with nil base and no skills, want 0", len(aug)) @@ -754,7 +754,7 @@ func TestBuildWorkflowSkipsBrokenPlugin(t *testing.T) { t.Fatal(err) } - // First plugin — valid. + // First plugin -- valid. if err := os.WriteFile(filepath.Join(pluginsDir, "01-setup.go"), []byte(`package main import ( @@ -772,14 +772,14 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { t.Fatal(err) } - // Second plugin — BROKEN (syntax error). + // Second plugin -- BROKEN (syntax error). if err := os.WriteFile(filepath.Join(pluginsDir, "02-broken.go"), []byte(`package main this is %% NOT VALID GO @@@@ `), 0o644); err != nil { t.Fatal(err) } - // Third plugin — valid. + // Third plugin -- valid. if err := os.WriteFile(filepath.Join(pluginsDir, "03-teardown.go"), []byte(`package main import ( @@ -1244,7 +1244,7 @@ func Stage() (string, func(context.Context, *workflow.TaskContext) error) { func TestBuildRegistrySkipsBrokenSkill(t *testing.T) { // R2: a skill with broken plugins must not prevent other skills - // from registering — and must not block daemon startup. + // from registering -- and must not block daemon startup. dir := t.TempDir() @@ -1281,7 +1281,7 @@ Good. t.Fatal(err) } - // Skill 2: broken plugins — ALL plugins are broken. + // Skill 2: broken plugins -- ALL plugins are broken. badDir := filepath.Join(dir, ".agents", "skills", "archie-wf-bad", "plugins") if err := os.MkdirAll(badDir, 0o755); err != nil { t.Fatal(err) @@ -1311,11 +1311,11 @@ Broken. // Good workflow must still be registered. if _, ok := reg["good"]; !ok { - t.Error("'good' workflow missing — broken skill blocked registry build") + t.Error("'good' workflow missing -- broken skill blocked registry build") } // Bad workflow must not be registered (it had no valid stages). if _, ok := reg["bad"]; ok { - // It might fall back to built-in "bad" — that's fine. + // It might fall back to built-in "bad" -- that's fine. // But it should NOT be the empty workflow from the broken skill. t.Log("'bad' workflow present (may be built-in fallback)") } diff --git a/internal/workflow/steps.go b/internal/workflow/steps.go index 5cd0d6c4c..5167bfc53 100644 --- a/internal/workflow/steps.go +++ b/internal/workflow/steps.go @@ -31,7 +31,7 @@ func StagePrepareWorktree() Stage { }} } -// StageCommit commits everything in the worktree without pushing — +// StageCommit commits everything in the worktree without pushing -- // used mid-workflow so a PR tells its story in multiple commits (TDD: // failing tests first, fix second). An empty tree parks. func StageCommit(name string, message func(*TaskContext) string) Stage { @@ -49,19 +49,19 @@ func StageCommit(name string, message func(*TaskContext) string) Stage { // StageCommitPush commits everything in the worktree and pushes the // branch. When the builder completed with no changes (BuildNoChanges is -// set), the issue is already resolved — close it with a comment instead +// set), the issue is already resolved -- close it with a comment instead // of erroring on an empty tree. func StageCommitPush(message func(*TaskContext) string) Stage { return Stage{Name: "commit-push", Run: func(ctx context.Context, tc *TaskContext) error { if tc.BuildNoChanges { - body := fmt.Sprintf("**archie closed this issue — no changes required.**\n\n%s", tc.BuildSummary) + body := fmt.Sprintf("**archie closed this issue -- no changes required.**\n\n%s", tc.BuildSummary) if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil { tc.Log.Warn("no-op close comment failed", "err", err) } if err := tc.Forge.CloseIssue(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, ""); err != nil { return err } - tc.Outcome = Outcome{Status: store.StatusMerged, Detail: "closed — no changes required"} + tc.Outcome = Outcome{Status: store.StatusMerged, Detail: "closed -- no changes required"} return nil } commit := StageCommit("commit-push", message) @@ -72,7 +72,7 @@ func StageCommitPush(message func(*TaskContext) string) Stage { }} } -// StageDiffCap parks tasks whose diff exceeds the configured line cap — +// StageDiffCap parks tasks whose diff exceeds the configured line cap -- // oversized changes need human pre-approval, not an auto-opened PR. func StageDiffCap() Stage { return Stage{Name: "diff-cap", Run: func(ctx context.Context, tc *TaskContext) error { @@ -86,7 +86,7 @@ func StageDiffCap() Stage { if lines > tc.Cfg.DiffCapLines { tc.Outcome = Outcome{ Status: store.StatusParked, - Detail: fmt.Sprintf("diff is %d changed lines (cap %d) — split the issue or approve manually", lines, tc.Cfg.DiffCapLines), + Detail: fmt.Sprintf("diff is %d changed lines (cap %d) -- split the issue or approve manually", lines, tc.Cfg.DiffCapLines), } } return nil @@ -95,7 +95,7 @@ func StageDiffCap() Stage { // StageRepoStages runs every custom stage the repo defines under // .archie/stages/*.go (Yaegi-interpreted via TaskContext.CustomStages), -// in the order the loader returns them — a no-op when no loader is wired +// in the order the loader returns them -- a no-op when no loader is wired // up or the repo defines none. A custom stage that sets tc.Outcome ends // the workflow there, same as any built-in stage. func StageRepoStages() Stage { @@ -120,7 +120,7 @@ func StageRepoStages() Stage { }} } -// StageYaegiGate evaluates the repo's optional .archie/gate.go — a +// StageYaegiGate evaluates the repo's optional .archie/gate.go -- a // Yaegi-interpreted Go file inspecting the committed diff for // project-specific rules shell gate commands can't express (AST checks, // diff scanning). A missing script is a no-op. Error-level findings @@ -170,7 +170,7 @@ func StageYaegiGate() Stage { // OpenPR opens the task's pull request, records its number, and sets // the terminal pr_open outcome. Stages that need to act after the PR // exists (e.g. posting evidence comments) call this and then do so in -// the same stage — the engine stops at the first stage with an outcome. +// the same stage -- the engine stops at the first stage with an outcome. func OpenPR(ctx context.Context, tc *TaskContext, body string) error { t := tc.Task title := fmt.Sprintf("%s (archie)", t.Title) @@ -204,7 +204,7 @@ func Bootstrap() Workflow { if err := os.MkdirAll(dir, 0o755); err != nil { return err } - content := fmt.Sprintf("# archie bootstrap\n\nIssue: #%d — %s\nTime: %s\n\nThis file proves the archie pipeline (poll → worktree → push → PR) works for this repository.\n", + content := fmt.Sprintf("# archie bootstrap\n\nIssue: #%d -- %s\nTime: %s\n\nThis file proves the archie pipeline (poll → worktree → push → PR) works for this repository.\n", tc.Task.IssueNumber, tc.Task.Title, time.Now().UTC().Format(time.RFC3339)) return os.WriteFile(filepath.Join(dir, "bootstrap.md"), []byte(content), 0o644) }}, diff --git a/internal/workflow/steps_test.go b/internal/workflow/steps_test.go index 366405de7..439eadf74 100644 --- a/internal/workflow/steps_test.go +++ b/internal/workflow/steps_test.go @@ -27,8 +27,8 @@ func runGit(t *testing.T, dir string, args ...string) { // gitRepoWithOriginRef creates a repo with a base commit, then labels // that commit "origin/" (a plain local branch standing in for a -// remote-tracking ref) so Manager.Diff/ChangedFiles — which always diff -// against "origin/" — resolve without a real clone/push round trip. +// remote-tracking ref) so Manager.Diff/ChangedFiles -- which always diff +// against "origin/" -- resolve without a real clone/push round trip. func gitRepoWithOriginRef(t *testing.T, base string) string { t.Helper() dir := t.TempDir() diff --git a/internal/workflow/tdd.go b/internal/workflow/tdd.go index 534784cb4..60ebaf98c 100644 --- a/internal/workflow/tdd.go +++ b/internal/workflow/tdd.go @@ -12,8 +12,8 @@ import ( // TDD is the bugfix workflow: prove the bug with failing tests before // fixing it. The repro stage's gate INVERTS the test command -// (ExpectFailure) — the run cannot proceed until the new tests fail for -// the right reason — and the fix stage restores the repo's full gate. +// (ExpectFailure) -- the run cannot proceed until the new tests fail for +// the right reason -- and the fix stage restores the repo's full gate. // Routed via the "bug" label. func TDD() Workflow { return Workflow{ @@ -49,7 +49,7 @@ func TDD() Workflow { Role: "builder", // The inverted gate: code-quality commands must still // pass, but the test command (last in repo.Gate) MUST - // fail — proof the repro captures the bug. + // fail -- proof the repro captures the bug. Gate: func(tc *TaskContext) agentexec.Gate { return tddReproGate(tc.Repo, tc.Cfg.Budgets) }, @@ -67,18 +67,18 @@ func TDD() Workflow { }, }.Stage(), - // Capture the failing test run — the proof the repro + // Capture the failing test run -- the proof the repro // reproduces the bug, posted on the PR later. {Name: "capture-proof", Run: func(ctx context.Context, tc *TaskContext) error { argv := testCommandArgv(tc.Repo) if len(argv) == 0 { - return fmt.Errorf("tdd: repo %s has no gate configured — cannot capture repro proof (add at least one [[repos.gate]] command, with the test runner last)", tc.Repo.FullName()) + return fmt.Errorf("tdd: repo %s has no gate configured -- cannot capture repro proof (add at least one [[repos.gate]] command, with the test runner last)", tc.Repo.FullName()) } cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) cmd.Dir = tc.Dir out, err := cmd.CombinedOutput() if err == nil { - return fmt.Errorf("repro tests unexpectedly pass after commit — the bug is not captured") + return fmt.Errorf("repro tests unexpectedly pass after commit -- the bug is not captured") } tc.ReproProof = clip(string(out), 4000) return nil @@ -95,7 +95,7 @@ func TDD() Workflow { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }, // Environmental, not advisory: the fix stage cannot touch - // test files at all — the committed repro is the spec. + // test files at all -- the committed repro is the spec. ProtectGlobs: func(tc *TaskContext) []string { glob := tc.Repo.ResolvedTestGlob() if glob == "" { @@ -104,7 +104,7 @@ func TDD() Workflow { return []string{glob} }, ExtraRules: "The repro tests written in the previous stage are the bug's specification. " + - "Test files are write-protected in this stage — make them pass by fixing the code they exercise.", + "Test files are write-protected in this stage -- make them pass by fixing the code they exercise.", Mission: func(tc *TaskContext) string { return fmt.Sprintf( "Fix the bug in the repository %s. Failing repro tests are already committed; make them pass.\n\n"+ @@ -149,7 +149,7 @@ func TDD() Workflow { // tddReproGate builds the inverted gate for the repro-tests stage: // every command from repo.Gate runs normally except the last one (the -// test runner, by convention), which gets ExpectFailure — the repro +// test runner, by convention), which gets ExpectFailure -- the repro // must fail the tests to prove the bug exists. func tddReproGate(repo config.Repo, budgets config.Budgets) agentexec.Gate { if len(repo.Gate) == 0 { diff --git a/internal/workflow/wfeval/yaegi.go b/internal/workflow/wfeval/yaegi.go index cd58d3464..ddb72fb5b 100644 --- a/internal/workflow/wfeval/yaegi.go +++ b/internal/workflow/wfeval/yaegi.go @@ -24,7 +24,7 @@ const stagesDir = ".archie/stages" // Discover loads every .archie/stages/*.go file in dir and returns the // workflow.Stage each exports, in filename order. A missing directory is -// not an error — it returns (nil, nil), meaning no custom stages are +// not an error -- it returns (nil, nil), meaning no custom stages are // configured for this repo. func Discover(dir string) ([]workflow.Stage, error) { entries, err := os.ReadDir(filepath.Join(dir, stagesDir)) diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go index 8f0ec3e15..3000f6575 100644 --- a/internal/workflow/workflow.go +++ b/internal/workflow/workflow.go @@ -1,7 +1,7 @@ // Package workflow is archied's extensible pipeline engine. A Workflow // is an ordered list of stages over a shared TaskContext; stages are // either deterministic steps (git, gate, PR, comments) or agent stages -// (agentloop runs). New workflows compose from the shared step library — +// (agentloop runs). New workflows compose from the shared step library -- // adding one must never require reimplementing the engine or the steps. package workflow @@ -58,7 +58,7 @@ type TaskContext struct { // CustomStages discovers a repo's per-repo custom stages (Yaegi- // interpreted from .archie/stages/*.go in the given worktree // directory), returning them in the order they should run. Wired up - // by the composition root (cmd/archied) — nil disables discovery, so + // by the composition root (cmd/archied) -- nil disables discovery, so // StageRepoStages is a no-op. Kept as an injected function rather // than a direct import to avoid workflow depending on its own // generated Yaegi symbol table (an import cycle). @@ -75,10 +75,10 @@ type TaskContext struct { // Dir/Branch are set by the prepare step. Dir string Branch string - // BuildSummary is the builder agent's finish summary — the PR body. + // BuildSummary is the builder agent's finish summary -- the PR body. BuildSummary string // BuildNoChanges is set when the builder returned StatusPassed but - // made no file changes — the fix already exists or the issue is a + // made no file changes -- the fix already exists or the issue is a // no-op. StageCommitPush closes the issue instead of erroring. BuildNoChanges bool // ReproProof is the captured failing-test output from a TDD repro @@ -153,7 +153,7 @@ func Route(t *store.Task, reg Registry) Workflow { } case "bootstrap": // Diagnostics: exercise the full pipeline deterministically - // (no LLM spend) — invites, clone, push, PR, labels. + // (no LLM spend) -- invites, clone, push, PR, labels. if wf, ok := reg["bootstrap"]; ok { return wf } @@ -175,7 +175,7 @@ func Route(t *store.Task, reg Registry) Workflow { } // Run executes the workflow: stages in order, task persisted after each, -// errors park the task with a comment on the issue — never silently. +// errors park the task with a comment on the issue -- never silently. func Run(ctx context.Context, wf Workflow, tc *TaskContext) { t := tc.Task t.Workflow = wf.Name @@ -204,7 +204,7 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) { return } t.ParkReason = fmt.Sprintf("stage %s: %v", stage.Name, err) - log.Warn("stage failed — parking", "stage", stage.Name, "err", err) + log.Warn("stage failed -- parking", "stage", stage.Name, "err", err) park(ctx, tc, t.ParkReason) return } @@ -233,7 +233,7 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) { // stateLabelFor maps a terminal workflow status to its forge label by // looking up the configured [dispatch.labels]; empty clears (done states -// — the issue closes or the PR speaks). +// -- the issue closes or the PR speaks). func stateLabelFor(d config.Dispatch, status string) string { switch status { case store.StatusPROpen: diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index d89d8d683..94d9c944d 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -1,6 +1,6 @@ // Package worktree owns archied's git operations: fresh clone per task, // branch, commit as the bot identity, push, diff stats, cleanup. The -// daemon performs these deterministically — the model's shell tool never +// daemon performs these deterministically -- the model's shell tool never // drives git. package worktree @@ -119,7 +119,7 @@ func (m *Manager) prepare(ctx context.Context, owner, repo, base string, issue i } } if _, err := m.git(ctx, dir, "reset", "--hard", "origin/"+base); err != nil { - _ = err // Non-fatal — the branch may not have been pushed yet. + _ = err // Non-fatal -- the branch may not have been pushed yet. } return dir, branch, nil } @@ -349,7 +349,7 @@ func (m *Manager) Push(ctx context.Context, dir, branch string) error { return err } -// ChangedLines reports lines added+deleted vs the base branch — the +// ChangedLines reports lines added+deleted vs the base branch -- the // input to the diff-size cap. func (m *Manager) ChangedLines(ctx context.Context, dir, base string) (int, error) { out, err := m.git(ctx, dir, "diff", "--shortstat", "origin/"+base+"...HEAD") diff --git a/internal/worktree/worktree_test.go b/internal/worktree/worktree_test.go index f7b187584..0dc7464d2 100644 --- a/internal/worktree/worktree_test.go +++ b/internal/worktree/worktree_test.go @@ -224,7 +224,7 @@ func TestAskpassWrittenOnce(t *testing.T) { t.Fatalf("paths differ: %q vs %q", p1, p2) } - // Mod time must be unchanged — file was not rewritten. + // Mod time must be unchanged -- file was not rewritten. fi2, err := os.Stat(p2) if err != nil { t.Fatal(err) @@ -307,7 +307,7 @@ func TestPrepareResumesAfterInterruptedClone(t *testing.T) { t.Fatalf("working tree missing README.md after prepare: %v", err) } - // CommitAll must work — the sentinel is excluded from git tracking. + // CommitAll must work -- the sentinel is excluded from git tracking. changed, err := m.CommitAll(ctx, dir2, "noop") if err != nil || changed { t.Fatalf("clean CommitAll = (%v, %v), want (false, nil)", changed, err) @@ -318,7 +318,7 @@ func TestPrepareResumesAfterInterruptedClone(t *testing.T) { t.Fatalf("push: %v", err) } - // A second Prepare call must short-circuit via the sentinel — no re-clone. + // A second Prepare call must short-circuit via the sentinel -- no re-clone. dir3, _, err := m.Prepare(ctx, "acme", "interrupt", "main", 1, "feat: interrupted", "", "") if err != nil { t.Fatalf("second prepare: %v", err) @@ -610,7 +610,7 @@ func TestPushRejected(t *testing.T) { } // Now the first worktree's branch is behind origin/branch. - // Make a change and try to push — it should be rejected. + // Make a change and try to push -- it should be rejected. if err := os.WriteFile(filepath.Join(dir, "third.txt"), []byte("third\n"), 0o644); err != nil { t.Fatal(err) } diff --git a/internal/worktreerpc/worktreerpc.go b/internal/worktreerpc/worktreerpc.go index c4cea90b5..b48533e58 100644 --- a/internal/worktreerpc/worktreerpc.go +++ b/internal/worktreerpc/worktreerpc.go @@ -1,6 +1,6 @@ // Package worktreerpc lets archie-agent request the two worktree -// operations that touch the network — clone/fetch (Prepare) and push -// (Push) — over core NATS request/reply, instead of holding the forge +// operations that touch the network -- clone/fetch (Prepare) and push +// (Push) -- over core NATS request/reply, instead of holding the forge // credential itself. archied remains the sole holder of // worktree.Manager.Token and performs both against the host worktree // directory (the same files the agent container has bind-mounted at @@ -29,7 +29,7 @@ const ( ) // PushRequest identifies the task's worktree by owner/repo/issue rather -// than trusting a path from the (sandboxed) agent — the server resolves +// than trusting a path from the (sandboxed) agent -- the server resolves // the directory itself via worktree.Manager.Dir. type PushRequest struct { Owner string `json:"owner"` diff --git a/internal/worktreerpc/worktreerpc_test.go b/internal/worktreerpc/worktreerpc_test.go index eb59427fb..6c3df9069 100644 --- a/internal/worktreerpc/worktreerpc_test.go +++ b/internal/worktreerpc/worktreerpc_test.go @@ -34,7 +34,7 @@ func connect(t *testing.T, url string) *nats.Conn { } // newLocalRemote creates a bare repo with one commit on main, reachable -// via file:////.git — mirrors worktree_test.go's helper. +// via file:////.git -- mirrors worktree_test.go's helper. func newLocalRemote(t *testing.T, owner, repo string) string { t.Helper() host := t.TempDir() @@ -178,7 +178,7 @@ func TestClientPropagatesServerError(t *testing.T) { t.Cleanup(unsub) client := &Client{Conn: connect(t, url), Timeout: 5 * time.Second} - // No worktree ever prepared at this dir — push must fail. + // No worktree ever prepared at this dir -- push must fail. err = client.Push(context.Background(), "acme", "nonexistent", 999, "some-branch") if err == nil { t.Fatal("expected Push to propagate the server-side git error") diff --git a/internal/yaegiutil/yaegiutil.go b/internal/yaegiutil/yaegiutil.go index 24fc0f13d..5f43b3b41 100644 --- a/internal/yaegiutil/yaegiutil.go +++ b/internal/yaegiutil/yaegiutil.go @@ -4,8 +4,8 @@ // plugins, skill scripts). Each surface differs in what symbol tables it // loads, what export it resolves, and how it invokes that export, but // all of them build an interpreter the same way and must recover a -// panic from interpreted code — including a panic during the call -// itself, not just during eval — rather than let it take down the +// panic from interpreted code -- including a panic during the call +// itself, not just during eval -- rather than let it take down the // daemon. package yaegiutil @@ -19,7 +19,7 @@ import ( // New returns a Yaegi interpreter with the standard library and any // extraSymbols loaded. Each interpreted file must get its own -// interpreter when it declares package main — Yaegi cannot co-evaluate +// interpreter when it declares package main -- Yaegi cannot co-evaluate // two package-main files with colliding symbols (e.g. two Stage() // functions) in the same interpreter. func New(opts interp.Options, extraSymbols ...map[string]map[string]reflect.Value) (*interp.Interpreter, error) { @@ -37,7 +37,7 @@ func New(opts interp.Options, extraSymbols ...map[string]map[string]reflect.Valu // Resolve evaluates src in i and type-asserts exportPath's value // (e.g. "main.Stage", "gate.Check") to T. It does not itself recover -// panics — wrap the call that invokes the returned T in Safe, since a +// panics -- wrap the call that invokes the returned T in Safe, since a // panic can happen either during Eval (e.g. an init()) or during the // caller's later invocation of the resolved function. func Resolve[T any](i *interp.Interpreter, src, exportPath string) (result T, err error) { @@ -55,7 +55,7 @@ func Resolve[T any](i *interp.Interpreter, src, exportPath string) (result T, er return fn, nil } -// Safe runs fn and recovers any panic — interpreted code is untrusted +// Safe runs fn and recovers any panic -- interpreted code is untrusted // relative to the daemon's own logic, so a nil dereference or // out-of-range index inside it must become an error, not a crash. // label identifies the interpreted source in the resulting error. diff --git a/task.json b/task.json index 5f79095e3..425a5a946 100644 --- a/task.json +++ b/task.json @@ -1 +1 @@ -{"id":5,"owner":"sam","repo":"archie-core","issue_number":57,"title":"Prepare() treats worktree as ready from .git dir existence alone","body":"## Problem\n\n`Manager.Prepare` in `internal/worktree/worktree.go:76-79` decides whether a task worktree is already fully prepared solely by checking that a `.git` directory exists:\n\n```go\n// Already prepared (daemon cloned before container acquire).\nif st, statErr := os.Stat(filepath.Join(dir, \".git\")); statErr == nil \u0026\u0026 st.IsDir() {\n return dir, branch, nil\n}\n```\n\n`git clone` creates the `.git` directory early in the clone process, before the checkout of the working tree completes, and well before the subsequent `checkout -b archie/issue-N` step (worktree.go:93) runs. If `archied` is killed or restarted (OOM, deploy, crash) while a clone is in progress, on the next start `Prepare()` will see the existing `.git` directory and short-circuit, assuming the worktree is fully set up — skipping the clone, the `checkout -b` branch creation, and any config steps.\n\n## Why it matters\n\nThis directly conflicts with the package's stated goal of being safely restartable: the package doc for `internal/daemon/daemon.go:3` states \"the daemon is restartable ... at any point.\" With this shortcut, a restart mid-clone leaves a `.git` directory but an incomplete/missing working tree and no `archie/issue-N` branch. Later calls to `CommitAll` (git add/status/commit) or `Push` (git push -u origin branch) will then operate on this broken state — failing with confusing errors, or in the worst case running against whatever branch actually exists (e.g. the base branch) rather than the intended `archie/issue-N` branch.\n\n## Suggested fix\n\nStrengthen the \"already prepared\" check to verify actual completion, not just `.git` existence, e.g.:\n- Confirm the target branch exists and is checked out (`git rev-parse --verify \u003cbranch\u003e` / check `HEAD`), and\n- Confirm the working tree is non-empty / clone actually finished (e.g. check for a marker file written only after the full clone+checkout sequence succeeds, or verify `git status` runs without error and matches expected branch).\n\nA simple robust option: write a sentinel file (e.g. `.archie-prepared`) as the very last step of the success path, and gate the early-return solely on that sentinel rather than on `.git` alone.\n\u003c/refined_body\u003e\n","labels":["agent:dead"],"workflow":"","branch":"feat/57-prepare-treats-worktree-as-ready-from-git-dir-existence-alon"} \ No newline at end of file +{"id":5,"owner":"sam","repo":"archie-core","issue_number":57,"title":"Prepare() treats worktree as ready from .git dir existence alone","body":"## Problem\n\n`Manager.Prepare` in `internal/worktree/worktree.go:76-79` decides whether a task worktree is already fully prepared solely by checking that a `.git` directory exists:\n\n```go\n// Already prepared (daemon cloned before container acquire).\nif st, statErr := os.Stat(filepath.Join(dir, \".git\")); statErr == nil \u0026\u0026 st.IsDir() {\n return dir, branch, nil\n}\n```\n\n`git clone` creates the `.git` directory early in the clone process, before the checkout of the working tree completes, and well before the subsequent `checkout -b archie/issue-N` step (worktree.go:93) runs. If `archied` is killed or restarted (OOM, deploy, crash) while a clone is in progress, on the next start `Prepare()` will see the existing `.git` directory and short-circuit, assuming the worktree is fully set up -- skipping the clone, the `checkout -b` branch creation, and any config steps.\n\n## Why it matters\n\nThis directly conflicts with the package's stated goal of being safely restartable: the package doc for `internal/daemon/daemon.go:3` states \"the daemon is restartable ... at any point.\" With this shortcut, a restart mid-clone leaves a `.git` directory but an incomplete/missing working tree and no `archie/issue-N` branch. Later calls to `CommitAll` (git add/status/commit) or `Push` (git push -u origin branch) will then operate on this broken state -- failing with confusing errors, or in the worst case running against whatever branch actually exists (e.g. the base branch) rather than the intended `archie/issue-N` branch.\n\n## Suggested fix\n\nStrengthen the \"already prepared\" check to verify actual completion, not just `.git` existence, e.g.:\n- Confirm the target branch exists and is checked out (`git rev-parse --verify \u003cbranch\u003e` / check `HEAD`), and\n- Confirm the working tree is non-empty / clone actually finished (e.g. check for a marker file written only after the full clone+checkout sequence succeeds, or verify `git status` runs without error and matches expected branch).\n\nA simple robust option: write a sentinel file (e.g. `.archie-prepared`) as the very last step of the success path, and gate the early-return solely on that sentinel rather than on `.git` alone.\n\u003c/refined_body\u003e\n","labels":["agent:dead"],"workflow":"","branch":"feat/57-prepare-treats-worktree-as-ready-from-git-dir-existence-alon"} \ No newline at end of file