Commit Graph
106 Commits
Author SHA1 Message Date
sam f498f593c9 fix(eda): authoritative module ids and stricter action load errors 2026-09-22 09:41:31 +10:00
sam 0ca733f7e5 docs(config): point rate_limit at the Channel settings resource
The rate-limit budget's runtime owner is the channel-settings control-plane
resource, which the Web UI edits and which boot.loadRuntimeConfig layers over
the file before boot.startRateLimiter reads it. [chat.rate_limit] is that
resource's seed, not its authority.

1fe4691b's comments and commit message described the file key as the thing that
documents a webhook's per-route budget, which is the pre-migration framing.
Cite the resource and the layering instead, and say plainly that editing the
file does not change a stored value.
2026-09-22 03:32:20 +10:00
sam 1fe4691bd6 fix(webhook): keep a route path out of the sender identity
A webhook set SenderID to its configured route path. The turn path reads that
field through a per-channel resolver which refuses webhook, but the session
curator derives its participant from the raw field with no channel filter, so a
webhook session with exactly one distinct sender and one extracted fact wrote
agent-user memory addressed to User: "/hooks/...". Nothing reads it, and every
pass added more, because the facts are identical strings with no dedup.
docs/prds/memory-engine-unification.md criterion 7 requires that a route path
never become a user identity.

Clear it at the producer rather than teaching every consumer which channels are
lying: a route path is a source, not a person, so it no longer enters SenderID.
It still keys the inbound rate limit, where it is the documented per-source
budget for webhooks (config.RateLimitConfig), so it travels in the new
transport-only Inbound.BudgetKey -- carried on the wire beside Page, never
persisted, and never read as an identity.

pb.Message gains budget_key (field 9) for the same reason page (field 7) exists:
transport context that rides with an inbound message and is deliberately absent
from storedProto's rendering of a canonical record.

The curator needs no change. An empty SenderID already fails closed as an
unidentified user message, which is the path a dashboard session takes, and
sessionParticipant's existing skip covers it; the test name now says so.
2026-09-22 03:18:59 +10:00
sam 59cc831ff7 feat(tools): add per-server parallel_tool_calls to the MCP client
MCPServer gains ParallelToolCalls (default false). The client's
per-server callMu is now nil for a server that opted in, so CallTool
stops serializing that server's calls and the caller's own concurrency
decides; every other server keeps exactly one tools/call in flight.

The flag is threaded from config through the provider constructor -
the only place MCPServer configs become Client instances - into
NewClient, in both the daemon and the agent worker.
2026-09-22 01:57:58 +10:00
sam 31622ec5c2 refactor(config): delete the runtime config overlay
The control plane replaces this, rather than extending it
(docs/prds/runtime-control-plane.md, "First implementation"). Until now both
paths existed: overlay kept dashboard edits in its own SQLite file beside
archie.db and layered them over the file config at boot and on every reload,
which is the duplicate configuration authority the PRD set out to remove.

Gone with it: the --no-config-overlay flag and ARCHIE_SKIP_CONFIG_OVERLAY
recovery hatch, which existed because a bad overlay row could brick the boot;
ReloadStatus.OverlayUnavailable; and the reload controller's overlay source.
The -config-overlay file overlay is a different thing and stays.

The dashboard's three write seams went too. UpdateConfig, ResetConfig and
UpdateRepoField were assigned only in internal/webui's own tests, so in
production they answered 503 and ConfigView.Editable was permanently false
(archie-core-j28m). Removing Editable would otherwise have flipped the SPA's
controls on, since configEditable read a missing field as true, so the config
pages become what they already were in practice: a read of what each process
is running with. Configuration is written through the control plane.

apply.go survives this deliberately; archie-core-xrux carries the question of
whether its map merge is still guarding the file overlay path.
2026-09-21 08:57:55 +10:00
sam f6397af7f4 fix: address the Greptile findings on the merged PRs (#902)
* fix: address the Greptile findings on the merged PRs

Four valid review findings from PRs #892, #893, #898 and #899, which were
merged without the comments being read.

- Config.Clone left the new diff-cap pointers aliased (#899, mine). Clone
  deep-copies every reference field, including the *bool beside it, so a
  clone could write the cap through to the published snapshot. Both the
  top-level field and the identity overrides are copied, with the clone test
  extended to cover them.
- providerOutcomeRecorder.record could report an older call as the latest
  (#892). The completion time is taken before the lock, so two concurrent
  calls can reach the lock in the opposite order to their completion and the
  unconditional store overwrote the newer outcome. It now keeps the newer,
  via a recordAt seam that makes the reordering testable.
- Curator model calls bypassed the recorder (#892). curatorLLMRunner calls
  the runtime directly, so a daemon whose only recent model traffic was
  curator work reported "no calls attempted yet" while the provider was
  demonstrably reachable. It records at its own adapter, and sendChatTurn's
  "single choke point" comment is corrected to say there are two.
- A provider error reached /status raw (#892), unlike channel details, so a
  multiline or oversized error broke the one-line-per-fact layout. Both now
  share one bounded formatter.

Found while fixing the curator path: agentexec.NewRuntime returns nil when no
provider is configured, and a nil *runtime.Runtime panics on its first method
call, so a curator asking for a completion took the daemon down. It now
returns an error, and records nothing -- a local misconfiguration is not a
provider call.

Not fixed, filed instead: the shared lastPollAt masking a stuck identity, the
container max-uptime callback resurrecting teardown bookkeeping, the
dashboard dropping a served-only status filter on cold load, and the route
registry test's line-by-line parser.

* fix(build): drop goimports from the gate's formatter set

`task check` spent 136 of its 167 seconds in `task fmt`, and 134 of those
136 in one formatter: goimports alone over the tree.

golangci-lint's goimports formatter calls imports.Process once per file,
which builds a fresh x/tools ProcessEnv each time, so
internal/imports.getFixesWithSource re-reads modindex.Read($GOMODCACHE) per
file. On this machine that index is 62.7 MiB / 2,081,070 lines (an 11 GiB
module cache), and modindex's in-process memo does not take effect: 3 files
read 187.9 MiB back, 15 files open the payload 15 times. That is ~53 GiB of
I/O and CSV parsing per run, and it is linear at ~155 ms per file (122 files
-> 18.8s, 864 -> 133.8s). Pointing the index cache elsewhere drops the same
command to 3.9s.

The same analyzer runs under `golangci-lint run`, so a cold cache pays it
again: 169s cold with goimports, 31s without -- which is what CI and archied's
own PR gate see, since only `fmt` never caches locally.

Removing it costs no enforcement. gofumpt and gci remain, `task lint` still
reports formatter drift as an issue, and the whole-tree fmt is now 2.2s with
the tree byte-identical. What is given up is goimports' convenience of
adding and removing import lines, which compile errors already cover.

The examples/secret-engines exclusion stays: gofumpt and gci leave those
Yaegi programs alone today, but the exclusion is the stated invariant that a
formatter must not rewrite the imports of files it cannot type-check, and
TestFormattersExcludeInterpretedSecretEngines holds it. Its comment no longer
pins the reason to the formatter that was dropped.

* fix(gateway): stop /status promising and mis-reporting health it cannot see

Two findings from the cloud review of #892.

Title generation no longer records chat-model health. It runs detached after
a first turn under its own 30s bound and its error is swallowed by the
caller, but it shared the process-wide outcome recorder, so a title that
merely timed out overwrote the health line with "failed" -- reporting a
broken provider on the strength of a call no user was waiting for.

The /status command description no longer claims "workers" and "channels".
Neither can render: newStatusHealth reads the container pool and the poll
loop from boot, but the only production router.Health assignment is in
setupGatewayChat, which runs solely in the archie-gateway process, where
neither exists; channels is nil since the Messaging Service took the
front-ends. Only the broker and chat-model lines actually appear, so that is
what the help text now says.

The underlying split -- daemon owns the facts, Gateway owns the Router -- is
filed rather than patched here: it needs either a cross-process health
contract or a ratified two-section /status, not a quick wire-up.
2026-09-20 02:42:36 +10:00
sam c35d9b6fdd feat(messaging): Messaging Service operator surface, chat report rendering, and the diff-cap config fix (#899)
* 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.

* fix(gateway): render chat reports as lines, not one run-on paragraph

/status and /tasks are line-oriented reports, but their newlines were plain
"\n" -- CommonMark's soft wrap. The Telegram rich-block renderer space-joins
soft-wrapped lines, by design: a Telegram paragraph renders an embedded
newline as nothing at all, so a space is the only separator that survives.
The reports therefore arrived as one line each: "Runtime Provider: DeepSeek
Model: deepseek/deepseek-flash", and every task's title, state and park
reason jammed together.

The renderer now implements CommonMark's hard line break (two trailing
spaces, or a trailing backslash): the line closes its own block and the next
one hugs it, so a stanza keeps its lines without the spacer paragraph that
separates unrelated blocks. Ordinary prose is untouched -- a model's wrapped
paragraph still joins with a space. The producers mark their report lines
with it.

Two report fixes alongside:

- A park reason is capped to its first line at 160 runes. It carries whatever
  the failing stage reported, which for a lint gate is the whole tool log;
  unbounded, one parked task pushed every other task out of the reply. The
  full reason is still on the task.
- /status loses its "Runtime" sub-header. A section header over two fields
  made a four-fact report read like a document.

* fix(config): let diff_cap_lines = 0 actually switch the cap off

Config.DiffCapLines was a plain int, so the defaults pass could not tell an
absent key from an explicit 0 and rewrote both to 400. The dashboard schema
said "0 means unlimited" and StageDiffCap treated <= 0 as unlimited, but 0
never reached the step: the documented way to switch the cap off was
unreachable through config.

Same root cause, worse instance: configForIdentity assigned
root.DiffCapLines = identity.DiffCapLines unconditionally, so an identity
that simply omitted the key overwrote the shared cap with the zero value and
silently disabled the safety rail for that identity.

DiffCapLines is now *int on both Config and IdentityConfig -- nil is absent,
0 is no cap -- read through Config.DiffCap(). Defaults fill only nil, and an
identity overrides only when it set the key. TaskConfig keeps a resolved int,
so the daemon/agent wire format is unchanged and a version-skewed agent
cannot misread a null.

The park reason changes too. It told the operator to "approve manually", but
a parked task's actions are retry, abandon and reject (internal/taskstate):
there is no approve path out of diff-cap, so it sent them looking for a
button that does not exist. It now names the two things that work.

* feat(config): make the daemon's readiness dependency timeout configurable

The daemon's gateway probe bounded its call with a hardcoded 5s constant,
while every other NewContractProbe call site (archie-ui, archie-messaging)
passes the service's configured DependencyTimeout. It was the only magic
number among them.

[health].dependency_timeout carries it, defaulting to the same 5s the
extracted services' -dependency-timeout flag defaults to, so every process
bounds a probe into a dependency the same way out of the box.

It is not added to the dashboard config schema or the reloadable set:
[health] appears in neither today, health.listen included, and a probe
assembled at boot would not observe a reload anyway.
2026-09-20 00:32:13 +10:00
sam 04d4d8f1d8 chore(memory): delete internal/memory (unification slice 5) (#889)
Deletes internal/memory (Manager, builtin.Provider, memory_edit tool) now
that slices 2-4 built the CRUD engine family and its per-turn read/write
seams. Also deletes internal/infrastructure/memory/builtin/provider.go (the
memory_edit adapter over the old package -- its markdown store already
relocated in slice 2), internal/tools/provider/memory (the old tool
registration, redundant with slice 4's memory_create/update/delete/list),
config.Memory.{Provider,ProviderConfig} and the validateMemory rejection
that existed only to complain about Provider, and webui.MemoryStatus/
MemoryProviderHandle plus its dashboard page -- never wired in production
(s.Memory was always nil), confirmed by /api/capabilities always reporting
"memory": false.

Rewrites ARCHITECTURE.md's "Memory engine family" section to describe the
current engine (internal/domain/memory contract, internal/infrastructure/
memory builtin engine + its builtin/ markdown store, the per-turn read seam
in gateway/turn_memory.go, the per-turn write tools in
gateway/turn_memory_tool.go) instead of the deleted Manager. Fixes two
docs/architecture/configuration.md rows that described the deleted
manager's literals and SaveConfig mechanism.
2026-09-19 13:43:16 +10:00
sam 28ede30b74 fix(config): clone the Services map so an overlay cannot mutate the published snapshot
Config.Clone deep-copies every reference-type field except Services, which became a
map[string]ServiceConnection. A value copy shares the map header, and yaml.Unmarshal
writes keys into whatever map it is handed -- so Loader.ApplyOverlay, which clones
precisely so it cannot corrupt the base document, rewrote the published snapshot in
place:

  ApplyOverlay(doc, {"services": {"state": {"target": "10.0.0.5:9090"}}})
  left doc.Config.Services["state"].Target changed

That defeats the reason Clone exists: a failed or partial overlay must not alter the
configuration still being served.

Red: TestConfigCloneDeepCopiesReferenceFields failed with "Services map is shared"
after the case was added; green with the one-line clone.
2026-09-19 03:07:14 +10:00
sam cc390256a4 fix(config): enforce the service context at registration
ServiceSpec.Context documented which addresses a service must end up with, but
nothing read it, so a typo'd context was accepted and meant nothing. Review
caught it as scaffolding that looked load-bearing.

RegisterService now validates it: an unknown context, or a hosted (server/both)
service registered with no default listen address, panics. Registrations come
from this repository's own init(), never from operator input, so an invalid one
is a programming error with no caller positioned to handle an error return, and
failing at process start beats a service binding where nobody dials.

Services.RequireTarget replaces the same check and message hand-written in
composeStateStoreClient and composeChatContract. An empty registered default
target is what declares a target operator-supplied, so the requirement belongs
to the registry rather than to each consumer. It stays a lazy check at
composition time rather than becoming load-time validation: a process that
never dials a service must still load a configuration that omits it.

The review's stated failure mode does not occur. A hosted service with an empty
listen does not reach net.Listen as an ephemeral port; resolveServiceListen
returns "no listen address" and archied refuses to start. The defect was the
inert field, not a silent bind.

Refs: archie-core-u23g
2026-09-19 01:50:25 +10:00
sam 6bdbd5e31e feat(config): key services by name through a registry
Services was a struct with one field per service, so each service's name was
stated three times: the field, the loader's defaulting branch, and every
consumer's field access. Adding one meant editing all three, and nothing
stopped them disagreeing. The drift was already there: stateStoreResolvedToken
and gatewayResolvedToken were identical apart from the env var each hard-coded.

Services becomes map[string]ServiceConnection, and RegisterService declares a
service once with the five fields it has. Everything that differs between
services is now an argument rather than a branch elsewhere: an empty registered
target means the operator must supply one, which is how services.state.target
stays required while the gateway's is defaulted, and the registered token env
var replaces the two copied resolvers with Services.ResolvedToken.

Defaulting iterates the registry, so a new service needs no loader edit.
Consumers read Services.Get(name).

Keeping a typo'd section reported took explicit work. [services.gatway] used to
land in toml.MetaData.Undecoded() because the struct had no such field; a map
decodes any section, so it would have loaded silently and left the daemon
dialing the default. unregisteredServiceKeys asks the registry which names are
real, and the test for it fails with an empty UnknownKeys when that check is
removed.

The TOML shape is unchanged, so no deployment profile, config.example.toml or
install.sh edit is needed.

Refs: archie-core-u23g
2026-09-18 23:32:36 +10:00
sam e0beb68978 feat(config): let the State Store and Gateway listen addresses be configured
Both gRPC listeners took their bind address from a -listen flag default alone,
with no config key. The port a service binds and the port its clients dial were
therefore two separate facts -- the flag default, and [services.<name>].target --
with nothing keeping them in step.

On a host that already owned the default the effect read as a code fault rather
than a port collision: the store died with "bind: address already in use" while
every client reported "state store: connection error ... error reading server
preface: EOF". Cockpit binds 9090 by default, so this is not hypothetical.
Verifying the dashboard on such a host needed a hand-written overlay plus a
matching -listen, two things to keep in step by hand.

- [services.state].listen and [services.gateway].listen now name the bind
  address. Precedence is -listen, then config, then a default applied by the
  loader. An empty result is a startup ERROR, never a fallback: net.Listen reads
  "" as "any free port", so defaulting there would bind the service somewhere no
  client looks and still report success.
- Both flag defaults become "" so configuration can win, mirroring how archie-ui
  already prefers [web].listen over its flag.
- Gateway listen defaults to the same constant as the gateway target, so a
  default deployment's client and server cannot drift onto different ports.
  [services.state].target still has no default: an empty target stays a startup
  error in the daemon and gateway, which no longer serve a local store.
- ServiceConnection gains the field. Its doc now says clients read only Target
  and TargetToken, and Listen belongs to the process that owns the service --
  the previous wording claimed the struct starts no listeners while carrying one.
- deployments/dev.toml states each port once, beside the target it must match, so
  `task dev` is retargetable on a host that owns 9090 by editing one overlay.

Tests. Unit: config defaults, explicit values, and precedence. Process: the
existing real-process smoke test now takes its listen from configuration instead
of -listen, so the end-to-end wiring is proven by the test that already starts
the binary, with no extra process. Both were verified load-bearing by mutation --
inverting the precedence fails the unit test, and making the app layer ignore
config fails the process test with "state: no listen address".

Verified: task check exit 0. Also documented in config.example.toml, the
configuration architecture table, and the `task dev` summary.
2026-09-18 19:15:02 +10:00
sam f25dd1e867 refactor(config): delete the two decoded-but-unread policy fields
MemoryConfig.SessionTTL and ToolPolicy.ParallelExecution were decoded by
config loading and read nowhere, so setting either silently did nothing.
Removing them routes both keys into the unknown-key detector, which names
them in a boot warning instead. A live-looking knob wired to nothing is
the worse state, and the sibling memory.provider already earned a loud
load-time rejection for exactly this.

Also drops the config.example.toml line that shipped session_ttl into
every first-run config.toml via configtemplate.go, and the commented-out
dir_test.go assertions that would have re-created both fields under that
file's "make these pass without modifying them" header.
2026-09-17 00:32:02 +10:00
sam 2c80f3c59b Merge branch 'crew/cluster1' into crew-integration 2026-09-15 10:33:15 +10:00
sam 1fe6b9af48 feat(channels): wire chat.webhook route config through to the gateway
internal/channels/webhook's RouteConfig implements and tests HMAC
signature validation, payload template extraction, and reply delivery,
but setupWebhookGateway built []webhook.RouteConfig{{Path: "/webhook"}}
literally -- no config field could reach Secret/Template/DeliverTo, so
the gateway accepted any unsigned POST despite its package doc claiming
signature validation.

Adds config.ChatConfig.Webhook (WebhookRoute: path, secret as the
existing SecretRef pattern, template, deliver_to) and webhookRoutes(),
the pure translation into []webhook.RouteConfig that
setupWebhookGateway now calls. A secret ref that fails to resolve logs
and falls back to no validation rather than refusing to start, since
signature validation stays opt-in (an empty secret is documented,
valid config) unlike the mandatory forge webhook secret.
2026-09-15 10:22:54 +10:00
sam 72d9125bba fix(agentworker): wire configured tool-result policy into worker's LoopRunner
TaskConfig now carries the daemon's ToolPolicy (MaxResultChars/SpillDir)
via ForTask/ToConfig, and runTask applies it to the constructed
LoopRunner. Previously the worker always built the agent loop with a
zero-value ToolLimits, so tool results in every task's agent stage were
never capped or spilled despite the configured 50k default (agentexec-1,
tools-core-11).
2026-09-15 10:14:50 +10:00
sam 888c612844 fix(config): deep-copy Image.Hosted/Image.Local in Config.Clone
Clone's own doc comment promises mutating the clone cannot touch memory
shared with the original, but Image.Hosted/Image.Local were left as a
shallow map copy -- a runtime overlay or dashboard PATCH decoding into the
clone could mutate the published config's image provider maps.
2026-09-15 04:38:54 +10:00
sam 5c9f5fea20 feat(ratelimit): wire per-identity inbound rate limiting into the gateway
internal/ratelimit was fully built (sliding-window limiter, ticker-driven
eviction) but had no consumer, leaving multi-identity deployments with no
inbound request budget on any channel (archie-core-6wxb / GH #797).

Adds Message.SenderID (Telegram numeric user ID, SMTP from address, or
webhook route path -- the closest thing webhook has to a caller identity),
threads it into Router.Route/RouteStream via a shared checkRateLimit, and
wires an opt-in [chat.rate_limit] config section through bootstrap with the
documented EvictStale ticker.
2026-09-15 01:24:20 +10:00
sam 55a4ac201b fix(webui): count every chat front-end in the published projection
GitHub #821 reported two dashboard behaviours degrading in the extracted UI
process because webui.Server.Cfg is nil there. Half of it was already closed:
19062a7 ("take configuration off the dashboard server", on main since
2026-09-12) moved the daemon's ConfigView renderer off webui.Server, gave
ConfigView a chat section carrying show_tool_calls, the operator name and a
channel flag, and pointed chatShowToolCalls and handleSetup at the projection.
The chat page and the checklist do read published values now.

The channel flag was still wrong. It was derived from telegram and the webhook
gateway only, while the daemon's own channel status manager lists three
front-ends and counts the inbound mail gateway as one. An email-only
deployment therefore read as configured on /api/channels and unconfigured on
the setup checklist at the same time, and the checklist told the operator to
connect a channel they already had.

Fix at the producer: config.ChatConfig gains FrontEnds, the single definition
of "this front-end is configured", enumerating telegram, email and the webhook
gateway. Both the published projection (ChannelConfigured) and the daemon's
channel descriptors (status.NewManager) now derive from it, so the two surfaces
cannot drift apart again. A front-end added to [chat] is counted by both or
neither. Whitespace-only values are not configured: an env var name of " "
resolves to nothing and " " cannot be listened on.

The setup checklist stays. It renders each step as a title, a detail and a done
mark with no control behind it, so it answers "what is this deployment
missing?" rather than promising to fix it; the process that cannot apply setup
never offered to. Removing it would delete the one surface that distinguishes a
fresh deployment from a finished one, and the values it reads already cross the
boundary in ConfigView at no cost to the daemon. The write path stays descoped
for Phase 3 (docs/prds/ui-service-boundary.md, /api/config (write) row): the
checklist reports configuration, it does not change it.

docs/prds/ui-service-boundary.md records that judgement and corrects the
"Real-process evidence" paragraph, which claimed the channel flag covered every
chat channel.
2026-09-14 10:53:16 +00:00
sam da28ddb5e6 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 1ffdedc62e feat(archied): serve the daemon's own health endpoint
The update watchdog verifies archied's restart, so archied has to be what
answers. It was probing the dashboard's /healthz, which belongs to the
dashboard: switch [web] off and nothing answers, and in the extracted UI
topology that endpoint reports a different process entirely, which would
confirm a release while the daemon it was meant to verify is down.

[health].listen (127.0.0.1:8485, defaulted, always on) serves /healthz,
/health and /health/detailed for the life of the process. Liveness answers
503 until the daemon reaches its run loop: the listener binds before the
subsystems do, so an unconditional 200 would tell the watchdog a half-booted
release came up. Failing to bind is fatal, because a daemon nothing can probe
gets every update rolled back. The State Store's readiness surface now shares
the listener plumbing, keeping its log and error text verbatim.

Closes archie-core-exbz, which asked which of two bad options to take when
the dashboard is off. Neither: the daemon owns its own liveness.

Also deletes TestInstallUpdateDetachesInstallerFromCallbackContext. It has
failed intermittently under load more than once, racing its fake bot server's
multipart parse against the cancellation it induces.
2026-09-09 23:29:11 +10:00
sam ac7b4492a2 fix(archieui): resolve service tokens from env and correct the stale State Store config comment
D1: the UI read [services.*].target_token verbatim, but the config loader does
not expand environment variables. A deployment that presents the gateway and
state tokens by env (as config.example.toml documents for remote consumers)
would leave archie-ui with an empty token, and staterpc.Dial then refuses a
non-loopback start. Mirror the daemon's stateStoreResolvedToken /
gatewayResolvedToken: explicit key, then GATEWAY_TOKEN / STATE_STORE_TOKEN.

D5: internal/config/services.go claimed the State Store service 'is not yet
extracted into its own process' and that target_token 'remains dead
configuration', both false since the daemon made an empty services.state.target
a hard startup error. State current truth.

D3: document that Web.Listen = 'off' is read with opposite meanings by the
dsaemon (disables the dashboard) and the UI process (falls through to the
default listener), pinning it as the one overloaded key an operator preparing
the split would set.
2026-09-09 02:38:16 +10:00
sam e6a2e5b3b4 feat(state-store): stand up archie-state-store binary and own archie.db (archie-core-8cda.4.3) (#771) 2026-09-07 03:41:32 +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 bf482f9d56 fix(gateway): drop services.gateway.mode, remote is the only transport
Mode had exactly one legal value after the previous commit deleted the
in-process path, which made it dead config surface that could only
confuse an operator into thinking there was still a real choice.
ServiceConnection is now just a target address; composeChatContract only
checks it's non-blank, defaulting to 127.0.0.1:8585.
2026-09-06 02:13:03 +10:00
sam 3d7666002c feat(contracts): add gateway service seams and protobuf toolchain 2026-09-05 22:57:45 +10:00
sam 7cdd7adb4e feat(telegram): support secret refs for bot tokens (#705) 2026-09-03 14:52:31 +10:00
sam e7afe2da8b feat(eda): playbook document + event coordinator, single-action workflow-kind dispatch
Seventh slice of docs/prds/eda-playbook-engine.md (t2db.15), consuming
t2db.14's expr package: the rich trigger+actions playbook document and
the coordinator that dispatches it.

- internal/domain/eda/playbook: Load(dir) reads *.yaml/*.yml playbook
  documents (trigger + exactly one workflow-kind action + optional CEL
  when), validating the HARD BOUNDARY at load: a playbook with 2+ actions
  or a non-workflow action position is a reported load failure --
  multi-action and Module/Channel/Forge actions stay blocked on the
  unresolved execution-time gaps. Any malformed YAML, invalid trigger,
  missing workflow name, or when compile failure fails the WHOLE load
  (reject-at-load, same shape as routing collisions); a missing dir is an
  empty store. Trigger reuses the existing workintake kind/label
  vocabulary (no second label-matching mechanism). Dispatch matches
  trigger, evaluates when (CEL, event context with actions: {} -- no
  prior actions in single-action playbooks), and returns the named
  workflow from the registry via the same lookup Route() uses -- no
  duplicated dispatch logic. when eval error follows the resolved doc's
  J3: false, skip, caller logs.
- Store.Dispatch(reg, DispatchInput) is the coordinator entrypoint; input
  carries Labels/Kind/Event. Production task intake wiring
  (daemon.go/pollNATS/publishTask) is explicitly NOT in this ticket -- a
  follow-up; proven end to end via direct tests plus the shipped example
  (examples/eda-playbooks/bug-tdd.yaml) loaded and dispatched through the
  real path.
- Config: EDAPlaybookDir (eda_playbook_dir), documented as DISTINCT from
  PlaybookDirs (flat binding files) -- a reader cannot confuse the two.
- Bootstrap: playbook.Load wired in loadWorkflows, log-and-abort on
  failure matching every prior slice; nonexistent dir is an empty store.
- workflow.Route(), workflowForLabels, and the t2db.9-.12 binding loaders
  are UNTOUCHED (verified: their full test suites pass, zero regressions).

Also carries small lint cleanups on t2db.13/.14 code flagged by the gate
run: expr Eval no longer type-asserts to ref.Val (Eval returns ref.Val
directly in v0.32.0; cel-go's own Eval wraps evaluation in recover --
verified in source); module decodeLogArgs extracted to clear the nestif
finding. golangci-lint: 0 issues.

Tests (10): single-action round trip, when-false skip, 2-action load
failure, non-workflow position load failure, when compile failure drops
playbook, empty trigger load failure, trigger mismatch skip, no-when
match, one-invalid-file fails whole load, missing dir empty store, plus
the shipped example load+dispatch. task check clean (113/113 UI, exit 0).
2026-09-03 04:05:59 +10:00
sam cba3a9a86d feat(eda): Module position first slice -- registry + side-effect-free log kind
Fifth slice of docs/prds/eda-playbook-engine.md (t2db.13), implementing
docs/prds/module-position.md's recommended first slice: prove schema ->
go:generate -> Yaegi load -> ModuleRegistry end to end with a
side-effect-free action kind, before any kind with a real external effect
(notify, image-gen, forge writes) -- those stay blocked on the parent
doc's unresolved execution-time gaps (idempotency, mid-run failure).

- internal/domain/eda/module/log: hand-written schema source (Args/Result/
  SchemaVersion per module-position.md) + logextract generated symbol
  table via go:generate yaegi extract (same tooling as wfextract/
  gateextract; scoped to ./internal/domain/eda/module/...).
- internal/domain/eda/module: ModuleRegistry with Register(kind, dir) /
  Invoke(ctx, kind, rawArgs). No generic Module interface with an any
  payload: each kind is its own tiny package with its own generated
  contract; the registry's internal storage is the only place erasure
  appears (exactly as inside wfextract). Invoke decodes rawArgs strictly
  into the kind's Args before calling the interpreted function -- an
  unknown key or wrong type is a reported failure, not a silent
  zero-value fill (the 'schema defines the accepted message' rule).
  Generalizes gateeval's fixed-signature Yaegi pattern via
  yaegiutil.New/Resolve/Safe -- no new interpreter-construction or
  panic-recovery mechanism.
- Config: ModuleDir mirroring PluginDir's shape and doc comment
  (operator-trusted directory of Yaegi module implementations, one .go
  per kind; empty means none loaded). Wired at daemon startup in
  bootstrap.go alongside PlaybookDirs loading -- log-and-abort on load
  failure (a broken module is a startup failure, not degrade-and-skip).
- examples/modules/log.go: operator-facing example (//go:build ignore,
  mirroring examples/secret-engines/) proving the shipped contract.

Tests: registry (register/invoke, unknown kind, missing file, strict
arg-decode shape failures, malformed file, panic recovery), logextract
smoke test, and an example-load test that runs the shipped
examples/modules/log.go through the real registry (not a test fixture).
task check clean (113/113 UI, exit 0).

Playbook YAML action dispatch is deliberately out of this slice: a
minimal 'run this one module action, no chaining' dispatch still requires
naming how args values reach the action (parent doc open question 1 --
data-flow/interpolation syntax) and what the result feeds, both
unresolved by design. Dispatch is a follow-up ticket that consumes this
registry as-is; recorded in module-position.md.
2026-09-03 03:35:18 +10:00
sam cf6c5f42d5 feat(workflow): load kind/label bindings from multiple playbook directories
Third slice of docs/prds/eda-playbook-engine.md (t2db.11), completing open
question 2: instead of a single playbook dir, the config gains a LIST of
directories (playbook_dirs) of *.yaml/*.yml binding files, loaded at
startup as an additional input to workflow_routing_file and
workflow_labels_file, which remain supported unchanged.

- LoadPlaybookDirs(dirs []string) reads every yaml file across the
  configured directories and merges kind + arbitrary-label bindings.
- This is what finally exercises the design doc's drop-and-report
  collision rule: a single file cannot collide with itself, so the
  cross-source path (two files in one dir, two dirs, or a dir plus a
  single-file field) had never run in production. A binding key declared
  by more than one source is a reported load failure, not a silent
  pick-one by source order or version.
- Router-level collision handling: MergeKindWorkflows/MergeLabelWorkflows
  fail on a key bound by both the single-file fields and the playbook
  dirs, applied at boot.
- Config: PlaybookDirs []string, empty by default (no behavior change for
  existing configs). Repo-scoping (typing dirs to Config.Repos owner/name)
  is explicitly deferred to a separate later decision per ticket;
  org/tenant keying is out of scope.
- PRD: records the list shape per Sam's correction (single dir would
  contradict multiple independently-maintained playbook sources).
2026-09-03 02:57:38 +10:00
sam 17e626dfba feat(workflow): route arbitrary forge labels to workflows via playbook YAML
Second slice of docs/prds/eda-playbook-engine.md, complementing the
kind->workflow layer (WorkflowRoutingFile): the label vocabulary itself
becomes playbook data. A label outside the closed bug/feature/bootstrap
kind set (e.g. security) now dispatches to a registered workflow from an
optional WorkflowLabelsFile, instead of falling through to triage.

- LabelWorkflows + LoadLabelWorkflowsYAML/SetLabelWorkflows in
  internal/domain/workflow/routing.go, mirroring the kind layer's
  once-at-startup lifecycle. The closed Kind/NATS-subject set is
  untouched; the map only extends binding authority for labels the kind
  layer does not own.
- Collision rule per design doc: a label owned by the kind set, an empty
  label, an empty workflow name, or a duplicate binding is a reported
  load failure (dropped, logged, error returned to the caller) -- the
  schema defines what is accepted; nothing is silently arbitrated by
  schema/version.
- Route() precedence: explicit t.Workflow -> arbitrary-label binding ->
  kind binding -> triage -> implement -> default.
- Config: WorkflowLabelsFile (workflow_labels_file), wired at boot
  alongside WorkflowRoutingFile; documented in config.example.toml.
- PRD: records this slice's decisions (single-file shape, collision rule,
  precedence) so later slices stay anchored.
2026-09-03 02:44:41 +10:00
sam 5268634f27 feat(workflow): make kind-to-workflow routing YAML-overridable
First slice of docs/prds/eda-playbook-engine.md: which registered
workflow an intake Kind (bug/feature/bootstrap) prefers is now data,
loaded from an optional WorkflowRoutingFile, instead of a Go literal.
labelKinds and the NATS-subject-per-kind set are unchanged -- expanding
the label vocabulary itself is a separate, larger decision (subject
allocation) deferred per the design doc's open questions.

An unrecognised kind in the file is a reported load failure (schema
defines what's accepted, per the design doc's collision-handling rule),
not a silently-dropped binding. No file configured falls back to
today's hardcoded defaults unchanged.
2026-09-03 02:35:42 +10:00
sam 7ee6ee5554 feat(store): encrypt playbook binding secrets at rest
binding.Binding.Secret was persisted as plaintext in the bindings.secret
column, so anyone with the SQLite file saw sender-side HMAC secrets. Seal
it with AES-256-GCM transparently inside the store: encrypt-on-write,
decrypt-on-read.

- cipher: AES-256-GCM, 12-byte random nonce, SHA-256-normalised 32-byte
  key resolved through the secret registry ([bindings].encryption_key).
- envelope 'arcie-binding:v1:<fingerprint>:<b64(nonce||ct||tag)>' so a
  future cipher/KDF change is a version bump and old rows stay readable.
- rotation via previous_encryption_keys; key identity is the material's
  SHA-256 fingerprint embedded in each row.
- legacy plaintext rows written before a key was configured stay readable;
  encryption is not retroactive.
- nil cipher (no key configured) preserves the pre-t2db.7 plaintext path.

Deferred: captured_events.body redaction upgrade (separate concern, see
docs/prds/binding-secret-encryption.md).

Refs archie-core-t2db.7
2026-09-02 23:54:06 +10:00
sam cfc296f17f feat(image): define provider-neutral image capability contract and config
Adds internal/domain/image (Provider/Registry per the plugin engine
family shape, but no Lifecycle -- a provider is call-scoped, not
long-running) and config.ImageConfig with the same explicit
enabled=true cost gate MinimaxConfig already uses, since a hosted
provider spends real API credits and a local one can saturate the
host GPU. Design doc at docs/prds/image-capability-contract.md per
CLAUDE.md's rule for undesigned capabilities.

No provider implementation lands here -- that's the epic's next
child bead. Also re-links all 7 epic children that were unlinked
from archie-core-1786748942120-1-6636e629 (same orphaning pattern
found in the curator/memory epics earlier this session).
2026-09-02 20:20:54 +10:00
sam f3abcb859e feat(config): config surface for memory engine selection
Part of archie-core-1786637490043 (config surface for memory engine
selection and settings).

config.MemoryConfig gets an Engine field selecting among the
domain/memory engine family, plus toml tags on every field -- Provider,
ProviderConfig, and SessionTTL had none before, yaml/json only, which
didn't match repo convention.

Engine and Provider are kept as two separate fields rather than one:
they select between two different mechanisms (the new engine family vs.
the legacy external-provider path, archie-core-1786637499161-356-e424e40d.1),
and conflating them would mean a value meant for one silently getting
read by the other once both are wired.

applyMemoryDefaults resolves an absent engine to "builtin" so
unconfigured and explicitly-builtin are the same state everywhere after
defaulting. validateMemory rejects an unrecognised engine name in the
same style as forge.type's existing validation -- named constant list,
"%w: field %q (want %s)" shape, wired into the same validate() chain.
config.example.toml documents the new field.

Not yet wired to anything: nothing reads cfg.Memory.Engine at daemon
boot yet to actually select and start an engine through
domain/memory.Registry. That's bootstrap wiring, tracked as the
remaining half of archie-core-1786637499480 (ship the builtin store as
the default engine).
2026-09-02 02:40:10 +10:00
sam 14d3a9461f feat(workflow): adversarial self-review stage before PR open
Implements archie-core-h019.3 (reviewer isolation) and h019.4 (wiring),
per docs/prds/adversarial-self-review.md.

- internal/domain/workflow: new Reviewer interface and StageReview,
  inserted between StageDiffCap and StageOpenPR in the implement
  workflow. Fail-closed: a review that didn't run, or a confirmed
  error-level finding, parks the task (store.StatusParked) with
  findings in Detail; warn/plausible findings never block. Inert
  unless Repo.ReviewEnabled.
- internal/worktree: Manager.Snapshot exports HEAD's tracked files into
  a fresh directory with no .git, for the reviewer's isolated
  workspace. Trees interface gains Snapshot; hybridTrees delegates to
  it.
- internal/app/agentworker: subagentReviewer implements Reviewer using
  ai-sdk's agent.Subagent (nested, in-process, non-streaming
  generation) -- conversation isolation is structural (Subagent.Run
  never carries message history), workspace isolation is the snapshot
  above. The reviewer's toolset is read-only (read/grep/find) rooted
  at the snapshot, never the worker's own toolset, so it cannot reach
  the worktreerpc publication grant. Findings are captured via a typed
  record_finding tool appending to a slice the stage owns, read even
  when Subagent.Run errors (a truncated run's captured findings
  survive).
- internal/config: Repo.ReviewEnabled (default false) and
  Models["reviewer"] (falls back to Models["builder"], no schema
  change).

Judgment calls: Reviewer.Review never returns a Go error -- every
failure folds into ReviewReport per the PRD's fail-closed contract,
which the stage can act on uniformly. A Subagent.Run error with zero
captured findings resolves to ReviewStatusNotRun (park); a
Subagent.Run error with >=1 captured findings resolves to
ReviewStatusCompleted with those findings, since the PRD's own example
("three defects survive a step-limit truncation") requires them to
still be evaluated for blocking rather than discarded.
2026-08-31 21:51:33 +10:00
sam 4b340d2b56 fix: harden task and chat execution
Task runs now preserve real model context limits, provider usage, baseline-repair spend, commit identity, durable agent-finish telemetry, and useful timeline details without imposing a token cap. Dashboard forge links are canonical per owning GitHub or Gitea identity. Chat turn claims acquire SQLite writer intent before reading, eliminating the concurrent SQLITE_BUSY snapshot race.
2026-08-25 05:48:17 +10:00
sam 29efce7049 fix(webui): validate mutation Origin against the effective external scheme
Origin validation compared the request's Origin against the daemon's own
direct connection: scheme from r.TLS, host from r.Host. Behind a TLS-
terminating reverse proxy the browser sends Origin: https://host while the
daemon sees a plain HTTP connection, so every dashboard mutation was
refused as cross-origin.

Taking X-Forwarded-Proto/-Host unconditionally would be worse than the bug:
any client can set them, so an exposed daemon would let an attacker forge
the scheme half of the CSRF check. They are honoured only when
web.trust_forwarded_headers is explicitly enabled, which is off by default
and documented as safe only behind a proxy that overwrites or strips
untrusted forwarded headers.

authorizeTaskMutation becomes a method because the decision now depends on
server configuration; its three call sites move with it.
2026-08-25 02:06:02 +10:00
sam 1f05dbb33c 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 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 9d73bc7157 feat(nats): expose embedded broker to managed workers 2026-08-24 14:56:57 +10:00
sam cc53e5258d fix(telegram): compact tool output and drop turn caps
Render completed ToolCallEvents as Telegram-safe streaming blocks
with compact name/status and a short cleaned preview. Summarize
file contents and listings instead of dumping source or quoted
JSON. Collapse repeated legacy turn-budget failures.

Remove max_tokens turn gating and the 200000 turn_budget_chars
default so absent or commented config cannot restore an aggregate
cap. Keep per-result max_result_chars and spill.

Confine find/grep discovery to the active workspace/worktree.

Refs #604
2026-08-23 16:40:16 +00:00
sam e04045907c feat(archied): wire generate_video end to end, gate it behind config
drainChatStream now detects a tools.MultimodalResult in a tool
result's Output and reports each URL via turn.Media(...), alongside
the existing turn.ToolCall(...) narration -- the missing link between
a tool producing media and a channel delivering it.

MinimaxConfig registers the tool only once an API key actually
resolves (registerMinimaxTool), matching web_fetch's "never advertise
a broken capability" pattern. Off by default, unlike web_fetch: this
spends real API credits per call.
2026-08-23 02:48:25 +10:00
sam 875b7a50d5 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
e19ff3a (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 51bb80f6a1 feat(nats): run an embedded server when no external NATS is configured
Wire github.com/nats-io/nats-server/v2 into production startup so a
single-process deployment gets reaction delivery and task distribution
over an in-process server rather than a separate one
(docs/prds/embedded-nats.md).

Meaning change: [nats].url empty used to mean "no NATS, use the SQLite
ClaimNext flow"; it now means "start an embedded NATS server". The old
behaviour is the explicit opt-out [nats].mode = "off". mode resolves from
url when unset (url set -> external, url empty -> embedded), and
agent.mode="nats" / [containers] now require mode="external" (an embedded
loopback server cannot be reached by agent workers or containers).

The daemon owns the embedded server's lifecycle: StartEmbedded before
dialing the client, Shutdown after the client closes (LIFO cleanups). The
embedded server binds loopback on a random port, enables JetStream in a
store dir under the data directory, and leaves its logger nil so a startup
failure surfaces as a Connect error rather than an os.Exit.

Retention becomes a nats.Config field (default WorkQueuePolicy) so a future
reaction stream can fan out under LimitsPolicy instead of the hardcoded
competing-consumer policy that starves a second consumer on overlapping
subjects.
2026-08-22 05:18:31 +10:00
sam 101c133239 feat(capture): store unbound webhook events, retention-bounded
Adds POST /webhooks/capture/{source}: an unauthenticated endpoint (mounted
alongside /healthz, bypassing dashboard token auth by design) that persists
any inbound webhook archie has no binding for yet, so it can be inspected
and mapped later (t2db.2/t2db.3).

docs/prds/event-capture-storage.md decides SQLite over NATS JetStream for
storage: NATS is not unconditionally available until 7d5u.2 ships embedded
support, and capture's single-writer/single-reader access pattern doesn't
need JetStream's fan-out/replay machinery anyway.

internal/store/captures.go adds a captured_events table with prune-on-write
(retention age + row-count cap, both configurable). The HTTP handler applies
webhookguard redaction before persisting, and enforces two more independent
disk-bound mechanics before that: a per-request body-size cap and a
per-remote-address rate limit. New [capture] config section with documented
defaults; all fields optional, capture is on by default.

Adversarial review (manual, after the usual fresh-subagent pass hit a
session API limit mid-run) caught and fixed three real defects before this
landed, each with a regression test confirmed to fail against the pre-fix
code:
- the body-size cap silently no-op'd when CaptureMaxBodyBytes was left
  unset, the one bound that limits a single payload's size rather than row
  count or write rate
- the rate limiter was keyed by the request's own source path segment --
  unregistered and attacker-chosen by design for this endpoint, violating
  webhookguard.RateLimiter's documented bounded-key-space assumption and
  letting a sender bypass the limit by rotating the segment; rekeyed to
  remote address
- the retention prune compared time.RFC3339Nano strings, whose trimmed
  variable-width fractional seconds break lexicographic ordering within the
  same second; switched to fixed-width RFC3339

Closes archie-core-t2db.1.
2026-08-22 04:51:25 +10:00
sam 8239e8e935 style: apply gofumpt formatting 2026-08-17 00:02:31 +10:00
sam ddfc8a7b91 fix(config,webui): make show_tool_calls one cross-channel setting
show_tool_calls gated Telegram's tool-activity narration only; the
web dashboard's SSE chat stream narrated every completed tool call
unconditionally with no way to turn it off, leaking tool names and
parameter shapes to anyone with dashboard access even when an
operator had already opted out for Telegram.

Moved ShowToolCalls from TelegramConfig to ChatConfig so it is one
setting for every channel, and wired the webui stream to it:
chatStreamSink now carries a showToolCalls flag (snapshotted once per
turn, mirroring how Telegram's liveReply snapshots it) and ToolCall
no-ops when it's off.

BREAKING: an existing [chat.telegram] show_tool_calls = true in
config.toml now parses as an unrecognized key under [chat.telegram]
and is silently ignored (TOML decoding is non-strict) rather than
erroring -- move it to the top-level [chat] table.
2026-08-15 01:57:06 +10:00
sam 0d73f2fa5a feat(chat): show tool calls inline and stream replies into one message
Chat returned only the final answer, so a wrong tool choice, a
hallucinated action, or a footgun like `systemctl stop` against
`restart` was invisible from the conversation. Only text deltas were
threaded through the turn, and tool calls executed inside Generate with
nowhere to report.

Replace the delta callback with gateway.TurnStream, which carries text
fragments and completed tool calls on one ordered path from the model
loop to the channel. The sequence is the point: a tool line that
overtakes the sentence it interrupted describes a turn that never
happened. Text-only callers use gateway.DeltaFunc and are unaffected.

A tool is reported on its result, never on its call  --  the call part
carries no outcome yet, so reporting both would list every tool twice,
once with nothing to say.

Telegram renders it behind [chat.telegram] show_tool_calls, off by
default: this is debugging visibility, and it narrates every internal
step to provide it. The dashboard always shows it, being the operator's
own observability surface; its tool lines are live-only and are not
persisted with the conversation.

The Telegram live reply changes mechanism, and with it what a frame
MEANS. It used to stream through sendMessageDraft: drafts are ephemeral
30-second previews, so a tool call longer than that outlived the
preview, and successive frames were observed concatenated with their
cursors intact. It now sends one real message and edits it. An update
used to be "the next preview of the answer"; it is now "the whole
answer as it currently stands, replacing what is there". The cursor is
appended at render time and never stored, so exactly one exists and
always at the end, and a frame too long for one message is cut to its
tail rather than rejected outright.

A stopped or failed turn now edits the cursor away instead of leaving
it blinking on a message nothing will finish. That cleanup runs on a
live context because turnCtx is already dead, and it runs on both
failure branches: ai-sdk raises an aborted stream as ErrAborted with
ctx.Err() formatted in rather than wrapped, so errors.Is cannot be
trusted to tell a /stop from a fault.

Closes #467
2026-08-14 02:36:12 +10:00
sam 3802ed473d fix(config): preserve nil slices in Clone to avoid spurious reload warnings
Clone normalized nil slices to empty non-nil (make([]T, 0)), so after a
dashboard PATCH the cloned published config carried [] where the file
decodes to nil -- a subsequent SIGHUP reload's diff-and-warn compared
old [] against fresh nil and reported 'Repos changed; requires a
restart' for a field that had not changed at all. The exact warning
fatigue the allowlist exists to prevent. cloneRepos/cloneIdentities/
cloneMCPServers/cloneStringSlices now return nil for nil input (the
append-based copies already preserved nilness).
2026-08-10 01:41:20 +10:00