Commit Graph
26 Commits
Author SHA1 Message Date
sam 3a0dfa924d refactor(state-store): cut daemon/Gateway over to the remote State Store (archie-core-8cda.4.6) (#774)
* refactor(state-store): delete NATS storerpc; agent store is gRPC-only (archie-core-8cda.4.6)

The agent is fully on the gRPC State Store contract, so the legacy NATS
storerpc path is dead (docs/prds/state-store-contract.md §12 step 4):
- delete internal/storerpc (Server, Client, subjects) and its tests
- drop the storerpc registration from registerTaskRPCServers and the
  now-unused store param
- make the agent transport's State Store URL required and Store() return
  only the gRPC staterpc.Client (no NATS fallback)
- rework agentworker/agent transport tests to back the store with a real
  gRPC State Store server instead of the deleted NATS storerpc server

The agent binary now fails fast when STATE_STORE_URL is absent. Agent store
calls (workflow.Store) go over gRPC to the archie-state-store service.

* refactor(state-store): delete daemon/gateway in-process store ownership (archie-core-8cda.4.6)

The daemon and gateway no longer open archie.db in-process: the single SQLite
file is owned by the standalone archie-state-store process, and both consumers
dial its gRPC State StateStore contract (docs/prds/state-store-contract.md
§12 step 7, no dual-store ownership).

- openStores no longer opens the production task store or seeds b.st; it only
  wires secrets/forge and the gateway conversation store
- openStateStoreAdapter now requires [services.state].target (the old local
  default is deleted) and resolves b.stateStore as the remote *staterpc.Client
- delete the in-process startStateStoreServer (the multiplexed gRPC server and
  its per-task bearer-token registry) from the daemon composition
- RunGateway now resolves the same remote State Store adapter; its session
  SQLite stays Gateway-owned and untouched
- daemon.ConnectedStateStore carries the configured target plus the resolved
  bearer token, which containerEnv injects as STATE_STORE_URL / STATE_STORE_TOKEN
  so archie-agent authenticates to the same remote service
- readiness store probe reads b.stateStore

PRD-consistent choice (noted): with the in-process server gone, per-task token
generation is removed; the daemon/gateway/agent all present the single
[services.state].target_token (or STATE_STORE_TOKEN secret) that the standalone
store validates.

* docs(webui): require [services.state].target in config and deployment templates (archie-core-8cda.4.6)

After the in-process store path is deleted, archied and archie-gateway dial the
standalone archie-state-store gRPC service via [services.state].target and never
open archie.db themselves (docs/prds/state-store-contract.md §12 step 7).

- config.example.toml documents [services.state].target as required, with the
  loopback vs Docker-bridge gateway + target_token rule
- deployment templates set [services.state] per topology: bridge gateway +
  token for container-mode agents, loopback for host-only
- deployments/README.md and systemd-user-service.md describe start commands
  for both topologies and drop the stale "not yet consumed by the daemon" note

* style: gofumpt alignment for State Store daemon literal; appease noctx/staticcheck (archie-core-8cda.4.6)

* docs(state-store): refresh stale in-process references post-cutover (archie-core-8cda.4.6)
2026-09-07 05:06:12 +10:00
sam 2b102b04a2 feat(state-store): generalize storerpc as the State Store gRPC contract (archie-core-8cda.4.2) (#770)
* feat(state-store): generalize storerpc as the State Store gRPC contract

Implements archie-core-8cda.4.2 against docs/prds/state-store-contract.md
rev. 2c: generate protobuf/gRPC client and server adapters for every
ratified store contract (proto/state/v1/state.proto, 40 RPCs, one
StateStoreService), add internal/infrastructure/staterpc with a bufconn
conformance suite exercising both local and remote adapters, serve the
service in-process (bridge address + mandatory per-task bearer token when
agent containers exist, loopback-only otherwise), and flip archie-agent's
workflow.Store to a long-lived gRPC client when the daemon injects
STATE_STORE_URL/STATE_STORE_TOKEN (falling back to the legacy NATS
storerpc path otherwise -- one agent process is never both).

Also drops the *sql.Tx parameter from store.BindingDispatcher.RecordDispatch
(a required wire-blocker fix: a transaction cannot cross a gRPC boundary,
and production always passed nil).

fix(store): drop RecordDispatch's unusable *sql.Tx parameter
feat(config): add services.state contract-adapter selector

* fix(state-store): apply no-mistakes review decisions

- Drop StreamTokenInterceptor (unused; the State Store service has no
  streaming RPCs and nothing calls it).
- Make StateStoreTokens.Validate compare tokens in constant time
  (crypto/subtle) per the auto-fix hardening.ing finding.
- Amend config.example.toml / config.Services.State doc text so it frames
  [services.state].target as the ratified surface consumed by the upcoming
  standalone archie-state-store binary (.4.3), not active today.
2026-09-07 03:01:33 +10:00
sam d3da153768 refactor(agentexec): remove legacy execution paths
Autonomous workflows now have exactly one production boundary: a task-scoped archie-agent receives a full-task core-NATS request and runs the worker-local stage loop. The legacy [agent] section remains decode-only for migration; it no longer selects runtime behavior.
2026-08-24 14:56:57 +10:00
sam d28ca099c5 refactor(agent): move worker runtime into application layer
cmd/archie-agent used to own worker construction, NATS lifecycle, task execution, MCP setup, and workflow wiring. It now owns process input only and invokes internal/app/agentworker, while transport-specific NATS, boot-brief, and git-safety mechanics live under infrastructure.
2026-08-15 00:43:12 +10:00
sam 9ef6f41910 fix(agent): route git safe.directory setup through markWorktreeSafe
The dubious-ownership fix landed twice: markWorktreeSafe in gitsafe.go
and an inline exec.Command block in main.go, both configuring the same
safe.directory on every start. Two setup paths for one invariant means a
later change to either one silently disagrees with the other.

Keep the tested helper and drop the inline block. markWorktreeSafe also
skips the call when /data/worktree is not a mounted directory, so
running archie-agent directly on a host no longer writes to the
operator's own ~/.gitconfig for a path that was never mounted.

The new test parses main.go and fails on more than one setup path, so a
future re-addition of an inline block is caught rather than merged.

Refs #468
2026-08-14 02:35:49 +10:00
sam 62cf76ad40 feat(agent): mark the mounted worktree as a git safe directory 2026-08-14 01:59:56 +10:00
sam 4f4e151ff8 fix(agent): resolve git dubious-ownership in sandbox containers
Agent containers bind-mount the worktree from the host at
/data/worktree, where the owning UID differs from the container
user's UID. Git refuses to operate in such directories, so every
gate command that calls the Go toolchain (go build/test/vet) fails
with 'fatal: detected dubious ownership in repository' before any
real work begins.

Add 'git config --global --add safe.directory /data/worktree' at
archie-agent startup so all subsequent git-spawned operations
(baseline gate, build gate, agent shell tool invocations) work
correctly. Logs a warning if git is unavailable rather than
failing — the agent remains usable for repos with no gate config.
2026-08-12 14:37:37 +10:00
sam 53da52ecd1 feat(agentexec): publish agent-side logs to the task's system subject
Part of #453 (task-observability epic #450). archie-agent logged to
os.Stderr only, and its container is created with AutoRemove: true
(internal/container/pool.go), so all of it disappeared the moment a
task's container exited -- there was no way to see why, say, a gate
command failed inside one.

Adds agentexec.SystemLogHandler: a slog.Handler that tees to whatever
it wraps (kept for an operator attached to a live container) and
additionally publishes each record, JSON-encoded as a logging.Entry,
to SubjectForSystem(taskID) -- a subject that already existed,
documented for exactly this ("log dumps, health... observability"),
with zero publishers anywhere in the codebase.

cmd/archie-agent/main.go wires it in only when this container was
spawned for one specific task (bootTaskID / .git/task.json present);
shared queue-group mode serves many unrelated tasks per process, so
there's no single task subject to ship to and keeps the stderr-only
logger.

Building this surfaced a real pre-existing bug: FeedHandler's attr
flattening applied the group chain active at Handle-time to *all*
accumulated attrs, including ones added via WithAttrs before a later
WithGroup call -- nesting them under a group they were never
actually inside, contrary to slog's own documented Handler contract.
It went unnoticed because nothing in the codebase called WithGroup
until this change needed to. Extracting the shared flattening logic
into exported FlattenAttrs/PrefixAttrs (so SystemLogHandler doesn't
duplicate it) is what surfaced it; fixed in the same change since I
was the one making it public API.

Docs on the wire format's own trap for the daemon-side consumer
(#454, not yet written): the published bytes are a marshaled
logging.Entry, meant for json.Unmarshal, not logging.decode() --
decode() parses raw slog JSON *log lines* off disk, a different and
incompatible shape. See the doc comment on SystemLogHandler.
2026-08-09 16:49:39 +10:00
sam 308666b410 chore: remove legacy terminology and dead code
- Reword docs and comments to drop vague "legacy" qualifiers where they no longer describe deprecation status
- Remove unused code: RecentEvents, MessageEvent.ToLegacy, index setState, stderr redaction tool, telegramOnlyCommands
- Delete or comment out tests covering removed or superseded behavior
2026-08-06 22:55:26 +10:00
sam 4c0a06df6d fix(container): write the task boot brief under .git
WriteTaskJSON wrote task.json to the worktree root -- the same worktree
the agent commits from. CommitAll stages with go-git's All option, and
go-git's Add does not honour .gitignore or .git/info/exclude, so the
brief was swept into the agent's commit and pushed onto every task
branch. That is how a task.json for issue #57 ended up committed in
the repo root.

This is the identical failure the prepared sentinel hit; worktree.go
already documents the fix. Nothing under .git can ever be tracked, so
put the brief there rather than papering over it with an exclude.
2026-07-31 01:13:08 +10:00
sam d3dd06d48f Merge remote-tracking branch 'origin/feat/75-add-mcp-client-capabilities-to-archied-and-archie-agent'
# Conflicts:
#	cmd/archie-agent/main.go
#	cmd/archied/main.go
#	cmd/archied/main_test.go
#	internal/agentexec/nats.go
#	internal/config/config.go
#	internal/tools/budget_test.go
#	internal/tools/dispatch_test.go
#	internal/tools/mcp/transport_sse.go
2026-07-29 23:19:36 +10:00
sam 9d5040fd65 refactor: add internal/eventbus as the broker-neutral messaging contract
dependencies-and-contracts.md rule 1 says domains must not import
internal/infrastructure. internal/daemon and internal/agentexec both did,
and for exactly the thing the doc carves out: "internal/eventbus is an
approved shared application contract ... it MUST remain broker-neutral."

The Publisher/Consumer/Requester interfaces existed but lived inside the
NATS package, so a caller could depend on the behaviour yet still had to
import the implementation to name it. They now live in internal/eventbus,
and nats.Client asserts against eventbus.Bus.

The larger violation was ownership of meaning. The doc says "message schemas
stay with their owning domains; the event bus transports messages, it does
not own their meaning." The bus exported TaskEnvelope and a PublishTask
method, so the transport knew what a unit of work was, and it exported the
archie.agent.* subject helpers, so it also owned the agent protocol.

  - TaskEnvelope, its routing Kind, the label vocabulary and the task
    subjects move to internal/domain/workintake, which encodes and decodes
    its own bytes. This starts internal/domain/ per organisation.md.
  - The agent request/response/system subjects move to internal/agentexec,
    which defines what those messages mean.
  - internal/workflow keeps only the kind-to-registry mapping; the label
    table stays single and lives with the domain that reads forge issues.
  - The bus now carries opaque payloads on plain-string subjects.

Consumers declare the smallest interface they need rather than taking the
whole Bus: daemon.TaskBus is publish-unique/fetch/request, agentexec.
RequestBus is publish-request/reply-inbox, and archie-agent's stageBus is
fetch/respond. None can reach what it does not use.

Two defects this surfaced:

  - archie-agent declared its own JetStream stream with a second copy of the
    name, subjects, retention, dedup window, MaxDeliver and TTLs that
    nats.Connect already sets -- two definitions of one stream, free to
    diverge. Config now takes Subjects and FilterSubject from composition,
    which is what let the agent use the shared client and delete its
    hand-rolled setup.
  - Replying to a request needs core NATS, not the JetStream publish path:
    a reply inbox is ephemeral and belongs to no stream, so a durable
    publish to it fails. The old code hid this by using the raw connection.
    The contract now distinguishes Respond from Publish. The agentexec
    round-trip test caught it after I had made the same mistake in
    archie-agent.

Also translated the SDK's ErrNoResponders into eventbus.ErrNoResponders, so
the daemon's taskrun retry no longer imports the NATS SDK to name a
transient condition. The SDK is now confined to the nats package, the *rpc
packages (themselves NATS infrastructure), and cmd/*.

The agentexec test fake previously hand-rolled a JetStream consumer; it now
drains the client's own consumer, which is both closer to production and
avoids conflicting consumers on a work-queue stream.

Verified: go build, go vet, gofmt clean; full test suite passes.
2026-07-29 11:40:24 +10:00
sam 2d082eef89 Merge branch 'crew/lint6' 2026-07-29 10:37:52 +10:00
sam 492ca209f9 refactor(nats): rebuild as infrastructure/eventbus/nats with real boundaries
Relocating internal/nats as-is would have cemented its problems into the
approved layout, so this is a rewrite rather than a move.

What was wrong:
- Conn() *nats.Conn, PublishMsg(*nats.Msg) and Fetch() jetstream.Msg pushed
  SDK types into all four consumers, so the broker was not replaceable --
  the opposite of what dependencies-and-contracts.md requires.
- PublishTask took seven positional parameters, six of them strings, where a
  transposed argument was a silent bug.
- Labels travelled as a comma-separated string and were re-split on every
  publish.
- Fetch returned (nil, nil) for 'no message', which every caller had to
  remember to special-case.
- The logger field was stored and never used.
- Stream name, consumer name and every timeout were hardcoded constants.
- Errors were inconsistently wrapped; several paths returned bare errors.
- Connect repeated nc.Close() on each failure branch.

What replaces it:
- One concern per file: config, errors, subjects, message, client,
  publisher, consumer.
- Publisher/Consumer/Requester interfaces with compile-time assertions, so
  callers depend on behaviour and can be faked without a broker.
- A Message wrapper keeps jetstream types behind the boundary; consumers no
  longer import the NATS SDK at all.
- TaskEnvelope with []string labels and JSON methods preserving the
  comma-separated wire form for already-queued messages.
- Sentinel errors (ErrNoMessage, ErrNotConnected, ErrNoReplyAddress,
  ErrInvalidConfig) and %w wrapping with operation context throughout.
- Config with validation and defaults; a single deferred cleanup in Connect.
- CoreConn() as the one documented escape hatch, for the *rpc packages that
  are themselves NATS infrastructure.

Consumers migrated: cmd/archied, cmd/archie-agent, internal/daemon,
internal/agentexec. Behaviour, subjects and wire format unchanged.
2026-07-29 10:19:09 +10:00
sam 712388dc6c fix: Phase 4 structural refactor — reduce lint findings from 28 to 5
cyclop (5→0): extract subcommand/case bodies in codesearch,
subprocess, Telegram, indexing
funlen (5→3): extract memory action handlers, tool provider startup
gocognit (7→2): extract config finalize/loadDirInto helpers, release
announcer, capture tool validation, Telegram gateway (200→108),
archie-agent main loop (35→0)
nestif (8→0): extract identity validation, container validation,
conf.d scanning, email multipart parsing, Telegram model/update
parsing, build-no-changes closure
interfacebloat (3→0): split Forge/IssueForge/PRForge/RepoForge,
SessionStore/SessionLifecycle/MessageHistory,
TaskStore/TaskLifecycle/TaskQueries/TaskEvents

Remaining: daemon process, workflow Feasibility/TDD/AgentStage,
archied main.go run (108→30 remaining). These require deeper
refactoring best done per-function in follow-up beads.

Updated contract tests and archied wiring tests to check both
main.go and the new telegram_setup.go.
2026-07-29 10:15:22 +10:00
archie 5f964030c5 feat: add MCP client capabilities to archied and archie-agent (archie)
Implements #75
2026-07-26 19:51:36 +00:00
sam f6d51416f0 chore: replace 607 em-dashes with double hyphens project-wide
Includes MCP crash-after-init test fix (crash moved from handle() to serve()
entry point so transport sees immediate subprocess death).
2026-07-26 09:53:33 +10:00
sam 9df02f2b60 fix: golangci-lint baseline to zero findings (39→0)
19 files touched. All fixes are in code — no lint configuration
weakened:
- Added unchecked error handling in defer cleanup paths
- Removed dead variables and unused functions
- Added missing imports (io in gitea.go)
- Simplified conditions (TrimSuffix, De Morgan, slices.Contains)

Also fixes JetStream TempDir teardown race (archie-core-340):
t.Cleanup(srv.Shutdown) now registers after t.TempDir() so
server shutdown (including JetStream files) completes before
temp dir removal. Added srv.WaitForShutdown() for deterministic
cleanup ordering.

Closes: archie-core-756, archie-core-340
2026-07-25 23:51:13 +10:00
sam 75f237d1ad feat: daemon hands off tasks to archie-agent in sandboxed mode (archie-core-5zh.8)
daemon.process() branches on ContainerPool != nil: sandboxed tasks publish
a taskrun.Request to archie.taskrun.<id> and await the response via the
new runViaAgent method, instead of running workflow.Route/workflow.Run
locally. Non-container mode is unchanged. Every durable side effect
(Store, Forge, git push) already landed via the storerpc/forgerpc/
worktreerpc proxies during archie-agent's run by the time runViaAgent
returns — it only parks the task itself on transport/setup failure, never
duplicating a terminal state archie-agent's own workflow.Run already
recorded.

Also fixes a real correctness gap: with concurrent multi-task dispatch
(archie-core-u64/g1l) plus containerized archie-agent, a shared queue-group
subscription could let one container answer a sibling's taskrun message
while having a *different* task's worktree mounted. archie-agent now reads
its boot-time task.json and subscribes to its own exact per-task subject
when present, falling back to the shared queue group only in dev/pool mode
(no task.json).

Adds agentexec.ProvidersFromConfig, deduped from cmd/archied's former
executionProviders.

Closes the archie-core-5zh epic: archie-agent runs an entire task's
workflow per invocation instead of one stage per round trip, with all
credentials staying daemon-side throughout.
2026-07-24 09:14:56 +10:00
sam 1eee983681 feat: archie-agent runs a full task's workflow itself (archie-core-5zh.7)
Add internal/taskrun (Request/Response wire types) and
cmd/archie-agent/taskrun.go: runTask builds a workflow.Registry from the
container's own bind-mounted worktree, routes and runs the task's entire
workflow via workflow.Route/workflow.Run, using storerpc.Client/
forgerpc.Client for Store/Forge and a new hybridTrees that splits
Prepare/Push (proxied over worktreerpc — network ops needing the daemon's
credential) from CommitAll/Diff/ChangedFiles/ChangedLines (local git
against the mount).

Add config.TaskConfig.ToConfig() to rebuild a usable Config from the
curated payload, and storage.WorktreeMountDir (/data/worktree) — critical
fix: hybridTrees.Prepare discards the RPC response's host-side directory
and returns the container's fixed local mount path instead, since archied
and archie-agent see the same files at different paths.

Wired a queue-grouped core-NATS subscription on archie.taskrun.> in
cmd/archie-agent/main.go alongside the existing per-stage consumer, so
this is reachable in the running binary. End-to-end test drives the real
"bootstrap" workflow (no LLM) through real storerpc/forgerpc/worktreerpc
servers and a real local git remote — registry build, route, prepare,
commit, push, PR creation, and confirms the authoritative task state
lands in archied's store via RPC, not just in-memory.

archie-core-5zh.8 (daemon.go handoff) is unblocked.
2026-07-24 09:08:19 +10:00
sam 4be28e0e48 feat: optional NATS token authentication (archie-core-l1q)
Add token_env to [nats] config, resolved and validated at daemon startup
(fails early if configured but the named env var is unset). Container
workers get NATS_URL/NATS_TOKEN; archie-agent honors both while CLI-supplied
URL still takes precedence. Anonymous auth remains the default for
single-node deployments.

Unblocks archie-core-5zh (promote archie-agent to per-task process).
2026-07-24 07:51:06 +10:00
sam f8df051b19 feat: bounded concurrent task dispatch in daemon (archie-core-u64)
Daemon previously processed one task at a time. Add bounded concurrent
dispatch for SQLite and NATS agent modes, reusing [containers].max_concurrency
(0 = unlimited). Same-repository tasks stay FIFO-serialized to avoid worktree
conflicts; different repositories now run concurrently.

Unblocks archie-core-l1q (NATS transport) and archie-core-g1l
(per-repo allow_concurrent override).
2026-07-24 07:42:13 +10:00
sam ce9ce050ed feat: close Gap 1 — per-task agent (multi-stage batch execution)
HandleMessage now supports two modes:
- Single-stage (Request only): backward compatible, no Workflow set
- Per-task batch (Workflow + Stages): runs all stages sequentially,
  accumulates tokens/iterations/notes, sets TaskCompleted on success

New fields:
- AgentRequestMessage.Stages []Request — batch of agent stages
- AgentResponseEnvelope.TaskCompleted bool — true when batch done

RunnerFactory injection for testability — HandleMessage accepts a
factory function. DefaultRunnerFactory creates InProcessRunner.
Tests use mockRunner.

runStages() executes each stage, stops on first failure, aggregates
results. Combined summary uses "[stage] summary" format.
2026-07-22 03:20:37 +10:00
sam e8ffa20b33 test: rewrite regression tests as behavioral (not structural)
Replaces field-existence checks with runtime behavior verification:

Gap 1 (per-task agent): FAILING
  TestHandleMessageReadsWorkflowField verifies HandleMessage produces
  different results when Workflow is set vs. unset. Currently identical
  — HandleMessage ignores the Workflow field. Must run full multi-stage
  workflow per PRD section 1.

Gap 3 (response/system split): PASSING
  TestHandleMessageRoutesSystemMessagesSeparately verifies Channel
  echoes from request to response. HandleMessage now reads input Channel
  and sets it on the response envelope. Subject functions verified
  distinct.

Gap 5 (daemon review): PASSING
  TestReviewResultBlocksOnResultWhenRejected verifies ReviewResult
  hook gates OnResult. Error blocks — OnResult never called. Nil
  allows — OnResult called normally.

Agent processing extracted into agentexec.HandleMessage for testability.
cmd/archie-agent delegates to it.
2026-07-22 03:13:57 +10:00
sam 8c4bb1ef1d feat: promote archie-agent to NATS-connected per-task worker
Replaces stdin/stdout subprocess transport with NATS JetStream
request-reply pattern. The Runner interface and workflow orchestration
are unchanged.

New NATSRunner (implements Runner):
- Publishes AgentRequestMessage to JetStream with X-Archie-Reply header
- Blocks on core NATS inbox subscription for response
- Same Run(ctx, workspace, req) (Result, error) contract

Rewritten archie-agent (cmd/archie-agent):
- Long-running NATS-connected process (was 28-line stdin/stdout)
- Pull-consumes from ARCHIE_TASKS with archie.agent.> filter
- Builds InProcessRunner, executes agent loop, replies to inbox
- Graceful shutdown via signal handling

Extended internal/nats:
- SubjectAgentWildcard, SubjectForAgentRequest, ReplyHeader
- Conn() accessor, NewReplyInbox(), PublishMsg() for JetStream
- Stream subjects extended to ["archie.task.>", "archie.agent.>"]

Config: "nats" added as valid agent.mode alongside inprocess/subprocess
Tests: NATSRunner round-trip with embedded NATS server + handler
2026-07-22 02:13:01 +10:00
sam 86339b4d0d feat: add subprocess agent runner 2026-07-21 23:21:24 +10:00