refactor: format markdown files using prettier, fix spelling concerns, reduce Taskfile bloat

This commit is contained in:
sam committed 2026-09-25 01:10:28 +10:00
1 parent 2051ca94d2
commit 2e00777f07
608 files changed
+63317 -10219

No files matched your search

+5 -4
View File
@@ -1,23 +1,24 @@
# 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.
Planned workflows:
- **bootstrap** (registered): deterministic marker-file PR proving invites/clone/push/PR plumbing.
- **implement**: planner (read-only agentloop, plan posted to the issue) → builder (full toolset,
repo gate) → diff cap → PR.
@@ -31,7 +32,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.
## Security posture
+21 -21
View File
@@ -2,7 +2,7 @@
**Author:** Archie
**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)
---
@@ -10,22 +10,22 @@
This document describes a target end state. The table below is the ground truth; read it before treating any section as already built.
| Area | Status | What actually exists today (post-e4d11b1) |
|---|---|---|
| Daemon/agent binary split | **Implemented** | `cmd/archied` and `cmd/archie-agent` both exist. `archie-agent` is a 189-line NATS-connected per-task worker that subscribes to task subjects, runs the full multi-stage workflow, and reports results. Workflow routing and sequencing (`workflow.Route`, `workflow.Run`) now run inside the agent, not the daemon. Three agent modes: `inprocess`, `subprocess`, `nats`. |
| Sandbox / "daemon never runs untrusted code" | **Partial** | Default mode is still `inprocess` for development. Docker sandbox mode (`agent.mode = "nats"` + `containers.enabled = true`) runs each task in an ephemeral Docker container with workspace bind-mounted at `/workspace`. `internal/container/pool.go` manages full lifecycle: pull, create, start, release, orphan recovery. Daemon dispatch and container lifecycle both enforce `max_concurrency`; same-repo tasks remain serialized. |
| NATS / JetStream messaging | **Implemented** | `internal/nats/client.go`: JetStream connect, stream creation (WorkQueue retention, file storage), pull consumer (durable, ack-wait 5min, max-deliver 3, dedup by Msg-Id), `PublishTask`, `Fetch`, `NewReplyInbox`, and optional token authentication. Subject hierarchy lives in `internal/nats/subjects.go`; `internal/agentexec/nats.go` implements request/reply agent execution. |
| Docker container sandbox | **Implemented** | `internal/container/pool.go` (210 lines): Docker API client, image pull (always/missing/never), container create with workspace bind mount, start, release (stop+remove), orphan recovery on daemon restart. `Dockerfile` at repo root builds archie-agent fat image. `[containers]` config block: enabled, image, max_concurrency, max_uptime, pull_policy. `agent.mode = "nats"` required when containers enabled. |
| `/data/` volume, `task.json` | **Partial** | `container.WriteTaskJSON()` writes task payload to the worktree before container acquire. The container pool bind-mounts the isolated task worktree at `/data/worktree`; configured repos also receive a persistent `/data/repo` Docker volume. Task payload travels over NATS as the primary channel; `/data/task.json` is a boot-time brief for the container. |
| `[containers]` config block | **Implemented** | `ContainerConfig` struct in config.go: enabled, image, max_concurrency, max_uptime, pull_policy. Validated on load. |
| Yaegi extensibility (gates, custom stages, skill scripts) | **Implemented** | Three surfaces: `.archie/gate.go`, `.archie/stages/*.go`, skill scripts via `run_go_script` tool. All in-process via Yaegi with generated symbol tables and panic recovery. Full detail in `docs/prds/yaegi-plugin-system.md`. |
| Layer 1: skill-bundled plugins | **Implemented** | `skill.DiscoverPlugins()` scans `.agents/skills/<name>/plugins/*.go`. `skill.Plugin.Run()` executes them via Yaegi. `skillbuild.BuildWorkflow()` constructs `workflow.Workflow` from plugin-defined stages. `TaskContext.SkillPlugins` makes them available during stage execution. `skillbuild.BuildRegistry()` replaces the hardcoded `workflow.Registry` with catalog-driven construction -- skills define workflows, plugins define stages. |
| Layer 2: core daemon plugins | **Partial** | `internal/plugin/plugin.go`: `Plugin` interface (`Name()`, `Version()`), `Registry` type, `LoadDir()` using Yaegi to interpret `.go` files. No `~/.config/archie/plugins/` loader wired into `cmd/archied/main.go` yet -- the interface and registry exist but are not connected to the daemon's startup. |
| Skills (agentskills.io spec) | **Implemented** | `internal/skill/skill.go`: parses SKILL.md YAML frontmatter, discovers skills from `.agents/skills/*/SKILL.md`, extracts body. Skills follow `archie-wf-*` naming convention. Progressive disclosure: `Catalog()` (Tier 1 -- frontmatter-only scan, ~100 tokens per entry), `LoadBody()` (Tier 2 -- full body on activation), `Discover()` (Tier 3 -- full parse with plugins). `metadata.archie.workflow` declares skill→workflow affinity. `skill.SkillForWorkflow()` is catalog-driven, no hardcoded maps. `skillbuild.BuildRegistry()` constructs the daemon's workflow registry from the catalog. |
| 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. |
| Area | Status | What actually exists today (post-e4d11b1) |
| --------------------------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Daemon/agent binary split | **Implemented** | `cmd/archied` and `cmd/archie-agent` both exist. `archie-agent` is a 189-line NATS-connected per-task worker that subscribes to task subjects, runs the full multi-stage workflow, and reports results. Workflow routing and sequencing (`workflow.Route`, `workflow.Run`) now run inside the agent, not the daemon. Three agent modes: `inprocess`, `subprocess`, `nats`. |
| Sandbox / "daemon never runs untrusted code" | **Partial** | Default mode is still `inprocess` for development. Docker sandbox mode (`agent.mode = "nats"` + `containers.enabled = true`) runs each task in an ephemeral Docker container with workspace bind-mounted at `/workspace`. `internal/container/pool.go` manages full lifecycle: pull, create, start, release, orphan recovery. Daemon dispatch and container lifecycle both enforce `max_concurrency`; same-repo tasks remain serialised. |
| NATS / JetStream messaging | **Implemented** | `internal/nats/client.go`: JetStream connect, stream creation (WorkQueue retention, file storage), pull consumer (durable, ack-wait 5min, max-deliver 3, dedup by Msg-Id), `PublishTask`, `Fetch`, `NewReplyInbox`, and optional token authentication. Subject hierarchy lives in `internal/nats/subjects.go`; `internal/agentexec/nats.go` implements request/reply agent execution. |
| Docker container sandbox | **Implemented** | `internal/container/pool.go` (210 lines): Docker API client, image pull (always/missing/never), container create with workspace bind mount, start, release (stop+remove), orphan recovery on daemon restart. `Dockerfile` at repo root builds archie-agent fat image. `[containers]` config block: enabled, image, max_concurrency, max_uptime, pull_policy. `agent.mode = "nats"` required when containers enabled. |
| `/data/` volume, `task.json` | **Partial** | `container.WriteTaskJSON()` writes task payload to the worktree before container acquire. The container pool bind-mounts the isolated task worktree at `/data/worktree`; configured repos also receive a persistent `/data/repo` Docker volume. Task payload travels over NATS as the primary channel; `/data/task.json` is a boot-time brief for the container. |
| `[containers]` config block | **Implemented** | `ContainerConfig` struct in config.go: enabled, image, max_concurrency, max_uptime, pull_policy. Validated on load. |
| Yaegi extensibility (gates, custom stages, skill scripts) | **Implemented** | Three surfaces: `.archie/gate.go`, `.archie/stages/*.go`, skill scripts via `run_go_script` tool. All in-process via Yaegi with generated symbol tables and panic recovery. Full detail in `docs/prds/yaegi-plugin-system.md`. |
| Layer 1: skill-bundled plugins | **Implemented** | `skill.DiscoverPlugins()` scans `.agents/skills/<name>/plugins/*.go`. `skill.Plugin.Run()` executes them via Yaegi. `skillbuild.BuildWorkflow()` constructs `workflow.Workflow` from plugin-defined stages. `TaskContext.SkillPlugins` makes them available during stage execution. `skillbuild.BuildRegistry()` replaces the hardcoded `workflow.Registry` with catalogue-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 catalogue-driven, no hardcoded maps. `skillbuild.BuildRegistry()` constructs the daemon's workflow registry from the catalogue. |
| 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. |
**Net read post-1dca419:** Phases 1, 2, and 3 are substantially implemented. NATS, Docker sandbox, skill parsing, skill-bundled plugins (Layer 1), skill progressive disclosure, and catalog-driven workflow construction (`skillbuild.BuildRegistry()`) all landed. The remaining aspirational work is Layer 2 daemon plugin loader (interface exists, not wired), pluggable storage backends, and per-worktree dynamic registry augmentation.
**Net read post-1dca419:** Phases 1, 2, and 3 are substantially implemented. NATS, Docker sandbox, skill parsing, skill-bundled plugins (Layer 1), skill progressive disclosure, and catalogue-driven workflow construction (`skillbuild.BuildRegistry()`) all landed. The remaining aspirational work is Layer 2 daemon plugin loader (interface exists, not wired), pluggable storage backends, and per-worktree dynamic registry augmentation.
---
@@ -313,7 +313,7 @@ metadata:
Per the agentskills.io spec:
1. **Catalog** (~100 tokens): `name` + `description` loaded at workflow start
1. **Catalogue** (~100 tokens): `name` + `description` loaded at workflow start
2. **Instructions** (<5000 tokens): Full `SKILL.md` body when the skill is activated
3. **Resources** (as needed): References, scripts, and bundled plugins loaded on demand
@@ -453,7 +453,7 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen
- ~~Persistent volumes with TTL~~ -- **done**: configured repos receive a persistent Docker volume plus a per-repo Git
object cache; both are automatically reaped using `containers.volume_ttl`.
- ~~`max_concurrency` enforcement~~ -- **done**: SQLite and NATS drains dispatch different repositories concurrently
up to `[containers].max_concurrency`; same-repo tasks remain serialized by default.
up to `[containers].max_concurrency`; same-repo tasks remain serialised by default.
- Grace period `max_uptime` -- not started
- **Groundwork already in place:** `agentexec.Runner` (`InProcessRunner`/`SubprocessRunner`) is an interface designed,
per its own doc comments, to be swapped for a container-backed runner without touching workflow orchestration --
@@ -504,9 +504,9 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen
lifetime with `max_total_uptime` (e.g. 4 hours) to prevent infinite hanging. `max_uptime` = grace after inactivity,
`max_total_uptime` = absolute kill switch.
5. **Concurrent agents on the same repo:** ~~Resolved.~~ Serialized by default (dispatcher chains tasks per
5. **Concurrent agents on the same repo:** ~~Resolved.~~ Serialised by default (dispatcher chains tasks per
`owner/repo`). `[[repos]]` now supports `allow_concurrent = true` (`config.Repo.AllowConcurrent`) to opt a repo out
of that serialization; the global `[containers].max_concurrency` slot limit still applies. Worktrees are already
of that serialisation; the global `[containers].max_concurrency` slot limit still applies. Worktrees are already
keyed per issue number (`worktree.Manager.Dir`), so opted-in repos don't collide on disk.
6. **Plugin architecture reconciliation:** Extend the existing Yaegi surfaces (`internal/gate/gateeval`,
@@ -515,5 +515,5 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen
3/4.
7. **Skill loading scope:** "Parse frontmatter, inject body into system prompt" is sufficient for v2. The gap is that
nothing reads SKILL.md today -- closing that gap is the value. Full progressive disclosure (catalog -> activate ->
nothing reads SKILL.md today -- closing that gap is the value. Full progressive disclosure (catalogue -> activate ->
resources) is deferred to a later phase.
+46 -37
View File
@@ -1,4 +1,4 @@
# archie-core Skills System -- PRD
# archie-core Skills System -- PRD
**Author:** Archie
**Date:** 2026-07-18
@@ -41,15 +41,15 @@ project:
# How archie-core connects to this project
connection:
interfaces:
- github # respond to assigned issues
- linear # respond to labelled tickets
- webhook # respond to HTTP POSTs
- github # respond to assigned issues
- linear # respond to labelled tickets
- webhook # respond to HTTP POSTs
github:
repo: sam/my-go-service
issue_labels:
ready: "archie:ready" # issues with this label get claimed
claimed: "archie:claimed" # archie sets this when working
done: "archie:done" # archie sets this after PR
ready: "archie:ready" # issues with this label get claimed
claimed: "archie:claimed" # archie sets this when working
done: "archie:done" # archie sets this after PR
pr:
base: main
draft: false
@@ -57,10 +57,10 @@ connection:
# Skills -- playbooks archie-core loads to know how to work
skills:
paths:
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
remotes:
- github.com/sam/archie-skills@v1 # shared skill library
- github.com/sam/archie-skills@v1 # shared skill library
# Sandbox -- what's available in the container
sandbox:
@@ -155,9 +155,11 @@ metadata:
# Go Quality Gate
## When to use
Before committing any Go change. After implementing a feature or fix.
## Procedure
Run in this exact order. If any step fails, fix the issue before continuing.
1. `gofumpt -w .`
@@ -167,28 +169,30 @@ Run in this exact order. If any step fails, fix the issue before continuing.
5. `task deadcode`
## Verification
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)
Skills carry archie-specific metadata under `metadata.archie`:
| Field | Purpose |
|---|---|
| `gates` | Which gates from `archie.yaml` this skill covers |
| `tools` | Sandbox tools this skill needs |
| `engine` | Preferred execution engine |
| `model` | Preferred model for this skill |
| `budget_usd` | Max spend ceiling |
| `timeout` | Max seconds |
| `worktree` | Whether to create isolated worktree |
| Field | Purpose |
| ------------ | ------------------------------------------------ |
| `gates` | Which gates from `archie.yaml` this skill covers |
| `tools` | Sandbox tools this skill needs |
| `engine` | Preferred execution engine |
| `model` | Preferred model for this skill |
| `budget_usd` | Max spend ceiling |
| `timeout` | Max seconds |
| `worktree` | Whether to create isolated worktree |
### 2.4 Progressive disclosure
@@ -245,6 +249,7 @@ This is the core loop. When an issue lands with the configured label:
### 3.6 On failure
If any gate fails irrecoverably:
1. Leave issue as `archie:claimed`
2. Comment with exact blocker, failed command, and worktree path
3. Preserve worktree for inspection
@@ -258,12 +263,12 @@ 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: codex # OpenAI Codex CLI
- 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
```
@@ -281,7 +286,7 @@ For skills that need a specific engine, the skill metadata overrides:
```yaml
metadata:
archie:
engine: claude # this skill only works with Claude
engine: claude # this skill only works with Claude
```
---
@@ -312,7 +317,6 @@ metadata:
tools: [docker, trivy]
engine: any
---
## Procedure
1. `trivy image --severity HIGH,CRITICAL <image>`
2. If findings exist, report each CVE with package, version, and fixed version
@@ -323,34 +327,37 @@ metadata:
## 6. Comparison: archie-core vs existing systems
| | archie-core | Claude Code | Codex CLI | GitHub Actions | External Agent |
|---|---|---|---|---|---|
| **How it receives work** | GitHub issue assignment, Linear label, webhook | Chat, slash commands | Chat, slash commands | YAML triggers (push, PR, schedule) | Chat, cron, webhooks |
| **What it does** | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Run arbitrary shell commands | Analyse → implement → gate → PR |
| **Skills** | SKILL.md (agentskills.io) | SKILL.md (native) | SKILL.md (agentskills.io) | Composite actions | SKILL.md (native) |
| **Gates** | Named checkpoints in archie.yaml | Ad-hoc (CLAUDE.md + lint) | Ad-hoc | Steps in jobs | Skills with gates |
| **Engine pluggable** | Yes | No (fixed to Claude) | No (fixed to Codex) | No (fixed to GitHub) | Yes (provider config) |
| **Worktree isolation** | Yes | Yes (`--worktree`) | No | No (ephemeral runner) | No |
| **Blueprint/cron** | Export externally | No | No | Schedule trigger | Native |
| **Where it runs** | Docker sandbox | Host | Host or sandbox | GitHub runner | Host, Docker, Modal, SSH |
| | archie-core | Claude Code | Codex CLI | GitHub Actions | External Agent |
| ------------------------ | ---------------------------------------------- | ------------------------------- | ------------------------------- | ---------------------------------- | ------------------------------- |
| **How it receives work** | GitHub issue assignment, Linear label, webhook | Chat, slash commands | Chat, slash commands | YAML triggers (push, PR, schedule) | Chat, cron, webhooks |
| **What it does** | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Run arbitrary shell commands | Analyse → implement → gate → PR |
| **Skills** | SKILL.md (agentskills.io) | SKILL.md (native) | SKILL.md (agentskills.io) | Composite actions | SKILL.md (native) |
| **Gates** | Named checkpoints in archie.yaml | Ad-hoc (CLAUDE.md + lint) | Ad-hoc | Steps in jobs | Skills with gates |
| **Engine pluggable** | Yes | No (fixed to Claude) | No (fixed to Codex) | No (fixed to GitHub) | Yes (provider config) |
| **Worktree isolation** | Yes | Yes (`--worktree`) | No | No (ephemeral runner) | No |
| **Blueprint/cron** | Export externally | No | No | Schedule trigger | Native |
| **Where it runs** | Docker sandbox | Host | Host or sandbox | GitHub runner | Host, Docker, Modal, SSH |
---
## 7. Implementation phases
### Phase 1: Workflow file and gates (current MVP)
- `archie.yaml` parser
- Gate runner executing shell commands and checking exit codes
- Skill discovery from project and user paths
- GitHub interface: claim issues, create worktrees, open PRs
### Phase 2: Skills
- SKILL.md progressive disclosure (advertise → activate → resources)
- archie-specific metadata parsing
- Skill chaining: skills that depend on other skills
- `archie skills list/install` CLI
### Phase 3: Engine abstraction
- Engine interface definition
- Claude Code adapter
- Raw LLM adapter
@@ -358,12 +365,14 @@ metadata:
- Per-skill engine preferences
### Phase 4: Advanced features
- Gate overrides per skill
- Skill templates for project scaffolding (`archie init --skill go-service`)
- Remote skill libraries (git repos as skill sources)
- Blueprint export to an external scheduler
### Phase 5: Additional interfaces
- Linear webhook integration
- Generic webhook interface for arbitrary sources
- CLI command interface (`archie run <command>`)
+54 -49
View File
@@ -1,4 +1,4 @@
# archie-core Workflows & Skills -- Product Requirements Document
# archie-core Workflows & Skills -- Product Requirements Document
**Author:** Archie
**Date:** 2026-07-18
@@ -40,20 +40,20 @@ project:
# Available skills (directories or individual files)
skills:
paths:
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
- github.com/org/shared-skills@v1 # remote skill repo
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
- github.com/org/shared-skills@v1 # remote skill repo
skills:
- go-testing # named skill from any path
- go-testing # named skill from any path
- security-audit
# Execution engines in preference order
engines:
- type: claude # Claude Code CLI
- type: claude # Claude Code CLI
model: sonnet
- type: codex # OpenAI Codex
- type: pi # Pi agent harness
- type: raw # Direct LLM without agent wrapper
- type: codex # OpenAI Codex
- type: pi # Pi agent harness
- type: raw # Direct LLM without agent wrapper
# Sandbox definition (what the Docker container provides)
sandbox:
@@ -90,7 +90,7 @@ gates:
description: "No vet warnings"
deadcode:
run: task deadcode
optional: true # non-blocking gate
optional: true # non-blocking gate
description: "Dead code check (advisory)"
# Quality pipeline -- ordered sequence of gate groups
@@ -105,7 +105,7 @@ quality:
# Commit conventions
commit:
format: conventional # conventional commits
format: conventional # conventional commits
signoff: false
template: "feat({scope}): {description}"
@@ -142,15 +142,15 @@ commands:
### 1.3 Design decisions (with rationale)
| Decision | Rationale |
|---|---|
| YAML over TOML/JSON | Already dominant in CI (GitHub Actions, GitLab CI, Taskfile). Human-readable with comments. |
| Single file over multi-file | Task discovery (like `Taskfile.yml`), devcontainer conventions. Avoids directory sprawl. |
| Gates as named checkpoints | GitHub Actions job model. Gates can be composed into quality pipelines, selected individually, or skipped with `--skip`. |
| Engines as ordered preference list | Supports deterministic fallback between available engines. Each engine declares its own tool surface. |
| Skills as paths + references | Matches devcontainer features (paths resolve to directories) and skills.sh (namespaced references). |
| Commands section for direct invocation | Arnie can `archie run test` without an agent turn. Thin wrapper over the sandbox. |
| Quality pipeline groups gates | Pre-commit vs pre-push vs pre-merge distinction. Some gates are required, some advisory. |
| Decision | Rationale |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| YAML over TOML/JSON | Already dominant in CI (GitHub Actions, GitLab CI, Taskfile). Human-readable with comments. |
| Single file over multi-file | Task discovery (like `Taskfile.yml`), devcontainer conventions. Avoids directory sprawl. |
| Gates as named checkpoints | GitHub Actions job model. Gates can be composed into quality pipelines, selected individually, or skipped with `--skip`. |
| Engines as ordered preference list | Supports deterministic fallback between available engines. Each engine declares its own tool surface. |
| Skills as paths + references | Matches devcontainer features (paths resolve to directories) and skills.sh (namespaced references). |
| Commands section for direct invocation | Arnie can `archie run test` without an agent turn. Thin wrapper over the sandbox. |
| Quality pipeline groups gates | Pre-commit vs pre-push vs pre-merge distinction. Some gates are required, some advisory. |
---
@@ -179,9 +179,9 @@ description: >
version: 1.0.0
metadata:
archie:
gates: [test] # gates this skill requires
tools: [go, golangci-lint] # sandbox tools it needs
engine: any # engine preference
gates: [test] # gates this skill requires
tools: [go, golangci-lint] # sandbox tools it needs
engine: any # engine preference
compatibility: Requires Go 1.22+
---
```
@@ -201,13 +201,13 @@ Skills can carry archie-specific frontmatter under `metadata.archie`:
```yaml
metadata:
archie:
gates: [test, lint] # must-pass gates before skill runs
tools: [go, docker] # sandbox tools required
engine: any # preferred engine
model: gpt-4o # preferred model
budget_usd: 2.00 # max spend ceiling
timeout: 600 # max seconds
worktree: true # create isolated worktree
gates: [test, lint] # must-pass gates before skill runs
tools: [go, docker] # sandbox tools required
engine: any # preferred engine
model: gpt-4o # preferred model
budget_usd: 2.00 # max spend ceiling
timeout: 600 # max seconds
worktree: true # create isolated worktree
```
### 2.4 Skill sources (inspired by devcontainer features + Dagger modules)
@@ -241,12 +241,12 @@ Engine interface:
### 3.2 Supported engines
| Engine | Type | What it provides |
|---|---|---|
| `claude` | Claude Code CLI | Full agent loop, tool use, worktrees, subagents |
| `codex` | OpenAI Codex CLI | Agentic coding with sandbox |
| `pi` | Pi agent harness | Minimalist coding agent, stdio protocol |
| `raw` | Direct LLM call | Single-turn prompt, no agent loop. For simple scripts. |
| Engine | Type | What it provides |
| -------- | ---------------- | ------------------------------------------------------ |
| `claude` | Claude Code CLI | Full agent loop, tool use, worktrees, subagents |
| `codex` | OpenAI Codex CLI | Agentic coding with sandbox |
| `pi` | Pi agent harness | Minimalist coding agent, stdio protocol |
| `raw` | Direct LLM call | Single-turn prompt, no agent loop. For simple scripts. |
### 3.3 Engine selection logic
@@ -302,15 +302,15 @@ metadata:
archie:
gates:
test:
run: go test -short ./... # override: faster test for this skill
lint: skip # skip lint for this skill
run: go test -short ./... # override: faster test for this skill
lint: skip # skip lint for this skill
```
Three override modes: `override` (replace command), `skip` (omit gate), `add` (add new gate requirement).
### 4.4 Skill templates (scaffolding)
Skills can carry an `assets/` directory with templates. When archie-core initializes a new project, it can apply skill templates:
Skills can carry an `assets/` directory with templates. When archie-core initialises a new project, it can apply skill templates:
```
skill-name/
@@ -342,45 +342,50 @@ The export produces a `SKILL.md` with scheduler metadata. The blueprint's prompt
## 5. Comparison to Existing Systems
| Feature | archie-core | GitHub Actions | Dagger | Taskfile | devcontainer | External Skills |
|---|---|---|---|---|---|---|
| Language | YAML | YAML | Go/Python/TS | YAML | JSON | Markdown |
| Gates | Named + composable | Steps in jobs | Functions | Tasks | Lifecycle scripts | N/A |
| Engine abstraction | First-class | GitHub only | Dagger Engine | Shell only | None | Provider |
| Skills | agentskills.io spec | Composite actions | Dagger Modules | Includes | Features | SKILL.md |
| Worktree isolation | Built-in | No | Containers | No | Container | No |
| Blueprint export | To external cron | No | No | No | No | Native |
| Multi-engine fallback | Yes (ordered list) | No | No | No | No | Provider config |
| Progressive disclosure | Yes (skill spec) | No | No | No | Feature metadata | Yes |
| Feature | archie-core | GitHub Actions | Dagger | Taskfile | devcontainer | External Skills |
| ---------------------- | ------------------- | ----------------- | -------------- | ---------- | ----------------- | --------------- |
| Language | YAML | YAML | Go/Python/TS | YAML | JSON | Markdown |
| Gates | Named + composable | Steps in jobs | Functions | Tasks | Lifecycle scripts | N/A |
| Engine abstraction | First-class | GitHub only | Dagger Engine | Shell only | None | Provider |
| Skills | agentskills.io spec | Composite actions | Dagger Modules | Includes | Features | SKILL.md |
| Worktree isolation | Built-in | No | Containers | No | Container | No |
| Blueprint export | To external cron | No | No | No | No | Native |
| Multi-engine fallback | Yes (ordered list) | No | No | No | No | Provider config |
| Progressive disclosure | Yes (skill spec) | No | No | No | Feature metadata | Yes |
---
## 6. Implementation Phases
### Phase 1: Core workflow file
- `archie.yaml` parser and schema validation
- Gate runner (test, lint, format, vet)
- `archie run <command>` CLI
- Sandbox Docker integration
### Phase 2: Skills
- SKILL.md discovery and progressive disclosure
- Skill metadata with gate/tool/engine requirements
- `archie skills list/install/search`
### Phase 3: Engine abstraction
- Engine interface definition
- Claude Code adapter
- Raw LLM adapter
- Engine fallback chain
### Phase 4: Advanced features
- Worktree isolation
- Skill chaining (dependency DAG)
- Gate overrides
- Blueprint export
### Phase 5: Ecosystem
- Public skill registry
- `archie init --skill <name>` scaffolding
- Community skill contributions
File diff suppressed because it is too large. Load diff
+23 -22
View File
@@ -7,7 +7,7 @@ changing anything that contradicts a prior decision.
---
## 2026-08-24 -- Turn continuation is never output-volume or token gated
## 2026-08-24 -- Turn continuation is never output-volume or token gated
**Decision**: A turn is never stopped because an aggregate token count or
aggregate tool-result character count was reached. `max_tokens` and
@@ -24,14 +24,14 @@ used to terminate the multi-step turn.
**Context**: GitHub #604 showed full file and module listings followed by four
identical read failures and a shell failure at the old 200,000-character cap.
The renderer now summarizes those legacy events for replay, while current
The renderer now summarises those legacy events for replay, while current
dispatch never creates them. Find and grep are confined to the active
workspace/worktree; the Go module cache remains readable only by explicit
path, not by discovery.
---
## 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
@@ -45,11 +45,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
@@ -59,19 +59,19 @@ 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.
**Current state**: dolt 2.2.2, beads 1.1.0 installed. Beads initialized
**Current state**: dolt 2.2.2, beads 1.1.0 installed. Beads initialised
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
> **Superseded by the 2026-08-24 decision above.** There is no configured
> aggregate token cap; model token usage remains accounting only.
@@ -88,7 +88,7 @@ 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
@@ -96,7 +96,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
@@ -104,7 +104,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
@@ -113,7 +113,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.
@@ -126,14 +126,14 @@ 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
has no changes to commit".
**Reasoning**: A builder that passes with 0 changes means the fix
already exists or the issue is a no-op. The old behavior parked in an
already exists or the issue is a no-op. The old behaviour parked in an
infinite loop (commit-push fails because nothing changed, task re-queues,
builder runs again, same result).
@@ -147,7 +147,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
@@ -159,7 +159,7 @@ 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
@@ -174,7 +174,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
@@ -182,12 +182,13 @@ 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`.
**Key fixes**:
- NATS healthcheck uses `wget localhost:8222/healthz` (not `nats-server check`)
- `host.docker.internal:host-gateway` extra_hosts for Linux
- Config mount path: `config.docker.toml` → `/etc/archie/config.toml`
@@ -195,10 +196,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
@@ -208,7 +209,7 @@ 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)
@@ -1,7 +1,7 @@
# Multi-Agent Collaboration -- PRD
**Status:** Draft (discovery interview complete, 2026-07-25)
**Author:** Discovery interview (archie-core-abg.1), synthesized from Sam's answers
**Author:** Discovery interview (archie-core-abg.1), synthesised from Sam's answers
**Parent epic:** archie-core-abg
---
@@ -80,7 +80,7 @@ implementation slice -- see section 5.
## 3. Constraints from existing architecture
From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
(read in full before implementation; summarized here):
(read in full before implementation; summarised here):
- **`Config.BotUser` is a single global field** (`internal/config`) -- the
root blocker for daemon-side multi-identity. Becomes a per-identity field
@@ -93,7 +93,7 @@ From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
(e.g. `archie.<identity>.task.<type>`) but that's a design decision, not
yet made.
- **Dispatch is `daemon.Run()` polling per configured forge/repo list**,
serialized per `owner/repo` by default (`AllowConcurrent` opts out).
serialised per `owner/repo` by default (`AllowConcurrent` opts out).
Multi-identity daemon means multiple poll loops (or one loop iterating
multiple identity configs) feeding the same NATS/container dispatch
machinery.
@@ -109,7 +109,7 @@ From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
- **The daemon gatekeeps all agent output** -- "no agent output reaches a
human without daemon review" (`archie-core-v2-architecture.md` sec.7).
Chat channels must respect this: a chat message that triggers a spawn goes
through the same review/labeling machinery PRs and comments do today, not
through the same review/labelling machinery PRs and comments do today, not
a side channel that bypasses it.
- **Environmental constraints over prompt rules** (`ARCHITECTURE.md` design
decision #1) -- chat-triggered actions (spawn, approve, cancel) should be
@@ -119,7 +119,7 @@ From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
## 4. Identity model (design direction, not yet finalized)
Confirmed requirement: within one daemon, identities differ by bot identity,
repo list, *and* model/provider config (per the archie/winter diff). Proposed
repo list, _and_ model/provider config (per the archie/winter diff). Proposed
shape -- **not yet approved, needs a follow-up design pass before
implementation**:
@@ -139,6 +139,7 @@ forge = { type = "gitea", host = "...", token_env = "..." }
models = { triage = "...", planner = "...", builder = "..." }
repos = [ ... ]
```
```
**Design answer (2026-07-25): per-identity goroutine, shared infrastructure.**
@@ -231,3 +232,4 @@ on.
identity).
- [ ] Broken into scoped, dependency-ordered beads issues under
`archie-core-abg`, the way the 5zh epic was. (Next step, this session.)
```
+127 -121
View File
@@ -1,4 +1,4 @@
# archie-core TypeScript Plugin Engine -- PRD
# archie-core TypeScript Plugin Engine -- PRD
**Author:** Archie
**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.
---
@@ -19,22 +19,24 @@ A TypeScript-based plugin engine that lets repositories ship interpreted, dynami
TypeScript is the most widely understood language among developers writing automation, CI, and workflow scripts. It already ships in most projects. Gate authors already know it. The ecosystem for linting, formatting, and type-checking is mature and free.
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
| Competitor | Problem |
|---|---|
| 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 |
| Ramune | Heavy dependency, bundles an entire TypeScript 7 compiler |
| Node.js subprocess | Process overhead per execution, IPC serialization cost |
| Competitor | Problem |
| ------------------ | -------------------------------------------------------------------- |
| 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 |
| Ramune | Heavy dependency, bundles an entire TypeScript 7 compiler |
| Node.js subprocess | Process overhead per execution, IPC serialisation 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()`
@@ -61,7 +63,7 @@ During the poll cycle, archie-core scans each repo's worktree for `.archie/workf
```
.archie/workflows/
├── custom-gate.ts # gate functions: exported `check()`
├── custom-gate.ts # gate functions: exported `check()`
├── db-migration.ts # custom stage: exported `stage()`
└── notify-slack.ts # skill script: exported `run()`
```
@@ -72,11 +74,11 @@ Each file is a self-contained module. No `package.json`, no `node_modules`, no e
A plugin declares its role via an exported symbol:
| Export | Role | When called |
|---|---|---|
| `export function check(ctx: GateContext): Finding[]` | Gate function | After shell-based gate, before commit |
| `export function stage(): Stage` | Workflow stage | When a workflow references the stage name |
| `export function run(ctx: ScriptContext): void` | Skill script | When a skill's instructions invoke the script |
| Export | Role | When called |
| ---------------------------------------------------- | -------------- | --------------------------------------------- |
| `export function check(ctx: GateContext): Finding[]` | Gate function | After shell-based gate, before commit |
| `export function stage(): Stage` | Workflow stage | When a workflow references the stage name |
| `export function run(ctx: ScriptContext): void` | Skill script | When a skill's instructions invoke the script |
arcie-core discovers the role by checking which exports exist. A file can export multiple roles.
@@ -86,54 +88,54 @@ arcie-core discovers the role by checking which exports exist. A file can export
// .archie/workflows/custom-gate.ts
interface GateContext {
diff: string; // unified diff of changes
changedFiles: string[]; // list of changed file paths
dir: string; // absolute worktree path
repo: string; // "owner/name"
baseRef: string; // "origin/main"
diff: string; // unified diff of changes
changedFiles: string[]; // list of changed file paths
dir: string; // absolute worktree path
repo: string; // "owner/name"
baseRef: string; // "origin/main"
}
interface Finding {
level: "error" | "warn";
file?: string;
line?: number;
message: string;
level: "error" | "warn";
file?: string;
line?: number;
message: string;
}
interface Block {
name: string;
message: string;
name: string;
message: string;
}
export function check(ctx: GateContext): Finding[] {
const findings: Finding[] = [];
const findings: Finding[] = [];
// Rule: no new panic() calls
for (const line of ctx.diff.split("\n")) {
if (line.startsWith("+") && !line.startsWith("+++")) {
if (line.includes("panic(")) {
findings.push({
level: "error",
message: "new panic() call -- use error returns instead"
});
}
}
// Rule: no new panic() calls
for (const line of ctx.diff.split("\n")) {
if (line.startsWith("+") && !line.startsWith("+++")) {
if (line.includes("panic(")) {
findings.push({
level: "error",
message: "new panic() call -- use error returns instead",
});
}
}
}
// Rule: no time.Sleep in non-test files
for (const file of ctx.changedFiles) {
if (file.endsWith("_test.go")) continue;
const content = archie.readFile(`${ctx.dir}/${file}`);
if (content.includes("time.Sleep")) {
findings.push({
level: "warn",
file: file,
message: "time.Sleep in non-test code -- use time.Ticker instead"
});
}
// Rule: no time.Sleep in non-test files
for (const file of ctx.changedFiles) {
if (file.endsWith("_test.go")) continue;
const content = archie.readFile(`${ctx.dir}/${file}`);
if (content.includes("time.Sleep")) {
findings.push({
level: "warn",
file: file,
message: "time.Sleep in non-test code -- use time.Ticker instead",
});
}
}
return findings;
return findings;
}
```
@@ -145,21 +147,21 @@ After transpilation and execution, archie-core calls `check(ctx)` via goja. Erro
// .archie/workflows/run-migrations.ts
export function stage(): Stage {
return {
name: "db-migration",
run: (ctx: TaskContext): string | null => {
// Check if migrations directory exists
const hasMigrations = archie.fileExists(`${ctx.dir}/migrations`);
if (!hasMigrations) return null; // nothing to do
return {
name: "db-migration",
run: (ctx: TaskContext): string | null => {
// Check if migrations directory exists
const hasMigrations = archie.fileExists(`${ctx.dir}/migrations`);
if (!hasMigrations) return null; // nothing to do
// Run migration tests
const result = archie.exec("go", ["test", "./migrations/..."]);
if (result.exitCode !== 0) {
return `migration tests failed: ${result.stderr}`;
}
return null; // success
}
};
// Run migration tests
const result = archie.exec("go", ["test", "./migrations/..."]);
if (result.exitCode !== 0) {
return `migration tests failed: ${result.stderr}`;
}
return null; // success
},
};
}
```
@@ -169,11 +171,11 @@ export function stage(): Stage {
// .archie/workflows/security-audit.ts
export function run(ctx: ScriptContext): void {
const result = archie.exec("gitleaks", ["detect", "--no-git"]);
if (result.exitCode !== 0) {
archie.log("warn", `gitleaks found secrets:\n${result.stdout}`);
}
archie.log("info", "security audit complete");
const result = archie.exec("gitleaks", ["detect", "--no-git"]);
if (result.exitCode !== 0) {
archie.log("warn", `gitleaks found secrets:\n${result.stdout}`);
}
archie.log("info", "security audit complete");
}
```
@@ -183,33 +185,33 @@ arcie-core exposes a `archie` global in the goja runtime:
```typescript
interface Archie {
// File operations (scoped to worktree)
readFile(path: string): string;
fileExists(path: string): boolean;
listDir(path: string): string[];
walkDir(path: string): string[];
// Shell execution
exec(command: string, args?: string[]): ExecResult;
// Logging
log(level: string, message: string): void;
// Path utilities
resolve(...parts: string[]): string;
ext(path: string): string;
// Environment
env(key: string): string;
// HTTP (optional, gated)
fetch(url: string, options?: FetchOptions): FetchResult;
// File operations (scoped to worktree)
readFile(path: string): string;
fileExists(path: string): boolean;
listDir(path: string): string[];
walkDir(path: string): string[];
// Shell execution
exec(command: string, args?: string[]): ExecResult;
// Logging
log(level: string, message: string): void;
// Path utilities
resolve(...parts: string[]): string;
ext(path: string): string;
// Environment
env(key: string): string;
// HTTP (optional, gated)
fetch(url: string, options?: FetchOptions): FetchResult;
}
interface ExecResult {
stdout: string;
stderr: string;
exitCode: number;
stdout: string;
stderr: string;
exitCode: number;
}
```
@@ -217,7 +219,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.
@@ -377,18 +379,18 @@ if gatePlugin := tc.Plugins.Gate(); gatePlugin != nil {
goja natively supports ES5.1 with significant ES6 features. Modern syntax like `async/await`, `??`, `?.`, or `class` fields may not parse. The transpile step (esbuild targeting ES2017) handles most of this, but there will be edge cases:
| Feature | Status |
|---|---|
| Arrow functions | ✅ via transpile |
| Template literals | ✅ via transpile |
| Destructuring | ✅ via transpile |
| `const`/`let` | ✅ via transpile |
| `async/await` | ❌ not supported (goja is synchronous) |
| `Promise` | ❌ requires `goja_nodejs` event loop |
| Generators | ❌ not supported |
| `Proxy` | ❌ not supported |
| Feature | Status |
| ----------------- | -------------------------------------- |
| Arrow functions | ✅ via transpile |
| Template literals | ✅ via transpile |
| Destructuring | ✅ via transpile |
| `const`/`let` | ✅ via transpile |
| `async/await` | ❌ not supported (goja is synchronous) |
| `Promise` | ❌ requires `goja_nodejs` event loop |
| 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
@@ -402,44 +404,48 @@ Plugins can't `import` from npm or other files. They're self-contained modules.
## Comparison: Yaegi vs goja
| | Yaegi (Go) | goja + esbuild (TypeScript) |
|---|---|---|
| **Language** | Go | TypeScript |
| **Pure Go** | ✅ | ✅ (goja + esbuild both pure Go) |
| **CGO** | None | None |
| **Transpile step** | None (interpreted directly) | esbuild TS→JS (~3ms) |
| **Author audience** | Go developers | Anyone who knows TypeScript |
| **Type annotations** | N/A (Go is typed) | Stripped by esbuild (no type-check at runtime) |
| **Interop** | Direct Go↔Go via `Use()` | Bridge via `archie` global |
| **Performance** | Interpreted Go (~10x slower than compiled) | Interpreted JS (~50x slower than V8, fine for gates) |
| **Maturity** | 8k stars, used by Traefik for plugins | 7k stars, used by k6, goja is battle-tested |
| **File extension** | `.go` | `.ts` |
| **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 |
| | Yaegi (Go) | goja + esbuild (TypeScript) |
| -------------------- | ----------------------------------------------------------- | --------------------------------------------------------- |
| **Language** | Go | TypeScript |
| **Pure Go** | ✅ | ✅ (goja + esbuild both pure Go) |
| **CGO** | None | None |
| **Transpile step** | None (interpreted directly) | esbuild TS→JS (~3ms) |
| **Author audience** | Go developers | Anyone who knows TypeScript |
| **Type annotations** | N/A (Go is typed) | Stripped by esbuild (no type-check at runtime) |
| **Interop** | Direct Go↔Go via `Use()` | Bridge via `archie` global |
| **Performance** | Interpreted Go (~10x slower than compiled) | Interpreted JS (~50x slower than V8, fine for gates) |
| **Maturity** | 8k stars, used by Traefik for plugins | 7k stars, used by k6, goja is battle-tested |
| **File extension** | `.go` | `.ts` |
| **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).
---
## Implementation phases
### Phase 1: goja runtime + esbuild
- Add `github.com/dop251/goja` and `github.com/evanw/esbuild` as dependencies
- Build `internal/plugins/` with loader, runtime pool, bridge
- Wire gate plugin discovery into the implement and TDD workflows
- Gate plugins run after shell-based gate, before commit
### Phase 2: Custom stages
- Stage plugins discovered and registered alongside built-in stages
- `config.toml` can reference plugin stages by name
- TaskContext exposed to JS plugins
### Phase 3: Skill scripts
- Skill SKILL.md can reference `scripts/security-audit.ts`
- archie-core loads, transpiles, and evaluates when the skill activates
- Script stdout captured and returned to the agent as tool output
### Phase 4: Yaegi side-by-side
- Go plugin files (`.go`) loaded via Yaegi from the same `.archie/workflows/` directory
- Same discovery pattern, different interpreter
- archie-core chooses engine by file extension