Commit Graph
89 Commits
Author SHA1 Message Date
sam ff27bd03fe fix(daemon): record every park reason in the attempt's own log
An operator who asks "why did task 1 attempt 3 park?" and downloads that
attempt's log got a zero-byte file, because nothing daemon-side wrote to a
task log at all: the container's system-log subscription was the only
writer, so an attempt that parked before any container produced output --
a worktree prepare failure, an unavailable worker, a taskrun error -- left
the file the sink had created empty and the reason only in the daemon-wide
log.

Both park paths now write the reason into that attempt's sink. The entry is
written after the guarded transition lands, so a park another actor won
does not leave a log claiming an outcome the task board contradicts -- the
same race the parked event is already withheld for.
2026-09-18 01:49:49 +10:00
sam 0b3dc6c01f refactor(forge): delete the unwired RepliesAfter surface
DELETE: IssueForge.RepliesAfter and its Reply type had no production caller --
the waiting_human status exists and is reachable, but automatic detection of a
human reply never landed, so the intended poller was never built. Neither
implementation paginated either (both read one page of 50), so the method
would have been wrong if wired as-is.

The manual path is untouched: waiting_human remains reachable and an operator
requeues through the existing task-action flow. Removing the interface method
also removes seven test fakes that existed only to satisfy it.

No behavioural test accompanies this: a pure deletion has no assertion to
make fail, and the compiler enforces completeness across every implementation.
2026-09-15 16:54:16 +10:00
sam 2b84ec2989 fix(daemon): forward configured MCP servers to task agents
WIRE: taskrun.Request.MCPServers is documented as the channel for MCP server
definitions the agent should construct, and the archie-agent worker consumes
it (task_execution.go startMCPProviders). The daemon's request constructor
dropped the field in a refactor, so configured MCP servers never reached a
task container. Restore it from d.configFor(task).Tools.MCPServers.
2026-09-15 13:01:53 +10:00
sam 16d331a16e refactor(daemon): remove unreachable SQLite poll/drain path
DELETE: NATS startup is mandatory (config.NATSConfig documents "there is no
broker-off execution mode"), so Daemon.Tasks is never nil in production and
pollSQLite/drainSQLite are unreachable. Remove them and their d.Tasks==nil
call sites, and correct the Tasks field comment.
2026-09-15 12:57:54 +10:00
sam eaa58dfe73 fix(daemon): guard binding dispatch loop against nil dispatcher/creator
BindingDispatcher and BindingTaskCreator are documented "optional: nil
disables the dispatch loop", same as Bindings, but dispatchBindings only
checked Bindings before dereferencing the other two. Any composition that
wires Bindings without also wiring both handles panicked on the first
dispatch cycle.
2026-09-15 04:35:00 +10:00
sam 1f3f54bedd test(archied): pin the wiring these fixes depend on and drop text coupling
Two fresh-context reviews of the preceding five fixes found that the tests were
mostly sound but that three things were not: one harness was coupled to shell
source text, one assertion was coupled to a tool count, and -- worse -- the two
changes carrying the most weight were pinned by nothing at all.

Composition order. review_pr worked only because Run builds the worktree manager
before the gateways; no test observed it. Reverting the order left every test
green while the daemon silently stopped offering review_pr, because the producer
guard then returns nil instead of advertising a broken tool. Pin the order by
source position, matching the existing
TestSetupBackendsRegistersContainerCleanupAfterNATS, since no runtime seam can
see it. methodBody now resolves package-level funcs as well as methods.

Composition wiring. The daemon fix's whole point is that resolved routing
bindings reach the worker, yet nothing verified that buildDaemon puts them on the
daemon: with b.kindWorkflows replaced by nil, only the new test fails and both
the daemon and worker packages stay green. That is the "tested in isolation,
never verified wired" shape this work exists to remove, so pin the hop.

The wire contract itself. taskrun.Request's json tags are the interface between
two binaries, and a same-type round trip cannot see a tag rename. Assert the
emitted keys literally; renaming one now fails with the key list.

Brittleness. selfHostConfig no longer string-matches install.sh's heredoc opener
or assumes the delimiter is EOF, and no longer hand-substitutes a copy of
forge_block's output -- it discovers heredocs by shape and selects the one
declaring [nats], a table the assertions never touch. Verified against four
behaviour-preserving refactors that previously failed: renaming the delimiter,
reordering the redirect, factoring the path into a variable, and <<-. The two
[services.gateway] source greps are gone: defaults.go already supplies that
target, so there was no behaviour to pin. review_pr is asserted present by name
rather than by entry count, so a sibling review tool cannot turn it red.

Also carry the published request's decode error instead of discarding it, so a
payload-shape break reports as itself rather than as an empty routing binding.

Every new test was verified non-vacuous by reintroducing the defect.
2026-09-15 02:18:30 +10:00
sam 669f98a059 fix(daemon): carry kind/label routing bindings to the process that routes
An operator's kind/label -> workflow overrides were decoded, validated and
installed into the DAEMON's package-level state via
workflow.SetKindWorkflows/SetLabelWorkflows -- but workflow.Route's only
production caller is app/agentworker/task_execution.go, in the separate
archie-agent process. The bindings never crossed the boundary, so every
configured override was silently ignored and routing always fell back to the
built-in defaults (bug -> tdd, feature -> feasibility, bootstrap -> bootstrap).

Carry the resolved bindings on taskrun.Request, mirroring how MCPServers already
crosses this boundary, and apply them in the worker before Route is called.
Resolved values are carried rather than file paths, so the worker does not need
the routing files to be readable in its sandbox. nil still means "use the
built-in defaults", so this is backward compatible for any request built by an
older daemon.

routeTask is a named seam for that install-then-route step. It mutates
package-level routing state, which is sound here because each archie-agent
process is task-scoped and ephemeral; if the worker ever served more than one
task that assumption would need revisiting.

Tests are mutation-verified: removing either the two Set calls in routeTask or
the two request fields in runViaAgent reproduces the exact assertion failures
the lane observed red-first, so neither test is vacuous.

Found by an adversarial package sweep (temp tracker: workflow-engine-1,
.local/issue-tracker/).
2026-09-15 02:13:33 +10:00
sam a00c578cb7 refactor(ui): sever the archie-ui binary from every daemon runtime package
Completes the objective deletion gate for the UI Service
(archie-core-8cda.5.6): go list -deps ./cmd/archie-ui now links zero
banned packages -- no modernc.org/sqlite, no internal/store, gateway,
channels, memory, secret, agentexec, tools, skill, yaegiutil, curator,
or the workflow engine. The closure shrinks from 68 to 26 archie-core
packages. Each cut is a producer-side move; no consumer-side defensive
shims.

- Store contracts (TaskStore family, value types, sentinels) moved from
  internal/store to internal/domain/storecontract -- the approved contract
  location per state-store-contract rev. 2d, and NOT internal/contracts:
  that tree is buf generate output and tools/proto.sh check deletes
  hand-written files there. internal/store keeps aliases; sentinel
  message strings are byte-identical and remain the wire contract.
- Chat contracts (ChatContract, sessions, turns, streaming, commands)
  moved from internal/gateway to internal/domain/messaging; gateway keeps
  aliases. ToolCallEvent rendering helpers become gateway functions
  (methods cannot live on alias types).
- Task vocabulary (Task, statuses, mid-run Store, Definition) split into
  internal/domain/workflow/task; the pipeline engine stays in package
  workflow with aliases, so daemon-side callers are unchanged.
- overlay.DeniedKeys moved to internal/infrastructure/configuration:
  webui referenced the constant and that dragged the overlay SQLite
  store in.
- webui.Server's concrete runtime handles become webui-owned view
  interfaces with daemon-side bootstrap adapters: channel lifecycle
  (internal/channels/status), MemoryStatus, CuratorStatus, and a
  SkillCatalog seam replacing the direct skill.DefaultRoots/CatalogRoots
  calls. Each degrades to an empty page when unwired.
- config.SecretRef moved into internal/config (config vocabulary);
  internal/secret keeps an alias and Registry.Resolve absorbs the
  zero-value short-circuit.

Docs: state-store-contract rev. 2d relocation record; ui-service-boundary
deletion gate marked satisfied; ARCHITECTURE.md package map rows.
2026-09-10 03:03:33 +10:00
sam 983ddd7c4b refactor(store): move the producer-owned contracts to internal/contracts/store/v1
The deletion gate for the UI Service (archie-core-8cda.5.6) is objective:
go list -deps from cmd/archie-ui must show no SQL/store implementation.
internal/store's hand-written contract surfaces (TaskStore and its
component interfaces, CaptureStore, MappingStore, BindingStore,
BindingDispatcher, BindingTaskCreator, ConfigSnapshotStore) move to
internal/contracts/store/v1 (package storev1), alongside the value types
they carry (CapturedEvent, ConfigSnapshot, WorkflowStat, StageStat,
DayTokens) and the sentinel errors -- whose canonical message strings are
the wire contract and are byte-identical after the move.

internal/store keeps type aliases, so daemon-side callers (archied, the
daemon, staterpc's server side, taskactions) are unaffected. The
UI-facing packages switch to storev1 directly: webui, archieui,
captureintake, gatewayrpc, and staterpc's client/values -- which drops
internal/store and modernc.org/sqlite from the archie-ui binary's import
closure.

overlay.DeniedKeys moves to internal/infrastructure/configuration for the
same reason: webui referenced the constant and that dragged the overlay
package's SQLite store in.

The chat-contract and remaining runtime-handle decoupling continues under
the same bead.
2026-09-10 03:03:33 +10:00
sam 694aaeb7cd style: apply gofumpt formatting 2026-09-09 10:08:51 +00:00
sam f5414a82a1 fix(state-store): task-scope container credentials, stream large capture lists, validate Update, wire dev's state-store (archie-core-8cda.4.7)
Closes six review findings against .4.6 (PR #775):

- daemon.StateStoreGrantIssuer + staterpc.TaskGrants: containers get a
  per-task credential authorized only for their own Update/Transition/
  InsertEvent, never the daemon's administrative token. Issued before
  Acquire, revoked on Release; fails closed if no issuer is wired.
- StreamCaptures/StreamUndispatchedCaptures: new streaming RPCs so a
  batch of large capture bodies can't exceed gRPC's 4MiB unary cap.
  The original unary RPCs are kept, unmodified (deprecated) rather than
  reshaped, so buf breaking stays green for an in-flight rolling deploy.
- Update rejects a nil Task with InvalidArgument instead of panicking in
  the store layer.
- RequireHostGateway only forces on for embedded NATS, so an externally
  reachable NATS/State Store no longer requires a local Docker bridge.
- Client-side token resolution now matches the server's (target_token,
  then STATE_STORE_TOKEN secret/env).
- task dev now runs archie-state-store (dev:state-store) alongside
  archied/archie-gateway/vite; deployments/dev.toml points them at it.
2026-09-07 13:18:44 +10:00
sam 05529d48d5 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 576e22b554 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 5c0efaceaf refactor(workflow): relocate Task/Status/Source and define workflow.Store (#754)
* refactor(workflow,store): relocate Task/Status/Source and define workflow.Store

Move store.Task, store.Status*/store.Source*, and the 3-method workflow
store interface out of internal/store into internal/domain/workflow as
workflow.Task/workflow.Status/workflow.Source plus a consumer-owned
workflow.Store, superseding store.WorkflowStore. internal/domain/workflow
now imports zero internal/store symbols; internal/store persists the
domain type instead (infrastructure depends on domain), and its Store
satisfies workflow.Store.

Updates every production and test caller of the relocated symbols across
daemon, webui, gateway, agentworker, agenttransport/nats, storerpc,
taskrun, and worktreerpc, and removes TestRecordDispatchViaExplicitTx per
docs/prds/state-store-contract.md (rev. 2c) sections 4 and 12 step 2.

Two workflow-package integration tests that exercise the real *store.Store
move to an external workflow_test package (store_integration_test.go) to
avoid a workflow(test)->store->workflow(prod) import cycle now that store
depends on workflow.

* no-mistakes(document): docs(state-store): mark §4.8 relocation done in state-store-contract
2026-09-07 00:39:26 +10:00
sam ebd2b430dd fix(binding): add Owner/Repo pin, fixing multi-repo dispatch
Root-cause fix for the correctness gap named in archie-core-t2db.8:
resolveBindingRepo refused to dispatch with zero or multiple configured
repos, meaning a multi-repo deployment could never use bindings at all.

- binding.Binding gains optional Owner/Repo fields; Validate rejects
  setting only one (a pin is a complete pair or not a pin at all).
- Persisted as new owner/repo columns (NOT NULL DEFAULT '', additive --
  no migration needed since bindings is a CREATE TABLE IF NOT EXISTS
  with no existing deployment yet).
- resolveBindingRepo now takes the binding: a pinned binding dispatches
  to its own owner/repo unconditionally; an unpinned binding keeps
  today's single-configured-repo fallback (0 or 2+ repos still refuses,
  unchanged -- verified by a dedicated regression test, not just
  assumed preserved).
- Wired through the API request/response shape (create/update accept
  and return owner/repo); no repo-existence validation against config
  added -- smallest workable change, not the named bug.

Red-green throughout: 8 new tests across domain/store/daemon/webui
layers, each proven to fail before the corresponding implementation
step. Zero regressions in existing binding/dispatch test suites.
Dashboard UI to expose this (the other half of t2db.8) is unstarted --
this closes the backend correctness gap only.
2026-09-03 04:38:45 +10:00
sam 5dc3c9895c feat(webui): playbook bindings -- matcher + mapping + workflow, HMAC-gated
Implements archie-core-t2db.4: the runtime-editable binding entity that
turns a captured webhook into an archie task, plus the per-source HMAC
verification at handleCapture that makes t2db.5's 'unauthenticated event
cannot trigger a binding' invariant structurally enforceable.

Captures, mappings and bindings are now separate concerns on the same
single *store.Store; the new BindingStore / BindingDispatcher /
BindingTaskCreator split keeps each interface under the interfacebloat
limit (8 methods).

State machine: draft -> pending_approval -> armed; any edit on an armed
binding drops it back to pending_approval, enforced in SQL via
status='pending_approval' on UPDATE so the rule cannot be bypassed by a
direct status field in the request body. Approve is the only sanctioned
transition into armed (WHERE status='pending_approval' guard).

Overlap: two bindings may not share a source in any status; enforced at
InsertBinding and UpdateBinding (transaction-local SELECT). Approve has
a separate TOCTOU guard so a race between Insert and Approve cannot
// bypass the check.

HMAC at handleCapture: reads X-Hub-Signature-256 (then X-Signature-256)
// fallback, verifies via webhookguard.VerifyHMAC against the binding's
// per-source secret, marks CapturedEvent.Authenticated=true on match.
// Captures with no armed binding, missing signature, or wrong signature
all persist as authenticated=false -- the dispatch loop's
binding.Matcher.Matches gate (requires authenticated) is what stops
them from spawning a task. Two armed bindings for one source returns
409 at capture time as a belt-and-braces TOCTOU guard.

Dispatch loop: added Daemon.dispatchBindings, called from both Cycle
and maintainAndDrain between poll and drain. Walks
captured_events where authenticated=1 AND source IN armed bindings
AND id NOT IN binding_dispatches, runs the binding's matcher, resolves
the mapping, enqueues a chat-style task with binding_id /
// binding_version provenance stamped in the same transaction as the
// row insert. The binding_dispatches ledger (composite PK on
(binding_id, capture_id)) is the at-most-once guarantee across cycles
// and daemon restarts.

Tasks schema migration: binding_id INTEGER NOT NULL DEFAULT 0 +
binding_version INTEGER NOT NULL DEFAULT 0 (taskSchemaVersion bumped
1 -> 2). Existing tasks keep 0 / 0.

Out of scope (documented follow-ups):
- secret encryption at rest (plaintext today)
- full dashboard HTML for the binding editor (CRUD API only this bead)
- per-binding rate limits (existing per-remote-address limit applies)
- binding.Owner / binding.Repo fields (dispatch falls back to the
  single configured repo; multi-repo deployments log and skip)
2026-09-02 23:09:25 +10:00
sam fd014f6a7f fix(daemon): detach terminal state transitions and cleanup from cancelled context
When an operator stopped a running task via chat /stop or the dashboard
Stop button, the task's context was cancelled. Container teardown
correctly completed (as Pool.Release detached its context), but terminal
state recording in Daemon.runViaAgent and worktree cleanup in
Daemon.cleanupTerminalTaskWorktree executed using the same cancelled
context. Consequently, SQLite transactions in store.Transition failed
immediately and errors were discarded, leaving the task row in 'running'
indefinitely until a daemon restart.

Extract parkRunningTask in internal/daemon/daemon.go to perform guarded
state transitions (store.StatusRunning -> store.StatusParked) using a
detached context (context.WithoutCancel) with a bounded 10-second timeout.
Update cleanupTerminalTaskWorktree to also use a detached 10-second
context for looking up the task status. Check transition errors and log
warnings for unexpected database failures while suppressing expected
ErrStaleTransition returns when workers have already completed. Add
comprehensive table-driven regression tests covering task cancellation,
worktree cleanup, and logging behavior.
2026-08-25 01:42:54 +10:00
sam fa7b70225a fix(daemon): clean worktrees on terminal no-change task completion
Tasks completing with BuildNoChanges transitioned directly to StatusMerged
without opening a pull request, bypassing the only production worktree
cleanup path inside reconcilePRs (which only queries StatusPROpen tasks).
As a result, every no-change task leaked a full git clone on disk.

Clean up the identity-correct worktree on terminal non-PR completions:
- In daemon.process, invoke cleanupTerminalTaskWorktree using the task's
  identity-resolved worktree manager when the task reaches a terminal
  status (Merged/Rejected/ClosedWontDo) with PRNumber == 0.
- Ensure parked tasks and open-PR tasks retain their worktrees for
  post-mortem triage and PR reconciliation respectively.
- Add lifecycle regression tests in internal/daemon/terminal_cleanup_test.go.
2026-08-24 18:04:43 +10:00
sam 972fb5b8e1 feat(deployment): default to managed NATS workers
Autonomous workflows now always hand a complete task to a scoped archie-agent container. Embedded NATS is the default and external NATS changes only broker placement; legacy agent and containers.enabled inputs decode for migration but cannot select an execution path. The daemon flushes task-event subscriptions before a worker can publish, and runtime updates snapshot and restore the configured worker image.
2026-08-24 14:56:57 +10:00
sam 5d00ec7b0c 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 cc6b093820 fix(daemon): require full-task worker handoff
Autonomous tasks no longer execute workflow stages inside archied; missing worker capability parks before worktree preparation.

A transition to parked now atomically makes its detail the task park reason, so daemon-side failures remain visible in task APIs and the dashboard.
2026-08-24 14:56:57 +10:00
sam 1b7bc004b6 feat(nats): expose embedded broker to managed workers 2026-08-24 14:56:57 +10:00
sam ed33ab5380 feat(agent): stamp archie-agent's build and report it back to the daemon
archied's own build has carried a compiled-in gatewayVersion and an
internal/installtype stamp since archie-core-522/b5d08d0, but
archie-agent's build had neither -- its Taskfile.yml and Dockerfile
build steps passed no -ldflags at all, so even a daemon that wanted to
verify what agent build is actually in service had nothing to check
against. daemonRunningVersions said as much explicitly: the agent was
left out of every verification on purpose, because nothing self-reported
a real value.

Every archie-agent process is task-scoped and ephemeral (spawned per
task, dies after), not a long-lived process the daemon can poll on
demand the way it polls Telegram's gateway. So there's no "ask the
agent its version" request -- the only channel back is whatever a
worker includes in the taskrun.Response it already sends on every
completed task.

Stamp archie-agent's build the same way archied's is (installtype,
plus a new agentworker.Version()), have executeTaskRequest report both
in its Response, and have the daemon record the latest observation in
a new mutex-guarded AgentStatus, fed from runViaAgent on every
successful response only -- never off a request that never reached an
agent, or one describing a failed/parked task. daemonRunningVersions
now includes the agent component once (and only once) something has
actually been observed, so Report.Verify gets a real value to check
future update claims against instead of omitting the component
entirely.

Part 1/3 of archie-core-1786751948782-3-837a8fd0 point 4. Closes
archie-core-1786751948782-3-837a8fd0.1.
2026-08-23 23:18:00 +10:00
sam dbb6550ab3 fix(worktree): bind publication to dispatch grants
Worktree RPC used to accept repository coordinates from the sandbox. It now accepts only an opaque per-dispatch grant, and the daemon derives the repository path and branch from grant-owned state.

Repository worktree paths also move from an ambiguous flattened key to encoded owner/repo components. Origin-matched legacy clones migrate safely; mismatched legacy paths are preserved.
2026-08-22 22:06:54 +10:00
sam 508a0ad48c feat(forge): GitHub webhook receiver for immediate issue dispatch
Add [forge] intake = "poll" (default) | "webhook" | "both", and a forge
webhook receiver (internal/forge/webhook) that verifies a GitHub webhook's
HMAC signature, decodes the "issues" event, and publishes a matched issue
through the same path the poller uses -- so a labelled or assigned issue
starts a task the moment it happens instead of waiting up to poll_interval
(bead archie-core-7d5u.4).

The dispatch predicate (workintake.MatchesDispatch/RequiresLabel) is now a
single shared definition consumed by both the poller and the webhook
receiver, so the two cannot drift -- including the empty-label guard from
63d0446 (an empty label must never match every open issue). Assignee
matching is case-insensitive to agree with AssignedIssues' server-side
GitHub filter; label matching stays case-sensitive, since GitHub labels
are case-distinct.

daemon.publishTask is exported as PublishTask, the single enqueue path
now shared by the poller and the webhook intake.

Two failure modes fixed during adversarial self-review before this landed:
a webhook secret that fails to resolve at runtime now degrades (logs and
skips the receiver) instead of aborting the whole daemon -- under
intake="both" the poll exists specifically as a backstop for this exact
misconfiguration, so crashing boot over it defeated its own purpose;
multi-identity deployments ([[identities]]) are explicitly unsupported for
now (webhook intake refuses to start, logs why, and leaves each identity's
own poll loop unaffected) rather than silently matching issues against the
wrong identity's dispatch rules.
2026-08-22 19:21:09 +10:00
sam 63d044603c fix(daemon): refuse to poll on an empty label-trigger match (#529)
GitHub's issues-list API treats an empty label filter as no filter at
all, so dispatch.trigger = "label"/"either" with cfg.Label unset
silently returned every open issue in the repo. A live incident
(GH#445) queued 124 unrelated issues in one poll cycle after
[dispatch.labels] -- a different field mapping task states to their
own labels -- was configured while the actual trigger-match label was
left blank.

pollIssuesWithConfig's "label" branch now refuses to poll and logs an
error when cfg.Label is empty; pollEitherWithConfig skips only the
label-side poll in that case, still returning assignee matches.
validateDispatch rejects the same misconfiguration at config-load
time. A per-identity gap remains: identities have no Label field of
their own and share the root's, so an identity overriding
dispatch.trigger to "label" isn't caught by validation -- only by
the runtime guard, which is why the runtime guard matters even with
validation in place.

Fixes archie-core-1786637501009-424-5b8332dd / GH#445.
2026-08-20 23:19:53 +10:00
sam 5da1d5d006 fix(agentworker,daemon): reconcile worktree ownership before push
Agent containers run as root (no USER in the Dockerfile, no
userns-remap), so a commit the agent writes to the bind-mounted
worktree lands owned by UID 0 on the host. The daemon then reads
those same loose objects to push, running as its own non-root host
user, and fails with "openat objects/../..: permission denied".

containerEnv() now passes the daemon's own UID/GID as
WORKTREE_UID/WORKTREE_GID. hybridTrees.Push -- the single point
where a commit's objects are handed back for the actual push --
chowns the worktree to that owner first, via os.Lchown so a
legitimately-tracked-but-dangling symlink doesn't abort a push that
would otherwise have succeeded.

Closes archie-core-1786749700606-6-bf6aa32d.
2026-08-18 09:05:31 +10:00
sam 16ec8393fe style: apply gofumpt formatting 2026-08-17 00:02:31 +10:00
sam 2b5c67087b fix(update): stamp install type and bound retry backoff 2026-08-16 23:59:48 +10:00
sam 20bff1a367 feat(agentexec,workflow): surface tool calls on the task timeline
archie-core-467 wired tool-call visibility into the interactive chat
gateway, but a workflow task's own transcript never showed what its
tools actually did -- only stage/agent-finish events existed, so
there was no way to confirm an agent's summary matched what it really
ran.

Adds a ToolCallReporter, invoked once per completed call from
toolExecute (the single choke point every tool call passes through
before reaching a model), reported via a new ToolSetOptions.OnToolCall
hook. Runner.Run grows a report parameter to carry it in: InProcessRunner
wires it through, since it executes in the same process as its tools;
SubprocessRunner and NATSRunner accept and ignore it, since their tool
calls happen in a different process with nothing here to observe them.

The workflow engine turns each report into a tool_call event on the
task's own Bus (agent.go, implement.go), riding the same NATS
event-forwarding archie-core-518 already built to get container
events onto the daemon's timeline.

Scoped to the central tool registry (read/write/edit/grep/shell/...)
built via BuildToolSet; capture tools (structured finish output) and
run_go_script build their ToolSet entries directly and are not yet
covered.
2026-08-15 12:53:41 +10:00
sam 45345cdfb6 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 f544dd0978 feat(config): SIGHUP-triggered reload with requires-restart warnings
The daemon can now re-read its configuration on SIGHUP (or on a
future in-process trigger) and republish it through the Holder,
closing the first half of issue #348: 'config can change at runtime,
safely, and can't brick the daemon.'

Reload path:
- cmd/archied/reload.go: ReloadController re-runs loader.Resolve on
  the same paths main.go passed at startup (Resolve is pure -- no
  reload state added to the loader). apply is called only with a
  Document that passed validation; a failed reload records the error
  and its timestamp and leaves the running config untouched. That
  Set-not-called-on-error property is the safety core and is pinned
  by TestReloadValidationFailureDoesNotApply.
- SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log);
  the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only,
  fine given the Linux target).

PollInterval is genuinely reloadable now, not just re-read:
the three ticker sites (Run, per-identity goroutine, shared
maintenance loop) re-read the interval each tick and Reset the ticker
on change. A reloaded poll_interval takes effect on the next cycle.

Diff-and-warn so an operator never has to read the source to know
whether an edit took effect: changedNonReloadableFields compares the
old and new snapshots against an allowlist of re-read fields
(PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the
Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that
changed logs Warn 'requires a restart'; a fully-applied reload logs
Info. The allowlist is deliberate: a field added to Config later
defaults to requires-restart, the safe direction.

NATS split-brain closed: containerEnv now hands containers the
endpoint the daemon's own client connected with at startup
(Daemon.ConnectedNATS, captured at construction) instead of the live
config, so a reloaded nats.url cannot point new containers at a
server the daemon is not publishing on. A nats change is therefore
classified requires-restart, and CLAUDE.md's 'hands its own nats.url
verbatim' note is updated to the meaning it now has (same today,
deliberately different after a reload).

Validation guard: poll_interval <= 0 is rejected in validate.go
beside the VolumeTTL guard. applyDefaults fills zero with 60s, so
this fires on an explicit negative -- which would panic
time.NewTicker/Reset at boot and, after the per-iteration reset,
on a SIGHUP mid-run.

Observability: config.ReloadStatus (last_error, last_error_at,
last_reload_at) is recorded by the controller and surfaced in
/api/config via Server.LastReload, so a stale running config is
visible in the dashboard, not just the logs. Rendering waits for the
UI step.

Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1
(configuration.SkipOverlay), logged at startup. No overlay source
exists yet; the flag is the documented escape hatch the DB overlay
(step 3 of #348) will consult.

webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can
swap it via SetProvenance independently of Cfg; the accepted skew
(new config alongside old provenance) is documented on the field.

Verified: task check clean; -race on daemon, webui, cmd/archied,
config, infrastructure/configuration.
2026-08-10 00:19:46 +10:00
sam b6f0aea930 refactor(daemon,webui): make Daemon.Cfg and webui.Server.Cfg reload-safe
Daemon.Cfg, webui.Server.Cfg, and telegramSetup.Cfg were all held by
value (or as a raw shared pointer in webui's case), so a future reload
path could not swap the running configuration -- the consumers held
frozen snapshots made at construction. This is the prerequisite for
issue #348.

Add config.Holder, a small RWMutex-backed snapshot holder:
  - Get returns a value copy under RLock; the copy shares its
    reference-type fields with the published snapshot, so a doc
    comment pins the immutability invariant (a published Config is
    immutable; reload constructs a fresh one).
  - Set replaces the snapshot under WLock.
  - Get is nil-safe; Set is not.

Convert every consumer to read through the accessor. The convention
'cfg := h.Get() once per logical operation' is documented on the
type so the next reader knows that inline d.Cfg.Get().Foo is a code
smell (a Set could land between two consecutive Gets).

Special cases:
  - webui.Server.Cfg: was *config.Config, a raw shared pointer read
    from handler goroutines. Convert to *config.Holder. The
    pre-existing 'cfg := s.Cfg' aliasing bug at api_config.go:295
    (which was *trying* to copy but only copied the pointer) now
    becomes 'cfg := s.Cfg.Get()', which is the value copy the
    read-only view always wanted.
  - daemon_test.go: one test mutated d.Cfg.DiffCapLines in place,
    which the Holder forbids. Replace with the documented
    read-modify-write pattern (prev := d.Cfg.Get(); prev.X = Y;
    d.Cfg.Set(prev)).
  - telegramSetup.Cfg: matches the daemon's API for consistency
    even though setup runs before the daemon is alive.

TaskContext.Cfg in internal/domain/workflow/workflow.go is
deliberately NOT converted -- a task that starts under one config
should finish under it, and a config changing between TDD and gate
stages is a bug, not a feature. Snapshotted at dispatch, as before.

Verified: go test ./... (61 packages), go vet, -race on
internal/daemon and internal/config.
2026-08-09 23:29:52 +10:00
sam 61b4b7b0cf refactor(store): replace legacy persistence with SQLite
Task and event persistence now uses a dedicated SQLite sidecar derived from the configured state prefix, matching the independently persisted conversation store. The configured path now means a state-path prefix rather than a database file so fresh SQLite state never attempts to interpret the previous storage format.

Remove the retired implementation and dependency completely, strengthen SQLite migrations and concurrency behavior, restore backend-neutral coverage, and align configuration, operational guidance, UI labels, and deployment documentation with the new storage and host-daemon topology.
2026-08-09 22:27:25 +10:00
sam 951ddbc9f4 feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
Closes the loop #451-#453 opened. archie-agent (#453) now publishes its
own logs to agentexec.SubjectForSystem(taskID) over NATS, and a task
log sink (#452) exists to persist them, but nothing on the daemon side
subscribed, demuxed, or wrote anything -- the messages had nowhere to
land.

- agentexec: SubjectSystemWildcard + TaskIDFromSystemSubject, the
  inverse of SubjectForSystem, for a daemon subscribing to every
  task's system subject with one wildcard subscription.
- logging: TaskRegistry manages one open TaskSink per running task
  attempt, mirroring every write onto the live dashboard Feed the same
  way a locally-written log would appear. Nil-receiver-safe, matching
  every other optional composition-wired Daemon field.
- daemon: Daemon.process opens a task's log sink for its own duration
  (covering both the sandboxed-container and in-process dispatch
  paths uniformly) and closes it on every return path.
- cmd/archied: constructs the registry, subscribes core NATS to
  SubjectSystemWildcard, and wires TaskLogs into both Daemon and
  webui.Server.
- webui: archiving a task now removes its log directory too, so
  archived tasks' logs don't accumulate forever. Documented as a
  known, accepted race: a task can reach terminal status (satisfying
  ArchiveTask's precondition) before process() itself returns and
  closes the sink, so a very late system-log write can race an
  archive's Remove. Not corrupting -- the write lands on a
  soon-to-be-unlinked inode and is discarded -- and not worth fixing
  here: it would mean tying Close to the store transition instead of
  to process()'s return, a larger change than this issue's scope.

Adversarial review (fresh subagent) found and fixed two real issues in
the first draft: a doc comment accidentally spliced between two
functions during an extraction meant to fix a lint regression, and a
genuine test gap on openTaskLog (added, using TaskRegistry.Write's own
true/false contract as the observable -- no Store/Forge/Trees fakes
needed, since openTaskLog only touches TaskLogs and Log).
2026-08-09 18:42:54 +10:00
sam 1081a6c3ed feat(daemon): identity-scoped isolation + gateway session titles and /delete
Multi-identity daemon isolation:
- Split runIdentities into per-identity poll loops plus one shared
  maintenance-and-drain loop, so reconcilePRs and storage cleanup run in
  multi-identity mode and the global max_concurrency / per-repo
  serialization holds across identities.
- Make the poll path identity-aware: each identity polls with its own
  forge client, bot user, label, trigger, and ack reaction.
- Make allowConcurrentFor task-based and identity-aware via repoFor.
- Roll back storage mounts when container acquisition fails; log
  Store.Update failures after branch set.

Container-mode RPC identity routing:
- forgerpc/worktreerpc gain identity-scoped subjects (SubjectFor,
  RegisterFor) and identity-carrying clients.
- registerTaskRPCServers registers one server pair per identity (plus
  root), so a container-mode task owned by a non-root identity is served
  by its own forge client and worktree manager.

Gateway/Telegram:
- LLM-proposed session titles generated in the background after turns
  (TitleGenerator + chatTitleGenerator), persisted by the gateway.
- /delete session command with prefix guard and tracker forget.
- Shared session display helpers (shortSessionID, sessionDisplayTitle,
  resolveSessionRef).
2026-08-08 01:32:35 +10:00
sam 7e896c9411 refactor: migration of workflow into it's own domain 2026-08-07 00:24:05 +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 4ece064026 feat(curator): engine family contract, registry, and runtime (archie-core-rfp, archie-core-89x)
internal/curator is a conforming engine family per the strict plugin
engine rule: typed CuratorEngine contract (Lifecycle + domain ops),
owning Registry (registration, discovery, start/health/stop with
failure isolation, reverse-order shutdown, ctx-bounded stop), and a
narrow typed Registrar — each curator receives a capability-filtered
view of the host at Bind, never the daemon.

Runtime: one loop per curator on an injectable clock (fake-clock
testable), best-effort wake nudges with the trigger decision kept in
Check (a dropped nudge only delays to the next check-in, never
corrupts accounting), per-pass timeout and a max-concurrent-passes
slot so curator bursts cannot starve chat turns, per-pass panic
recovery, and bounded shutdown even when a pass ignores cancellation.
curator_run / curator_action / curator_error ride the in-process
event bus so activity stays attributable.

Wired in cmd/archied/main.go (constructed beside memory, Start after
daemon startup, shutdown ordered before memory/LLM teardown) and
exposed as daemon.Daemon.Curators.
2026-08-05 14:54:12 +10:00
sam fa6f4aef5f fix(gateway,daemon): repair regressions found by the adversarial review
Six defects, four of them introduced by the fixes in dbacb96, 44d43ef,
d5e016e, de1a899 and 4d44ef7. This is the third round in this codebase
where a round of fixes broke something the next round caught.

SANDBOX SILENTLY DROPPED. startContainers degrades a failed container
pool to nil, and the daemon's only test was `if ContainerPool != nil`.
So `containers.enabled = true` plus a missing agent image ran every
task's agent loop in-process, with the daemon's own authority and the
host filesystem -- the one thing [containers] exists to prevent -- while
logging only that containers were disabled. Nil now means two things and
they are distinguished: SandboxRequired parks the task instead. The
daemon still stays up; chat and the dashboard are unaffected.

SUMMARY AT THE WRONG END OF HISTORY. compressedHistory returns [head,
summary, tail], but ordering is by timestamp, not slice position. The
retained messages keep their original timestamps -- that is what
preserves their identity -- so the summary, being new, was clamped to
now and sorted after the tail it was meant to precede. The model read
the recent conversation and was only then told earlier context had been
summarised. Confirmed on both backends: index 23 of 24.

The monotonic clamp belongs to the append path, where an inbound message
must not sort ahead of the one that provoked it. ReplaceMessages is a
rewrite primitive and now honours explicit placement, and the summary
takes a timestamp inside the span it replaces.

A COMPRESSION SUMMARY ANSWERED A QUESTION. Following from the above,
PriorReply saw a bot-attributed record immediately after an unanswered
message and replayed it as the answer: a redelivered question was
"answered" with the compression banner and the model never ran. The
user's question was silently swallowed.

RECENCY STILL DIVERGED. sessionRecency preferred LastActiveAt whenever
set; SQLite used MAX(last_active_at, created_at). Those agree only when
LastActiveAt is the later of the two, so a clock step or an older record
made the caller and the store order the same sessions differently.

LASTACTIVEAT WAS NEVER UPDATED. Touch had no caller, so "resolve the
most recently active session" meant the most recently created one -- an
operator who moved to an older session with /topic and worked there was
dropped back into the newer, abandoned one on restart, which is the bug
d5e016e claimed to fix, with the direction reversed.

/branch WITH NO ACTIVE SESSION PANICKED, slicing an empty parent ID for
its default title. Pre-existing, but reachable: email and webhook call
Route directly without resolving first, and the email path runs in a
goroutine with no recover, so one message took the daemon down.

The sandbox guard has no test. The honest reason is that exercising it
needs a daemon with a forge and worktree the current harness does not
build, and a test that re-states the condition proves nothing -- which
is the same false confidence that let these regressions through.
2026-08-05 04:24:16 +10:00
sam 170fe0250b fix: close the duplicate-work loop and the dead paths around it
Applies the four-reviewer pass over the forge/dashboard-actions work.
The through-line is that several capabilities were wired but inert, and
one of them could cost real work.

DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of
LinkBranch, which is sidebar linkage on Gitea and a no-op stub on
GitHub -- neither closes anything, and nothing else did either. So a
merged task left its issue open, labelled and assigned; the next poll
re-enqueued it, and once the dashboard's Clear removed the task row that
became a second implementation and a second PR for work already merged.
reconcilePRs now closes the issue on merge, and a rejected task closes
its issue too. A PR closed without merging deliberately leaves the issue
open: that usually means "try again".

MAX RETRIES. Configured, defaulted and reported by /api/config, and
enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had
no callers, so the dashboard's retry incremented retry_count forever.
The retry action now retires a task to dead at the cap.

DEAD ON ARRIVAL. Tasks() never selected plan or source, so the
"Decision required" panel could not render and chat tasks -- whose issue
number is synthetic -- linked to forge issues that do not exist.

COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when
LinkBranch errored, so the pull request was never opened and the task
parked; a retry re-links the same branch, which Gitea answers with a
conflict, so every retry parked again. It is best-effort now.

INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing
else, so the timeline and activity stream never showed that a human had
intervened. They emit events now.

Also: store write failures answer 500 rather than 409; the dashboard
surfaces the server's actual reason instead of "409 Conflict"; action
buttons stop propagation (acting on a task no longer also expands it),
disable in flight, keep per-task errors instead of one shared string,
and confirm before rejecting.

Removed: the maybeRetryParked shim and markDead with their now-vacuous
tests, WaitingTasks (no consumers; its tests were rewritten to assert
the same routing through TaskByID), write-only Daemon.Runtime, and
dir/dirs response bloat from /api/skills. skillSource checked workDir
before sharedDir, mislabelling every shared skill when the two are equal.
DefaultRoots now dedupes roots differing only by a trailing separator.

The air build rule claiming to keep ui/dist current never ran -- it
required one file to satisfy include_dir and include_file together, and
ui/ is excluded from the walk. Deleted with the comment that promised it.
task test:ui joins task check and CI; it ran nowhere before, so the
dashboard suite could rot silently.

Docs corrected where they described behaviour that no longer exists:
parks no longer comment on the issue, state labels no longer drive
retries, and forgerpc's doc claimed four proxied methods while listing
three of five.
2026-08-05 03:54:25 +10:00
sam 3ae59c99c0 fix(secrets): wire provider credentials through engines 2026-07-31 08:45:58 +10:00
sam 6c32550345 chore: replace personal owner names in tests and config with generic values
Test fixtures used 'sam', 'samcharles93', and 'sam/<repo>' as owner
names. These are personal and machine-specific — the repo should use
generic placeholders like 'acme' (matching the existing convention in
worktree_test.go).

config.example.toml: samcharles93 -> your-github-username
Test owner: sam -> acme
Repo refs: sam/archie-core -> acme/archie-core, etc.
Example skills: sam -> acme
2026-07-31 02:15:41 +10:00
sam 6be754787d polish: add install.sh, XDG setup, deployments/ examples, and github-token docs\n\n- Add install.sh following XDG Base Directory specification (~/.config/archie, ~/.local/share/archie, ~/.local/bin)\n- Add interactive setup for code forge (GitHub / Gitea / Standalone) and LLM provider selection (Ollama model picker / Cloud keys)\n- Implement NoopForge in internal/forge/noop.go for running Archie in standalone mode without a forge\n- Enable loginctl user linger and systemd user unit setup in install.sh\n- Add docs/github-token.md with step-by-step guidance for Classic PAT generation\n- Add top-level deployments/ directory with scenario templates (single-forge GitHub, multi-forge GitHub+Gitea, local Ollama standalone, systemd runbook) 2026-07-30 01:25:46 +10:00
sam e7d39254e7 feat: make /stop reach running agent tasks
/stop cancelled the chat turn but could not touch a task the daemon was
executing, and /cancel refused outright:

    case statusRunning:
        return fmt.Errorf("task is actively running; cannot cancel
                           until it reaches a waiting state")

So the one case worth interrupting was the one case neither command
would touch.

The daemon now holds a cancel function for every executing task,
registered in process() -- the single point every dispatch path reaches
-- so a task is stoppable for its whole life, including the slow clone,
worktree prepare and image pull that is exactly when someone realises
they asked for the wrong thing.

- /cancel <id> interrupts the work first, then records the terminal
  state. That order matters: writing the state while the task still runs
  invites it to write its own afterwards and win. A task the store calls
  running that nothing is executing (crashed daemon) still gets its state
  recorded, which is what unsticks it.
- bare /stop now stops the reply, the queue behind it, and every running
  task for the identity, reporting which of those it actually did.
  Nobody reaching for the brake should have to look up a task ID first.
- StopRunning deliberately writes no terminal state: a stopped task
  unwinds to parked, which is resumable. Forcing rejected would discard
  work worth keeping.
- Without a runtime wired, cancelling a running task is still refused --
  recording it as cancelled while it carries on would be a lie.

Container teardown detaches from the task context. Release runs on the
way out, and the main reason a task is on its way out is cancellation --
at which point the graceful ContainerStop failed instantly and the
container was left to the forced remove. Cleanup gets its own deadline.

process() gained two statements and crossed the funlen limit, so the
container setup block is extracted rather than suppressed.
2026-07-29 19:19:04 +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 a8efbf5046 refactor: route tasks on a typed kind, not forge labels
The event bus was inspecting forge issue labels ("bug", "feature",
"bootstrap") to pick a subject. That put a forge vocabulary inside
infrastructure and duplicated the label table already owned by
workflow.Route -- adding a label meant remembering both places, and
nothing would have caught it if you forgot.

The label table now lives once, in internal/workflow, which already owns
label semantics:

  - workflow.Kind names the routing category, with labelKinds as the
    single label vocabulary and kindWorkflows mapping kind to registry
    entry. Route consumes the ordered kind list so a "bug,feature" task
    still falls through to feasibility when no tdd workflow is
    registered, exactly as the switch did.
  - nats.TaskKind is a closed, validated set of subject tokens.
    PublishTask rejects an unknown kind rather than silently delivering
    it to the default queue; the zero kind means default, so messages
    queued before this field decode unchanged.
  - The daemon classifies at the publish site and sets TaskEnvelope.Kind.

Also fixes two defects this exposed:

  - drainNATS never reached its SQLite fallback. Replacing the old
    (nil, nil) no-message signal with ErrNoMessage in 492ca20 made that
    case continue at the top of the loop, but no-message is precisely
    when the fallback must run -- requeued tasks (waiting_human approval,
    retry-parked) never go through a NATS publish, so nothing would ever
    arrive to trigger them. go vet caught it as unreachable code.
  - config.classifyFeatureFile silently overwrote duplicate feature
    files, so config.gateway.yaml and conf.d/gateway.yaml together
    applied one at random. Its own doc comment recorded the bug
    ("or "" on success/duplicate"). The known-feature list in the error
    message is now derived from knownFeatureNames instead of being
    spelled out a second time beside it.

A test also called t.Fatalf from a non-test goroutine, where it does not
stop the test.

Verified: go build, go vet, gofmt clean. Pre-existing gateway (18) and
telegram (1) failures are unchanged in count -- they are lost routing
wiring from the parallel telegram merges, tracked separately.
2026-07-29 10:43:52 +10:00
sam f303998e14 Merge branch 'crew/lint5' 2026-07-29 10:37:36 +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 a9e8cda4f2 fix(qa4.3): resolve nilerr, bodyclose, contextcheck, containedctx, fatcontext lint findings
- bodyclose: add deferred resp.Body.Close() in storage_test.go Docker test handler
- contextcheck: thread context through email handleSMTP/processMessage; replace
  context.Background() with context.WithoutCancel(ctx) in telegram, webhook, webui
  shutdown paths and container pool cleanup; add ctx parameter to Pool.Release
- containedctx: replace ctx context.Context struct field with stopCh chan struct{}
  in StdioTransport and SSETransport; thread lifecycle context through goroutine
  chains instead of storing it in structs
- fatcontext: lift context deadline derivation out of PrefetchContext loop
2026-07-29 10:10:42 +10:00