Files
archie/internal/app/archied/main.go
T
sam e0b6aa6105 feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00

1029 lines
36 KiB
Go

// Command archied is the archie orchestrator daemon: it watches GitHub
// for issues labelled for archie, works each one in an isolated
// worktree through its routed workflow, and opens pull requests for
// human review.
package archied
import (
"context"
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"log/slog"
"net"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"syscall"
"github.com/moby/moby/client"
natsio "github.com/nats-io/nats.go"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/forge"
"github.com/samcharles93/archie-core/internal/forgerpc"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/plugin"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
"github.com/samcharles93/archie-core/internal/tools/mcp"
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
"github.com/samcharles93/archie-core/internal/worktree"
"github.com/samcharles93/archie-core/internal/worktreerpc"
)
const (
// defaultChatMaxSteps bounds the model/tool round-trips in one chat
// turn when [config.ChatConfig.MaxSteps] is unset.
defaultChatMaxSteps = 100
)
// Component versions are injected from their independent release tags.
// Components without a release tag remain "dev" and never generate upgrade
// notifications.
var (
gatewayVersion = "dev"
runtimeVersion = "dev"
)
// chatGenerateOptions builds one chat turn's request.
func chatGenerateOptions(
ctx context.Context,
messages []chat.Message,
registry *tools.Registry,
maxSteps int,
limits agentexec.ToolLimits,
extra []tools.ToolEntry,
contextWindow int,
) (core.GenerateOptions, error) {
toolOpts := limits.Options()
if approval := gateway.ApprovalFromContext(ctx); approval != nil {
toolOpts.Approval = approval
}
// Progressive tool disclosure: compose the base registry with the per-turn
// extras into a turn-local registry (extras are identity-bound and cannot
// live in the process-wide registry), then let the ContextPressureGate
// decide whether to serve the full arsenal directly or fall back to the
// bridge tools. The bridge tools are never registered process-wide, so they
// stay inside this composed, per-turn registry.
composed, err := tools.ComposeForTurn(registry, extra)
if err != nil {
return core.GenerateOptions{}, err
}
gate := tools.NewContextPressureGate(contextWindow)
gate.Evaluate(composed.All())
toolSet, err := agentexec.BuildToolSetFrom(gate.FilterTools(composed), toolOpts)
if err != nil {
return core.GenerateOptions{}, err
}
if maxSteps <= 0 {
maxSteps = defaultChatMaxSteps
}
return core.GenerateOptions{
Messages: messages,
Tools: toolSet,
MaxSteps: maxSteps,
}, nil
}
// isWithin reports whether target sits inside base.
func isWithin(base, target string) bool {
absBase, err := filepath.Abs(base)
if err != nil {
return false
}
absTarget, err := filepath.Abs(target)
if err != nil {
return false
}
rel, err := filepath.Rel(absBase, absTarget)
if err != nil {
return false
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
// toolLimits reads the configured per-turn result limits.
func toolLimits(cfg config.Config) agentexec.ToolLimits {
return agentexec.ToolLimits{
MaxResultChars: cfg.Tools.Policy.MaxResultChars,
SpillDir: cfg.Tools.Policy.SpillDir,
}
}
// taskListOverRead multiplies the requested limit when reading rows that are
// filtered by identity afterwards.
const taskListOverRead = 5
// chatTaskListerAdapter gives the gateway a read view of one identity's tasks.
// gateway deliberately does not import internal/store, so the projection
// happens here, as it does for the writer and controller adapters below.
type chatTaskListerAdapter struct {
tasks func(context.Context, int) ([]workflow.Task, error)
}
func (a chatTaskListerAdapter) ListChatTasks(ctx context.Context, identity string, limit int) ([]gateway.ChatTaskSummary, error) {
// Over-read before filtering: Tasks applies its limit across the whole
// table, so asking for exactly `limit` would return fewer than that for
// this identity whenever another identity's work is more recent.
rows, err := a.tasks(ctx, limit*taskListOverRead)
if err != nil {
return nil, err
}
out := make([]gateway.ChatTaskSummary, 0, limit)
for _, task := range rows {
if task.Identity != identity {
continue
}
if len(out) >= limit {
break
}
out = append(out, gateway.ChatTaskSummary{
ID: task.ID,
Repo: task.Owner + "/" + task.Repo,
Title: task.Title,
Status: task.Status,
Workflow: task.Workflow,
Stage: task.Stage,
PRNumber: task.PRNumber,
Attempt: task.Attempt,
ParkReason: task.ParkReason,
UpdatedAt: task.UpdatedAt,
})
}
return out, nil
}
// npmCacheServerEnv returns environment variables that make an
// npx-launched MCP server reuse a persistent package cache across daemon
// restarts, instead of npm re-resolving and re-downloading the package
// from the registry every time the daemon starts. Rooted under the
// daemon's own work dir so it persists regardless of whether the daemon
// itself runs in an ephemeral container. See mcp.NpmCacheEnv for the
// command-matching and env var details shared with archie-agent's
// per-task equivalent (internal/app/agentworker/mcp_providers.go), which
// points at a mounted cache volume instead of a work-dir subdirectory.
//
// workDir is unconditionally defaulted before registerTools runs
// (internal/infrastructure/configuration's applyGeneralDefaults), but
// filepath.Join silently accepts an empty string and would then put the
// cache in the daemon's current working directory instead of its
// persistent data directory -- guard it explicitly rather than trust that
// invariant here too.
func npmCacheServerEnv(command, workDir string) []string {
if workDir == "" {
return nil
}
return mcp.NpmCacheEnv(command, filepath.Join(workDir, "mcp-npm-cache"))
}
func configuredMCPProvider(server config.MCPServer, workDir string) (toolprovider.Engine, error) {
name := strings.TrimSpace(server.Name)
if name == "" {
return nil, fmt.Errorf("MCP server name is required")
}
transportType := strings.ToLower(strings.TrimSpace(server.Transport))
if transportType == "" {
transportType = "stdio"
}
switch transportType {
case "stdio":
command := strings.TrimSpace(server.Command)
if command == "" {
return nil, fmt.Errorf("MCP stdio server %q requires a command", name)
}
transport := mcp.NewStdioTransport(mcp.StdioTransportConfig{
Command: command,
Args: append([]string(nil), server.Args...),
Dir: server.WorkDir,
Env: npmCacheServerEnv(command, workDir),
})
return mcptoolprovider.New(name, transport), nil
case "http", "streamablehttp":
url := strings.TrimSpace(server.URL)
if url == "" {
return nil, fmt.Errorf("MCP http server %q requires a url", name)
}
transport := mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
Endpoint: url,
Headers: server.Headers,
})
return mcptoolprovider.New(name, transport), nil
case "sse":
sseEndpoint := strings.TrimSpace(server.SSEEndpoint)
if sseEndpoint == "" {
return nil, fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
}
transport := mcp.NewSSETransport(mcp.SSETransportConfig{
SSEEndpoint: sseEndpoint,
MessageEndpoint: strings.TrimSpace(server.MessageEndpoint),
Headers: server.Headers,
})
return mcptoolprovider.New(name, transport), nil
default:
return nil, fmt.Errorf("MCP transport %q is not supported", transportType)
}
}
// resolveForge builds the forge client for one forge configuration, returning
// the resolved token alongside it for the worktree manager.
//
// A missing or unusable credential disables the forge; it does not stop the
// daemon. The forge is one feature among many, and killing the process denies
// the operator chat, the gateway and every other subsystem over a capability
// they may not use at all -- under a systemd unit with Restart=on-failure that
// becomes a crash loop where the error scrolls past unread. A malformed
// configuration is a different matter and still fails fast in validation, well
// before this point.
func resolveForge(cfg config.Forge, secrets *secret.Registry, log *slog.Logger) (forge.Forge, string) {
if configuration.ForgeDisabled(cfg.Type) {
return forge.NewNoop(log), ""
}
token, err := secrets.Resolve(cfg.Token)
if err != nil || token == "" {
log.Warn("forge disabled: token unavailable",
"forge_type", cfg.Type,
"engine", cfg.Token.Engine,
"key", cfg.Token.Key,
"err", err)
return forge.NewNoop(log), ""
}
client, err := forge.New(cfg.Type, token, cfg.Host, log)
if err != nil {
log.Warn("forge disabled: client construction failed",
"forge_type", cfg.Type, "err", err)
return forge.NewNoop(log), ""
}
return client, token
}
func openProductionTaskStore(ctx context.Context, path string, opts ...store.OpenOption) (storecontract.TaskStore, error) {
return store.Open(ctx, path, opts...)
}
func taskDBPath(configuredPath string) string {
return configuredPath + "-tasks.sqlite"
}
// configDBPath resolves the runtime config overlay file. It is a sibling
// of the task and conversation stores (same configured path, own suffix)
// so each file owns its user_version and its migrator with no
// contention; recovery from a broken overlay is rm this file plus the
// --no-config-overlay boot flag.
func configDBPath(configuredPath string) string {
return configuredPath + "-config.sqlite"
}
func manualRequeueTask(ctx context.Context, st storecontract.TaskStore, taskID int64) error {
task, err := st.TaskByID(ctx, taskID)
if err != nil {
return err
}
if task == nil {
return fmt.Errorf("task %d not found", taskID)
}
switch task.Status {
case workflow.StatusParked, workflow.StatusWaitingHuman:
return st.Requeue(ctx, taskID, task.Status, "")
default:
return fmt.Errorf("task %d has status %q; only parked or waiting_human tasks can be requeued", taskID, task.Status)
}
}
type runArgs struct {
cfgPath string
overlayPath string
noConfigOverlay bool
once bool
requeue int64
}
func parseArgs() (runArgs, bool) {
defaultCfg := filepath.Join(configHome(), "archie", "config.toml")
var args runArgs
flag.StringVar(&args.cfgPath, "config", defaultCfg, "path to a TOML/YAML config file or configuration directory")
flag.StringVar(&args.overlayPath, "config-overlay", "", "path to a TOML/YAML overlay file or configuration directory applied on top of -config")
flag.BoolVar(&args.noConfigOverlay, "no-config-overlay", false, "skip the runtime config overlay (recovery hatch for the DB overlay; the -config-overlay file overlay still applies)")
flag.BoolVar(&args.once, "once", false, "run a single poll+process cycle and exit (systemd timer / testing)")
flag.Int64Var(&args.requeue, "requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set")
showVersion := flag.Bool("version", false, "print the gateway and runtime versions and exit")
flag.Parse()
// The versions were only reachable through the chat /version command,
// which needs a running daemon and a configured channel. An update-check
// adapter has to answer "what is installed?" from a shell, so expose the
// same two values here. Machine-readable: one "name version" per line.
if *showVersion {
fmt.Printf("archied %s\narchie-agent %s\n", gatewayVersion, runtimeVersion)
return args, true
}
return args, false
}
func Run() int { //nolint:cyclop // the composition root's setup sequence is deliberately flat and sequential
args, exit := parseArgs()
if exit {
return 0
}
root, cancelRoot := context.WithCancel(context.Background())
ctx, stop := signal.NotifyContext(root, os.Interrupt, syscall.SIGTERM)
defer stop()
b := newBootstrap()
// Arm the shutdown watchdog before any cleanup is registered so its
// disarm runs last in the LIFO cleanup chain: it force-exits the process
// as a backstop if graceful shutdown hangs past the drain-plus-grace
// leash, and stands down once every subsystem has shut down cleanly.
b.startShutdownWatchdog(ctx)
// The drain monitor cancels this root to trigger a graceful shutdown, which
// propagates through ctx exactly as an operator SIGTERM does.
b.shutdown = cancelRoot
if err := b.loadConfig(ctx, args.cfgPath, args.overlayPath, args.noConfigOverlay); err != nil {
return 1
}
defer b.cleanup()
// Before any subsystem: the port answers 503 for the whole of boot, so a
// watchdog polling a restarted daemon sees "not yet" rather than a
// refused connection it cannot tell from a crash.
if err := b.startHealth(ctx); err != nil {
return 1
}
if err := b.openStores(ctx); err != nil {
return 1
}
// Resolve the State Store contract adapter as the remote *staterpc.Client
// dialed to [services.state].target; the daemon no longer owns archie.db
// in-process, so an empty target is a composition error
// (docs/prds/state-store-contract.md §12 step 7). This runs after
// openStores has resolved b.secrets and before setupObservability wires the
// dashboard's storage surfaces (§10).
if err := b.openStateStoreAdapter(); err != nil {
return 1
}
if exit, err := b.handleRequeue(ctx, args.requeue, args.once); err != nil {
return 1
} else if exit {
return 0
}
b.loadCatalog(ctx, args.cfgPath)
b.setupObservability(ctx)
if err := b.setupBackends(ctx); err != nil {
return 1
}
if err := b.setupLLMAndChat(); err != nil {
return 1
}
if err := b.buildTreesAndIdentities(ctx); err != nil {
return 1
}
// setupMemoryEngine must run before setupCurators: curator.Registrar
// captures b.memEngines at construction time, so built the other way
// round every curator would hold a nil engine source.
if err := b.setupMemoryEngine(); err != nil {
return 1
}
if err := b.loadWorkflows(ctx); err != nil {
return 1
}
if err := b.loadPlugins(); err != nil {
return 1
}
if err := b.registerNATSRPC(); err != nil {
return 1
}
b.setupCurators(ctx)
if err := b.setupScheduling(); err != nil {
return 1
}
b.setupGuardrails()
if err := b.registerTools(ctx); err != nil {
return 1
}
b.registerStandaloneTools()
b.buildDaemon()
b.wireConfigSurfaces(ctx, args.cfgPath, args.overlayPath)
if err := b.startServices(ctx); err != nil {
return 1
}
return exitCode(b.runLoop(ctx, args.once))
}
// wireConfigSurfaces attaches the dashboard's configuration read path and
// the reload plumbing behind it. The write handlers (PATCH /api/config, the
// per-repository field update, per-row reset) are descoped for the UI
// process (archie-core-ymut): the daemon still owns the validate-persist-
// publish policy, but no HTTP route reaches it -- editing is config.toml
// plus reload -- so only the snapshot publication and the override list the
// renderer needs stay wired.
func (b *boot) wireConfigSurfaces(ctx context.Context, cfgPath, overlayPath string) {
b.wireConfigPublishing(ctx, cfgPath, overlayPath)
// Publish once at boot. Every later change goes through publishConfig,
// which republishes; without this the UI process would render nothing
// until the first reload or dashboard edit.
b.publishConfigSnapshot(ctx)
}
// bootConfigOverlay layers the runtime config overlay over the resolved
// file config. Every failure degrades rather than aborts -- the daemon
// boots on file config alone and the reason is recorded in bootOverlayErr,
// which /api/config surfaces as the reload status. The returned store is
// nil only when Open failed; a store that opened but could not be read
// stays open and non-nil so the dashboard PATCH path and reload wiring
// keep exactly the behaviour of the original inline block.
func bootConfigOverlay(
ctx context.Context,
loader *configuration.Loader,
doc *configuration.Document,
bootOverlayErr *atomic.Pointer[string],
log *slog.Logger,
) (*overlay.Store, *configuration.Document) {
store, err := overlay.Open(ctx, configDBPath(doc.Config.DBPath))
if err != nil {
recordBootOverlayError(bootOverlayErr, log, err,
"config overlay unavailable; booting on file config alone",
"path", configDBPath(doc.Config.DBPath))
return nil, doc
}
overrides, err := store.Snapshot(ctx)
if err != nil {
recordBootOverlayError(bootOverlayErr, log, err,
"config overlay unreadable; booting on file config alone")
return store, doc
}
if len(overrides) == 0 {
return store, doc
}
applied, err := loader.ApplyOverlay(doc, overrides)
if err != nil {
recordBootOverlayError(bootOverlayErr, log, err,
"config overlay rejected by validation; booting on file config alone")
return store, doc
}
return store, applied
}
// recordBootOverlayError stores the degrade reason for /api/config and
// logs it, so the operator sees both where they are looking.
func recordBootOverlayError(p *atomic.Pointer[string], log *slog.Logger, err error, msg string, args ...any) {
reason := err.Error()
p.Store(&reason)
args = append(args, "err", err)
log.Error(msg, args...)
}
// persistEvents drains the bus until it closes, giving each event an ID
// from the store. The store is the only fan-out point (docs/architecture/
// migration-decisions.md, "Dashboard live event delivery"): the UI process
// reads the same table through its event pump, so the daemon's job is
// persistence, not delivery.
//
// The insert deliberately outlives ctx: this loop ends when the bus closes,
// which is part of shutdown, and the last events of a run are exactly the
// ones an operator wants to read afterwards.
func persistEvents(ctx context.Context, sink *events.Sub, st storecontract.TaskStore, log *slog.Logger) {
ctx = context.WithoutCancel(ctx)
for e := range sink.C {
if e.ID != 0 {
continue
}
if _, err := st.InsertEvent(ctx, e); err != nil {
log.Error("event sink insert failed", "err", err)
}
}
}
// curatorEventSink adapts the in-process event bus to the curator family's
// narrow emission contract. Bus publish is non-blocking with bounded,
// dropping per-subscriber buffers, so curator activity can never
// backpressure the daemon or a chat turn.
type curatorEventSink struct {
b *events.Bus
}
func (s curatorEventSink) Emit(kind, detail string, data map[string]any) {
s.b.Publish(events.Event{Kind: kind, Detail: detail, Data: data})
}
// curatorLLMRunner adapts the shared ai-sdk runtime to the curator
// family's narrow LLMRunner contract: one model reference, plain
// messages, no tools, no streaming -- curators that need more than a
// single completion are a bigger decision than this adapter makes.
type curatorLLMRunner struct {
rt *runtime.Runtime
}
func (r curatorLLMRunner) Chat(ctx context.Context, req curator.ChatRequest) (curator.ChatResult, error) {
msgs := make([]chat.Message, 0, len(req.Messages))
for _, m := range req.Messages {
msgs = append(msgs, chat.Message{Role: chat.Role(m.Role), Content: m.Content})
}
res, err := r.rt.Chat(ctx, req.Model, core.GenerateOptions{Messages: msgs, MaxSteps: max(req.MaxSteps, 1)})
if err != nil {
return curator.ChatResult{}, err
}
return curator.ChatResult{Text: res.Text}, nil
}
type chatTaskWriterAdapter struct {
enqueue func(
ctx context.Context,
owner, repo, title, body, workflow, identity string,
) (*workflow.Task, error)
}
func (a chatTaskWriterAdapter) EnqueueChatTask(
ctx context.Context,
owner, repo, title, body, workflow, identity string,
) (int64, error) {
task, err := a.enqueue(ctx, owner, repo, title, body, workflow, identity)
if err != nil {
return 0, err
}
if task == nil {
return 0, fmt.Errorf("enqueue chat task returned no task")
}
return task.ID, nil
}
type chatTaskControllerAdapter struct {
taskByID func(context.Context, int64) (*workflow.Task, error)
requeue func(context.Context, int64, string, string) error
transition func(context.Context, int64, string, string, string) error
}
func (a chatTaskControllerAdapter) ChatTaskStatus(ctx context.Context, taskID int64) (gateway.ChatTaskStatus, bool, error) {
task, err := a.taskByID(ctx, taskID)
if err != nil {
return gateway.ChatTaskStatus{}, false, err
}
if task == nil {
return gateway.ChatTaskStatus{}, false, nil
}
if !task.IsForgeBacked() {
return gateway.ChatTaskStatus{Status: task.Status, Identity: task.Identity}, true, nil
}
return gateway.ChatTaskStatus{}, false, fmt.Errorf("task %d is not chat-originated", taskID)
}
func (a chatTaskControllerAdapter) ApproveChatTask(ctx context.Context, taskID int64) error {
return a.requeue(ctx, taskID, workflow.StatusWaitingHuman, "implement")
}
func (a chatTaskControllerAdapter) CancelChatTask(ctx context.Context, taskID int64, reason string) error {
task, err := a.taskByID(ctx, taskID)
if err != nil {
return err
}
if task == nil {
return fmt.Errorf("task %d not found", taskID)
}
if task.IsForgeBacked() {
return fmt.Errorf("task %d is not chat-originated", taskID)
}
// An operator declining work lands in the same state whichever surface
// they used. This used to record StatusRejected while the dashboard
// recorded StatusClosedWontDo, so the same decision showed up as two
// different states -- and StatusRejected, which the PR reconciler uses
// for "the pull request was closed without merging", stopped meaning one
// thing.
return a.transition(ctx, taskID, task.Status, workflow.StatusClosedWontDo, reason)
}
// chatTaskLogReaderAdapter gives the gateway a read view of a task's
// persisted log history without importing internal/logging or internal/store
// into the gateway package. Each identity's reader is scoped to its own
// tasks: the identity bound at construction is used for authorization, so a
// model cannot read another identity's task logs by passing a different
// identity through the tool input.
type chatTaskLogReaderAdapter struct {
tasks func(context.Context, int64) (*workflow.Task, error)
taskLogs *logging.TaskRegistry
}
func (a chatTaskLogReaderAdapter) ReadChatTaskLogs(
ctx context.Context, identity string, taskID int64, attempt int, q gateway.ChatTaskLogQuery,
) (gateway.ChatTaskLogResult, error) {
task, err := a.tasks(ctx, taskID)
if err != nil {
return gateway.ChatTaskLogResult{}, err
}
if task == nil {
return gateway.ChatTaskLogResult{}, fmt.Errorf("task %d not found", taskID)
}
// Match the filter chatTaskListerAdapter already applies: a model
// bound to one identity must not read logs for another identity's
// tasks, and tasks with no identity (forge-sourced) are not
// readable through a chat tool at all — they belong to the daemon,
// not a particular identity. "The empty string MUST NOT retain
// special meaning" (docs/architecture/identity.md).
if task.Identity != identity {
return gateway.ChatTaskLogResult{}, fmt.Errorf("task %d belongs to %q, not %q", taskID, task.Identity, identity)
}
if attempt <= 0 {
attempt = task.Attempt
}
path := a.taskLogs.Path(taskID, attempt)
if path == "" {
return gateway.ChatTaskLogResult{Attempt: attempt, Entries: []gateway.ChatTaskLogEntry{}}, nil
}
page, err := logging.Page(path, logging.Query{
Component: q.Component,
Contains: q.Contains,
Levels: q.Levels,
Since: q.Since,
Until: q.Until,
Limit: q.Limit,
}, q.AfterID)
if err != nil {
return gateway.ChatTaskLogResult{}, err
}
entries := make([]gateway.ChatTaskLogEntry, len(page.Entries))
for i, e := range page.Entries {
entries[i] = gateway.ChatTaskLogEntry{
Time: e.Time,
Level: e.Level,
Message: e.Message,
Fields: e.Fields,
}
}
return gateway.ChatTaskLogResult{
Entries: entries,
Attempt: attempt,
Truncated: page.Truncated,
Cursor: page.Cursor,
MoreAvailable: page.MoreAvailable,
}, nil
}
// chatTaskActorAdapter sends messaging actions through the Gateway boundary.
type chatTaskActorAdapter struct {
contract gateway.ChatContract
}
func (a chatTaskActorAdapter) ApplyChatTaskAction(
ctx context.Context, identity *string, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
if a.contract == nil {
return gateway.TaskActionResult{}, gateway.ErrChatCapabilityUnavailable
}
if identity == nil {
return a.contract.ApplyOperatorTaskAction(ctx, taskID, action)
}
return a.contract.ApplyTaskAction(ctx, *identity, taskID, action)
}
func chatTaskProfiles(cfg config.Config) ([]gateway.TaskProfile, string) {
if len(cfg.Identities) > 0 {
profiles := make([]gateway.TaskProfile, 0, len(cfg.Identities))
for _, identity := range cfg.Identities {
if len(identity.Repos) == 0 {
continue
}
profiles = append(profiles, newChatTaskProfile(identity.Name, identity.Repos))
}
if len(profiles) == 0 {
return nil, ""
}
return profiles, profiles[0].Identity
}
if len(cfg.Repos) == 0 {
return nil, ""
}
return []gateway.TaskProfile{newChatTaskProfile("", cfg.Repos)}, ""
}
func newChatTaskProfile(identity string, repos []config.Repo) gateway.TaskProfile {
allowed := make([]string, 0, len(repos))
for _, repo := range repos {
allowed = append(allowed, repo.Owner+"/"+repo.Name)
}
return gateway.TaskProfile{
Identity: identity,
DefaultOwner: repos[0].Owner,
DefaultRepo: repos[0].Name,
Repos: allowed,
}
}
func configureTaskCommands(
router *gateway.Router,
tasks gateway.TaskCreator,
controller gateway.TaskController,
lister gateway.ChatTaskLister,
identity string,
) {
router.Tasks = tasks
router.Controller = controller
router.TaskLister = lister
router.Identity = identity
}
// parseListenAddr splits "host:port" into components, using defaults
// when the input is empty or missing a part.
func parseListenAddr(addr, defaultHost string, defaultPort int) (string, int) {
if addr == "" {
return defaultHost, defaultPort
}
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return defaultHost, defaultPort
}
port, err := strconv.Atoi(portStr)
if err != nil || port < 0 {
return host, defaultPort
}
return host, port
}
// sessionKey builds a deterministic session identifier from a gateway
// message's routing fields. Platform + channel + thread uniquely identify
// a conversation for session persistence and history retrieval.
func executionProviders(cfg config.Config) map[string]agentexec.Provider {
return agentexec.ProvidersFromConfig(cfg.Providers)
}
// subscribeSystemLogs subscribes to every task's system log subject at once.
// A sandboxed container's own stderr disappears at AutoRemove; archie-agent
// ships it here instead (agentexec.SubjectForSystem), and this is where it
// lands: one wildcard subscription demuxed by taskID and routed through
// taskLogs, which is opened for a task's duration in Daemon.process, so a
// message for a task not currently open there -- late, duplicate, or from
// an attempt this instance never dispatched -- is expected and silently
// dropped rather than treated as an error.
func subscribeSystemLogs(nc *natsio.Conn, taskLogs *logging.TaskRegistry, log *slog.Logger) (unsubscribe func(), err error) {
sub, err := nc.Subscribe(agentexec.SubjectSystemWildcard, func(msg *natsio.Msg) {
taskID, ok := agentexec.TaskIDFromSystemSubject(msg.Subject)
if !ok {
log.Warn("system log message on unparseable subject", "subject", msg.Subject)
return
}
var entry logging.Entry
if err := json.Unmarshal(msg.Data, &entry); err != nil {
log.Warn("system log message undecodable", "task", taskID, "err", err)
return
}
// The NATS callback has no context of its own; the write is an append to
// an already-open sink, so there is nothing to cancel.
taskLogs.Write(context.Background(), taskID, entry)
})
if err != nil {
return nil, err
}
return func() {
if err := sub.Unsubscribe(); err != nil {
log.Warn("system log unsubscribe failed", "err", err)
}
}, nil
}
// subscribeAgentEvents subscribes to every task's events subject at once and
// republishes each decoded event on bus. An archie-agent worker's
// agentexec.ForwardTaskEvents ships a task's workflow events (stage
// progress, outcome, parking) here because that worker's own *events.Bus is
// in-process and invisible to the daemon; this is the other half of the
// bridge, landing them on bus so persistAndBroadcastEvents -- the single
// choke point that inserts into the SQLite events table and fans out over
// SSE -- treats them exactly like every other daemon-observed event. Mirrors
// subscribeSystemLogs's demux-by-taskID shape.
func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (unsubscribe func(), err error) {
sub, err := nc.Subscribe(agentexec.SubjectEventsWildcard, func(msg *natsio.Msg) {
taskID, ok := agentexec.TaskIDFromEventsSubject(msg.Subject)
if !ok {
log.Warn("task event message on unparseable subject", "subject", msg.Subject)
return
}
var e events.Event
if err := json.Unmarshal(msg.Data, &e); err != nil {
log.Warn("task event message undecodable", "task", taskID, "err", err)
return
}
bus.Publish(e)
})
if err != nil {
return nil, err
}
if err := nc.Flush(); err != nil {
if cleanupErr := sub.Unsubscribe(); cleanupErr != nil {
log.Warn("task event subscription cleanup failed after flush failure", "err", cleanupErr)
}
return nil, fmt.Errorf("flush task event subscription: %w", err)
}
return func() {
if err := sub.Unsubscribe(); err != nil {
log.Warn("task event unsubscribe failed", "err", err)
}
}, nil
}
// registerTaskRPCServers subscribes the forgerpc/worktreerpc handlers on nc
// so an archie-agent container (which holds no forge token, or push
// credential) can proxy those operations back to archied. The returned func
// unsubscribes all of them. The agent's store calls are NOT proxied here: they
// go over gRPC to the State Store (docs/prds/state-store-contract.md §12 step
// 4), so the legacy NATS storerpc registration is deleted.
//
// Forge and worktree are identity-scoped: the root servers answer the root
// (identity-less) subjects for single-identity deployments and root-owned
// tasks, and one server pair per identity answers that identity's scoped
// subjects so a container-mode task owned by a non-root identity has its RPC
// calls served by its own forge client and worktree manager.
func registerTaskRPCServers(nc *natsio.Conn, forgeClient forge.Forge, trees *worktree.Manager, identities []*daemon.IdentityRunner, grants *worktreerpc.Grants, log *slog.Logger) (unsubscribe func(), err error) {
unsubs := make([]func(), 0, 2+2*len(identities))
unsubAll := func() {
for _, u := range unsubs {
u()
}
}
registerForge := func(fg forge.Forge, identity string) error {
srv := &forgerpc.Server{Forge: fg, Log: log.With("rpc_identity", identity)}
u, err := srv.RegisterFor(nc, identity)
if err != nil {
return fmt.Errorf("register forgerpc%s: %w", identitySuffix(identity), err)
}
unsubs = append(unsubs, u)
return nil
}
registerTrees := func(mgr *worktree.Manager, identity string) error {
srv := &worktreerpc.Server{Trees: mgr, Grants: grants, Log: log.With("rpc_identity", identity)}
u, err := srv.RegisterFor(nc, identity)
if err != nil {
return fmt.Errorf("register worktreerpc%s: %w", identitySuffix(identity), err)
}
unsubs = append(unsubs, u)
return nil
}
// Root (identity-less) forge and worktree servers.
if err := registerForge(forgeClient, ""); err != nil {
unsubAll()
return nil, err
}
if err := registerTrees(trees, ""); err != nil {
unsubAll()
return nil, err
}
// One forge/worktree server pair per identity, on identity-scoped
// subjects.
for _, id := range identities {
if err := registerForge(id.Forge, id.Name); err != nil {
unsubAll()
return nil, err
}
if err := registerTrees(id.Trees, id.Name); err != nil {
unsubAll()
return nil, err
}
}
return unsubAll, nil
}
// identitySuffix renders a log suffix for an identity-scoped registration,
// empty for the root set.
func identitySuffix(identity string) string {
if identity == "" {
return ""
}
return " (" + identity + ")"
}
func configuredNATSToken(cfg config.NATSConfig, getenv func(string) string) (string, error) {
if cfg.TokenEnv == "" {
return "", nil
}
token := getenv(cfg.TokenEnv)
if token == "" {
return "", fmt.Errorf("%s is required when nats.token_env is configured", cfg.TokenEnv)
}
return token, nil
}
func configHome() string {
if x := os.Getenv("XDG_CONFIG_HOME"); x != "" {
return x
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".config")
}
// updateReportPath is where the update watchdog leaves the phase-2 outcome
// of an update for this identity to relay on its next launch. The identity is
// hashed so multiple identities sharing one daemon (see
// docs/architecture/identity.md) never collide.
func updateReportPath(workDir, identity string) string {
identityHash := sha256.Sum256([]byte(identity))
return filepath.Join(
workDir,
fmt.Sprintf("update-report-%x.json", identityHash[:8]),
)
}
// safePluginInfo calls Name() and Version() on a plugin, recovering from
// panics. A panicking plugin must not crash the daemon at startup.
func safePluginInfo(p plugin.Plugin) (name, version string) {
defer func() {
if r := recover(); r != nil {
name = "(panic)"
version = "(panic)"
}
}()
return p.Name(), p.Version()
}
// startContainers brings up the mandatory autonomous-worker pool and storage
// backend, returning a degraded nil pool when Docker is unavailable.
//
// Failure here degrades rather than aborting: the native interactive agent and
// dashboard remain useful without Docker, while autonomous tasks park because
// there is deliberately no host execution fallback.
func startContainers(
ctx context.Context,
cfg config.Config,
log *slog.Logger,
) (*container.Pool, storage.Backend, func()) {
noop := func() {}
// Single Docker client shared between pool and storage backend.
dockerCli, err := client.New(client.FromEnv)
if err != nil {
log.Error("autonomous workflows unavailable: docker client unavailable", "err", err)
return nil, nil, noop
}
closeDocker := func() {
if err := dockerCli.Close(); err != nil {
log.Warn("docker client close failed", "err", err)
}
}
pool, err := container.NewPool(ctx, container.Config{
Image: cfg.Containers.Image,
MaxConcurrency: cfg.Containers.MaxConcurrency,
MaxUptime: cfg.Containers.MaxUptime.Std(),
PullPolicy: cfg.Containers.PullPolicy,
Network: cfg.Containers.Network,
DockerClient: dockerCli,
// Only the embedded broker binds a discovered host gateway. The
// standalone State Store uses its configured, container-reachable target.
RequireHostGateway: cfg.NATS.Mode == config.NATSModeEmbedded,
}, log)
if err != nil {
// A missing image is recoverable by hand. The daemon sends no registry
// credentials on pull (internal/container/pool.go), so a private
// registry always needs the operator's CLI to fetch it first.
log.Error("autonomous workflows unavailable: container pool unavailable", "err", err,
"hint", "run `docker compose pull agent` (or `build agent`) so the image is present locally")
return nil, storage.NewDockerBackend(dockerCli), closeDocker
}
// contextcheck: Pool.Close takes no context by design -- it is a shutdown
// path that must run to completion after ctx is already cancelled.
//nolint:contextcheck
return pool, storage.NewDockerBackend(dockerCli), func() {
if err := pool.Close(); err != nil {
log.Warn("container pool close failed", "err", err)
}
closeDocker()
}
}