Brings the chat surface to the Web UI: /api/chat with its own handlers
and tests, a self-contained ui/src/chat feature folder, and the shared
plumbing to reach the same router Telegram uses.
Includes a dangerous-command approval path (internal/gateway/dangerous.go,
internal/webui/dangerous.go, and the Telegram counterpart) so /rollback
and /stop are gated the same way on both surfaces, persona handling for
web sessions, and release-update formatting split out of the Telegram
service so both can render it.
web_parity_test.go pins that the two surfaces expose the same commands.
Authored in a parallel session; committed here so it lands with the rest
rather than sitting uncommitted while other work builds on top of it.
task check passes with it in place.
Screenshots used while building are gitignored (*.png) rather than
committed, matching the call made on the earlier design reference.
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.
The dashboard and chat both let an operator approve or refuse work, and
they had drifted. Declining from the dashboard left the task
closed_wont_do; cancelling the same task from chat left it rejected. Two
operators looking at one queue saw different states for the same
decision, and "rejected" -- which reconcilePRs also uses for a pull
request closed without merging -- stopped meaning one thing.
internal/gateway deliberately does not import internal/store, so it kept
a hand-synced copy of the status strings with a comment asking future
editors to keep them aligned. That is the same defect one level down,
and it is how the drift happened.
internal/taskstate is a leaf package with no dependencies holding the
lifecycle vocabulary and the rules for operator actions. gateway, store
and the dashboard all import it, so gateway stays decoupled from store
without a copy, and CheckApprove/CheckRetry/CheckDecline have one
implementation. Declined is named for what it is -- a human said no --
and stays distinct from Rejected, which is something archie observed.
Chat cancel now records Declined. That is the behaviour change: same
decision, same state, whichever surface the operator used.
Rules were preserved rather than tidied while unifying. A parked task
still cannot be declined, which both surfaces already refused, even
though "not terminal" would have allowed it -- widening a rule under
cover of a refactor is how you ship a change nobody reviewed. The
comment says where to change it if that is ever wanted.
TestDashboardAndChatAgreeOnTerminalStates drives both real surfaces
against one store, so this cannot drift apart again without a red test.
Also removes a second rule for the dash-top-standalone class: renderSetup
already reconciles it from the data at the top of every call, and a later
branch cleared it again. Harmless, but it reads as two sources of truth
for one bit of layout state.
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.
provider.Registry.Start was atomic for every provider: one failure
unregistered every other provider including the builtins, returned an
error up through the capability host, and exited archied. Under
Restart=on-failure that is a crash loop. Observed on carina 2026-07-30 --
mcp.desktop-commander could not start because the runtime image was
missing unzip, and the daemon restarted continuously, losing chat, the
gateway and every builtin tool over one third-party npm package.
Atomicity is right for a provider archied requires. It is wrong for an
external MCP server pulled from a registry at runtime, which is exactly
the category allowed to be absent -- the same reasoning already applied
to the forge, and to containers.
RegisterOptional marks a provider the daemon can run without. Its
failure to start, discover or index stops only itself and excludes it;
Register keeps today's rollback. Required/optional is a deployment fact
rather than a property of the code, so the registrar states it instead
of the engine declaring it in its own manifest -- which also keeps
plugin.Manifest metadata-only, per the plugin engine rule.
A skipped provider's dependents cannot run either: an optional dependent
is skipped with the reason, a required one is a hard failure, since it
declared it cannot work without something now absent.
Degradation is reported, not silent -- Health goes degraded naming each
provider and cause, Skipped() exposes the set, and the daemon logs one
error line per exclusion. Silence is how this went unnoticed until the
crash loop. A provider that half-started before failing is still
stopped, so no child process is left behind.
The regression test drives the real capability host, the path main.go
calls: with desktop-commander registered as required it fails with the
verbatim carina error, and as optional the daemon starts with its
builtins intact.
Closes archie-core-ky6
Making the store idempotent stopped redelivery duplicating the inbound
record, but nothing consulted that result: respond() saved the message,
ignored the fact that nothing had changed, and called the model anyway.
The cost was a second billed turn, any tool side effects run a second
time, and a second assistant reply appended -- replies carry no upstream
reference, so they always get a fresh identity and always append. The
stated problem, "a re-delivered update appends a duplicate turn", was
only half fixed.
PriorReply answers "have I already replied to this?" from the history
the caller has already loaded, and the chat path replays that answer
instead of regenerating it. A message with nothing after it was never
answered -- the turn may have died partway -- so that still runs, since
the user is owed a reply.
CanonicalMessageID exposes the store's own derivation rather than
letting the caller reimplement it, since a lookup that silently never
matches is indistinguishable from a message never seen.
Refs archie-core-i6q
d615de5 made an unusable memory directory fatal. That was the wrong
call and contradicts the forge and container paths: memory is one
capability among many, and refusing to start over a path denies the
operator chat, the dashboard and everything else -- then crash-loops
under Restart=on-failure with the real error scrolling past unread.
builtin.New now reports an unusable directory through IsAvailable and
Err rather than failing, so the caller decides. The daemon warns and
falls back to the location an unset work_dir would have produced, which
is where someone who copied a config from another host will look. If
that is unusable too it says what the operator loses -- no recollection
between conversations, and failing writes -- and carries on.
The provider stays readable while degraded, so a bad path reads as an
empty memory rather than breaking mid-conversation, and the dashboard's
memory page already renders IsAvailable so this is visible there.
Also fixes a defect the fallback test caught: an empty work_dir made
filepath.Join produce the relative path "memory", which MkdirAll
creates wherever the daemon was started from -- succeeding, and putting
memory somewhere nobody would look.
Refs archie-core-rml
The old UI was a single 200-line Go file serving one hand-written HTML
page of task rows. It showed that archied was running and almost nothing
about what it was doing -- skills, workflows, memory, channels, logs and
configuration were all invisible unless you read the source or the
config file.
The dashboard now covers each of those as its own section, built as a
Vite app under ui/ at the repo root: it is a separate artefact from the
Go daemon, not an internal package of it. dist/ is committed so building
archied never needs a Node toolchain, and the !no_ui build tag keeps an
embed-free build available.
Both sides are split by concern rather than by layer -- one Go file per
API area, one folder per UI section with its own CSS -- so a change to
logs cannot disturb tasks.
Pages report consequences, not just state: an empty memory page says
Archie starts every conversation with no recollection of earlier ones,
and the setup checklist names what is missing in plain language instead
of showing a grid of zeroes. Nothing greets by a hardcoded name; the
operator comes from [chat], which is deployment data.
Auth is exposure control, not capability control -- the agent already
holds this user's authority through its own tools. So a loopback bind
needs no token, and only a reachable bind mints one and logs a URL,
which means an instance cannot be exposed merely by omitting config.
Container startup now degrades instead of aborting, for the reason
resolveForge already does: a missing agent image should not deny the
operator chat and the dashboard, and under Restart=on-failure it turns a
recoverable problem into a crash loop with the real error scrolling past.
`task dev` runs the daemon under air and the Vite server together in one
terminal.
Under systemd, journald held the only copy of archied's output, and
running it by hand left no record at all -- so "where are the logs?" had
no good answer, and the dashboard had no history to show from before it
connected. [log] adds a file destination alongside stderr, with
size-based rotation and retention done in-package rather than pulling in
a dependency for a few hundred lines.
A file that cannot be opened is reported and the daemon continues on
stderr: losing the durable copy is not worth refusing to start over.
reader.go owns the on-disk format so nothing else has to parse it, and
bounds every read -- tailing keeps the newest entries within a fixed
scan window, so pointing it at a large file cannot exhaust memory.
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
These asserted on file contents rather than what the code does:
Dockerfile strings, deploy.yml YAML, CHANGELOG headings, and greps of
main.go for identifiers. Two also referenced config.docker.toml and
docker-compose.yml, which were never committed, so they could not pass
at all.
The worst compared strings.Index byte offsets in main.go to assert
startup ordering -- it would pass on code that never runs and fail on
a correct refactor that moved a line.
WriteTaskJSON wrote task.json to the worktree root -- the same worktree
the agent commits from. CommitAll stages with go-git's All option, and
go-git's Add does not honour .gitignore or .git/info/exclude, so the
brief was swept into the agent's commit and pushed onto every task
branch. That is how a task.json for issue #57 ended up committed in
the repo root.
This is the identical failure the prepared sentinel hit; worktree.go
already documents the fix. Nothing under .git can ever be tracked, so
put the brief there rather than papering over it with an exclude.
An unresolvable forge token aborted startup with exit 1, denying the
operator chat, the gateway and every other subsystem over a capability
they may not use -- and under the installed unit (Restart=on-failure,
RestartSec=5s) it crash-looped where the error was never read.
Forge setup moves into resolveForge, shared by the primary forge and
each configured identity, and degrades to NoopForge with a warning.
Malformed config still fails fast in validation. The systemd unit gains
StartLimitIntervalSec/StartLimitBurst as a backstop for other failures.
/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.
/stop could not reach a running turn, and the reason was worse than a
missing cancel. go-telegram/bot runs one update worker that calls
handlers synchronously (defaultWorkers = 1, never overridden), and the
chat turn ran on it. While a turn streamed -- or sat in a shell tool --
the worker was blocked and /stop sat unread in the update channel until
the turn it was meant to kill had already finished.
Add gateway.Turns: a per-session serial lane that turns are submitted to
and that the event loop never waits on. The worker is free again in
microseconds, so /stop is serviced immediately; ordering comes from the
lane being serial rather than from the loop being blocked.
- Bare /stop cancels the running turn and clears the backlog behind it,
with no approval step. Approval guards destructive commands, and
gating the brake behind a confirmation defeats it. /stop <name> keeps
the existing process-termination behaviour and its approval.
- Cancellation propagates through the turn context, so it reaches the
model stream and any tool underneath -- a shell command built with
exec.CommandContext dies with the turn.
- Queues are unbounded and never shed. A dropped message is a silent
failure that surfaces later as an agent that ignored something.
- Turns are recovered per-lane: the channel's panic middleware wraps the
event-loop goroutine, which no longer runs the turn.
Also raise the chat step budget. It was hardcoded at 8 -- roughly one
read, one grep and two edits -- so turns hit the cap and stopped
mid-task with no indication they had been cut off. It is now
chat.max_steps, defaulting to 100. Interruption is /stop's job.
The chat agent had two tools -- memory_edit and skill_activate -- so it
could not read a file, search a tree or run a command. ai-sdk's runtime
already drives a tool loop for it (MaxSteps 8, toolExecute wired as the
executor), so the loop was never the missing piece: the registry was empty
of anything useful.
Lifted from tau internal/agent/tools at commit f5289ea, per the recorded
copy-and-mutate strategy: every file carries a provenance header naming its
tau source path, the commit, and the mutations made, so refreshing from
upstream is a diff rather than archaeology.
internal/tools/builtin/ the lifted tools, ~3.1k lines
internal/tools/provider/builtin/ the adapter to tools.ToolEntry
Six tools: read, write, edit, shell, grep, find. Tau's own tests came with
them and pass unmodified, which is the evidence that the lift is faithful.
Deliberately not lifted:
- agent.go (1214 lines): subagent spawning, and the only real coupling in
the package -- 10 tau packages including chat, sessions, store and
registry. Nothing the chat agent needs to do work.
- skill.go: depends on tau's skills package; archie has internal/skill and
already exposes skill_activate.
- docs.go: serves tau's own embedded documentation via tau/docs.
Not lifting the coordinator either. It is tau's agent loop (6.4k lines over
ten packages) and archie already has one in the ai-sdk runtime; porting it
would leave two loops competing. Its cancellation and tool events are worth
having, but they are a few hundred lines built against the existing path
rather than six thousand lifted onto a second one.
The adapter bridges two shape differences: archie hands handlers decoded
arguments where tau's executor takes raw JSON, and tau reports tool-level
failure in Result.IsError rather than as an error -- surfaced as a real
error so the runtime and the guardrail engine both see it. Tools are
classified idempotent or mutating for guardrails and budgets; that is
categorisation, not a jail.
chat.workspace roots the tools and defaults to empty, which registers none
of them. They read, write and execute, so the directory has to be a
deliberate choice rather than whatever the daemon started in -- in the
container that is /.
Verified: go build, go vet, gofmt clean; full suite passes.
Three defects found from a real Telegram transcript.
1. The operator's name was compiled into the prompt.
internal/gateway/persona.go and prompt.go both hardcoded "Sam's" into the
default persona and the fallback prompt. The persona renders first into
every system prompt, so a personal name was sent to the model provider on
every turn, and any other deployment got an assistant that believed it
worked for someone else. There was nowhere to put it: Repo.Owner is a repo
owner and config.Config had no operator concept.
ChatConfig.Operator now carries it, rendered in the prompt's <env> block as
runtime metadata and omitted entirely when unset. config.example.toml
documents that setting it sends the name to the model provider.
2. /new claimed to clear history that it had not cleared.
The chat responder keyed history by channel id through a local sessionKey
helper, while the session commands operate on tracked session ids.
sessionTracker.resolve mints deterministic ids so the two agree -- until
/new, /branch or /resume assigns a generated id, after which they address
different histories permanently. /new reported "Conversation history has
been cleared" while the next turn still saw everything, and /undo,
/compress, /resume and /sessions acted on a namespace the conversation
never read.
gateway.Router.ResolveSessionKey already existed for this, and
session_commands.go:104 said outright that main.go should call it instead of
its inline helper. It never got wired. The responder now resolves through
the router and the dead helper is deleted so it cannot come back.
buildTelegramRouter constructs the router before the responder so the
dependency is visible rather than captured by reference.
3. Prompt rules for two behaviours the transcript showed.
The agent offered to accept shell access it has no tool to use, which is
both unhonourable and a request for the user's secrets. It also opened
mid-conversation replies with a greeting, and described its own manner
("no fluff") in stock phrasing. Added core rule 7 and three communication
rules covering greetings, self-description and register.
Note the memory claim in that transcript was NOT a fabrication: the
memory_edit tool's own description names MEMORY.md and USER.md, and tool
descriptions are part of the prompt.
Also added chat-turn logging (session id, channel, thread, history depth).
Chat turns were entirely unlogged, so a report of lost context had no
evidence to check: 76 log lines covered two days and none of them was a
conversation. A separate report of mid-conversation amnesia remains
undiagnosed -- single process, 43h uptime, compression untriggered at three
messages -- and this is what makes it diagnosable next time.
Regression tests: prompt renders/omits the operator and carries no personal
name; the responder resolves via ResolveSessionKey and defines no local
session key helper.
Verified: go build, go vet, gofmt clean; full suite passes.
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.
internal/config both defined the types every package imports and performed
the file I/O to produce them. Importing a settings struct therefore pulled
in a TOML decoder and a YAML decoder, and the shared model owned discovery,
decoding, overlays, defaulting and validation all at once. See
docs/architecture/configuration.md, which requires loading to move out and
internal/config to be dissolved.
internal/config is now types only -- no os, no filepath, no toml. The new
package owns loading, one concern per file:
features.go the closed set of recognised feature files
discovery.go directory scan and classification
decode.go TOML/YAML decoding, format dispatch
defaults.go filling absent values, no errors
validate.go judging supplied values, no mutation
provenance.go which file contributed what
loader.go Loader wiring the above; File/Overlay/Dir
Beyond relocating, this fixes what the old code conflated:
- Defaulting and validation were interleaved. applyAgentDefaults and
applyDispatchDefaults returned validation errors; validateContainers and
validateSingleIdentity quietly mutated the config. There was no point at
which you could see what the operator actually supplied. They are now
separate passes: applyDefaults never fails, validate never writes.
- Errors were fmt.Errorf strings prefixed "config: ", so a caller could not
distinguish operator-fixable input from an unreadable file without
matching message text. Five sentinels now carry that distinction.
- dataHome() read XDG_DATA_HOME directly and discarded the error from
os.UserHomeDir, so defaulting could not be tested without the
environment. It is injectable on Loader and no longer swallows the error.
- Nothing recorded where a value came from. With overlays, feature files
and conf.d/ all able to set the same field, "which file set this?" was
answerable only by re-deriving precedence by hand. Provenance records it.
- Feature files were applied in map iteration order, making load order and
any resulting error arbitrary. Discovery now returns them sorted.
- loadMainConfig reported "no config.yaml or config.toml found in %s" with
an empty string: the directory was lost when it was extracted from
loadDirInto, so the error named no directory.
- Unreadable or malformed conf.d/ extras were skipped silently, which
presents as a setting the operator wrote simply not taking effect.
- Decode errors from the main config were returned bare, without naming
the file that failed to parse.
The 40 loader tests moved with the code and their assertions are unchanged,
so the defaulting and validation rewrite is behaviour-preserving.
Document.Config is the temporary seam: still internal/config.Config, named
as a field so the compromise is visible at each use site, with its deletion
condition recorded in doc.go. Building typed per-domain sections now, while
every consumer still reads config.Config, would mean two shapes kept in sync
by hand with no consumer for the new one; that belongs with the dissolution
work, not ahead of it.
No consumer outside cmd/archied changed.
Verified: go build, go vet, gofmt clean; go test ./internal/config/... and
./internal/infrastructure/configuration/... pass. Pre-existing gateway and
telegram failures are unchanged.
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.
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.
Add gateway/runtime-owned commands that remain usable when LLM credits
are exhausted:
- /start — acknowledgement without consuming a reply
- /new [name] (alias: /reset) — create a fresh session
- /topic [off|help|<session-id>] — session switching for threaded chats
- /retry — remove last assistant message, replay last user turn
- /undo [N] — remove last N messages from history (default: 1)
- /title [name] — set or display session title
- /branch [name] (alias: /fork) — create child session with inherited history
- /compress [here N|focus topic|--preview|--dry-run] (alias: /compact)
Design:
- sessionTracker maps channel+thread to active session, auto-creating
implicit sessions with the legacy sessionKey format for backward
compatibility with existing persisted data
- /new and /branch create explicit UUID-backed sessions
- SessionStore extended with DeleteRecentMessages, MessageCount, and
SaveMessages for undo/retry/branch/compress operations
- SessionContext extended with Title, ParentSessionID, BranchName
- All commands report 'not configured' when session store isn't wired
Session resolution is wired into the LLM responder so /new, /branch,
and /topic switches affect subsequent chat turns.
golangci-lint run --fix plus the formatters: errorlint, gocritic,
sloglint, usestdlibvars, usetesting, gci, gofumpt, goimports.
160 issues -> 130.
One autofix was wrong and had to be reverted by hand. gocritic rewrote
ctx, cancel = context.WithTimeout(ctx, m.prefetchTimeout)
to `:=` inside an if-block in internal/memory/manager.go. That does not
compile, which is the good outcome — had it compiled, the shadowed ctx
would have scoped the timeout to the if-block and the prefetch deadline
would silently never have applied. Restored the assignment and commented
why it must not be a declaration.
Worth recording: --fix is not a safe no-op. It broke the build on a
24-file change, and the failure mode it was one compiler error away from
was a silent behaviour change.
First slice of the tau cherry-pick strategy: copy-and-mutate rather than
extracting tau to pkg/. Exporting would force designing metrics, session
and logger seams upfront, before archie-core knows which of them it wants
differently — a cost paid for reuse not yet proven. ai-sdk earned library
status by stabilising across two consumers; nothing in tau/internal has.
indexing is the cheapest high-value lift: 512 LoC, one file, and its only
coupling to tau was three calls to process-global config path helpers.
Nothing else in tau imports it.
Mutations from upstream:
- path helpers become an explicit indexing.Config. Two archied instances
share a host (archie and winter), so they must not share one index.
- the child-process helper is archied's own workspace-codesearch
subcommand, dispatched before flag parsing so it touches no config,
store or NATS.
- deferred db.Close calls explicitly discarded; archie-core runs errcheck.
The child process is not incidental: google/codesearch calls fatal exits on
a corrupt index and leaks mmapped regions. Verified end to end against this
repo — 2.2MB indexed, correct hits for BuildSystemPrompt, [] for no match,
and a deliberately corrupted index returns "corrupt index" with exit 1
instead of taking the process down.
Every lifted file carries a provenance header naming its tau path and
commit (4893818d0c76), so refreshing from upstream is a diff rather than
archaeology.
The chat agent's entire system prompt was the four-sentence static string
in gateway.DefaultPersonas(). It carried no tool inventory, no environment
block and no instruction precedence, so the model invented its own
capabilities: asked to set something up it announced it "only has the
memory editing tool", then offered to walk through installing software it
has no tool to install.
Renders a template modelled on tau's agent.md.tpl + tau.agent.md:
instruction precedence, core rules, communication rules, a <tools> block
and an <env> block. The persona stays the style layer on top; the rules
and the tool inventory live in the template so switching persona cannot
remove them.
The tool list is derived from the same core.ToolSet handed to the model,
so the prompt cannot drift from what the agent can actually call, and an
empty toolset renders an explicit "no tools are available" rather than
silence the model fills in for itself.
Tool metadata is third-party data from MCP servers, so it is markup-escaped
(<, >, & only — not xml.EscapeText, which mangles prose into 
/')
and whitespace-flattened, so a description cannot forge a closing tag or a
second "- tool: ..." list entry.
Operator escape hatch: reload gateway config (notably the sender
allowlist) or recover a wedged adapter from chat, with no shell access to
the host.
Start becomes a supervisor loop that relaunches the bot on request, so a
restart is scoped to the gateway: the daemon keeps running and in-flight
agent tasks are untouched. Exiting the process would also have restarted
under the unless-stopped policy, but would have killed running work.
Two failure modes are handled deliberately:
- The handler runs on the very bot the supervisor is about to stop, so it
hands off over a buffered channel and returns instead of tearing down
inline, which would deadlock the restart it just requested. A duplicate
request while one is in flight is dropped, not queued.
- A failed config reload logs and relaunches on the previous settings, so
a bad config edit cannot take chat down permanently -- which would also
remove the means to fix it.
Authorisation is inherited from authorizedMessage: only allowlisted
senders reach any handler, so /restart is admin-only by construction.
main.go supplies Reload, which re-reads config from disk and refreshes
token and allowlist; other fields still need a full daemon restart, since
they are wired at construction.
Allowlist (16.33). telegram.New was called with a nil allowlist and
isChatAllowed returned true whenever the list was empty, so any Telegram
user who found the bot could talk to it; AllowedChatIDs was not plumbed
into config, so there was no way to close it. Chat tools run with the
daemon's own authority, so this had to be fixed before wiring any real
tools to the chat agent.
Now chat.telegram.allowed_user_ids configures it and an empty list denies
everyone: a bot handle is public, so failing open is not a safe default.
The check matches the sender (from.id) rather than the chat, so adding
the bot to a group cannot be used to inherit access. Rejections log the
sender id and answer once, so a legitimate user missing from the list can
tell the bot is misconfigured rather than dead. Startup warns when the
gateway is enabled with an empty list.
The previous TestIsChatAllowed asserted 'empty allowlist allows all' --
it encoded the vulnerability -- and is replaced by fail-closed tests.
Command menu (16.34). SetMyCommands was never called, so Telegram showed
no menu and the commands Router implements were undiscoverable; asked
about /commands the LLM confidently answered it had none. The published
list mirrors what Router actually handles. Failure is logged, not fatal:
it costs discoverability, not function.
Streamed chat replies hung on the first token: the draft rendered an
empty cursor, the typing indicator never cleared, and the turn never
completed.
RouteStream consumed stream.TextStream, but ai-sdk's channel contract
makes FullStream authoritative and requires draining it until close --
its writes are synchronous, so an unread FullStream applies backpressure
and stalls the producer. Once its buffer filled, the producer blocked,
TextStream stopped yielding, and the range loop blocked forever.
TextStream was the wrong source regardless: it is explicitly best-effort
and drops deltas when not drained, so a reply reconstructed from it can
silently lose text. Range over FullStream and collect StreamPartTextDelta
parts, exactly as the SDK documents.
Also bumps ai-sdk v0.1.17 -> v0.1.18 (build, full suite and lint clean).
Upgrades go-telegram/bot v1.18.0 -> v1.22.0 and uses the Bot API's rich
message support instead of hand-rolled formatting.
The previous commit converted LLM Markdown into Telegram's HTML subset,
on the premise that the API could not take Markdown directly and had no
table element. Both are true of v1.18.0 but not of v1.22.0, which adds
sendRichMessage/sendRichMessageDraft taking InputRichMessage{Markdown},
plus RichBlockTableCell for native tables. markdownToHTML and its tests
are deleted: LLM Markdown, tables included, now goes to Telegram as-is.
Replies also stream. runtime.ChatStream already returned a TextStream
and sendRichMessageDraft renders partial output, so the only missing
piece was a gateway seam: gateway.LLMStreamResponder plus Router.
RouteStream, which degrades to the blocking Route when unset so any
adapter can call it unconditionally. Local commands answer from local
state and are not streamed; an unrecognised /command is, since Route
hands it to the LLM. main.go derives both responders from one shared
turn implementation.
Draft updates are throttled to one per 700ms to respect per-chat rate
limits, and every streaming/rich path falls back rather than dropping a
reply: a rejected rich send retries unformatted, and a failed draft
update is skipped since the final message is authoritative.
archied's container-mode agent tasks were all failing with "nats: no
responders available for request" in production. Root cause: pool.go's
selfNetwork() auto-detects the daemon's own Docker network by looking up
a container named after os.Hostname(), then joins spawned agent
containers to that same network so they can resolve "nats" by name.
On carina this detection was silently failing (wrong/stale hostname vs.
actual container ID) and returning "", so every per-task agent container
landed on the default bridge network instead — unable to resolve "nats",
never subscribing, hence "no responders" on every request.
selfNetwork() swallowed every failure silently (only logged on success),
so this had no diagnostic trail.
Fix: added Containers.Network config field (containers.network in
config.toml) so deployments can name the network explicitly instead of
relying on fragile self-detection; selfNetwork() remains as a fallback
but now logs a warning on every failure path so this doesn't silently
recur. Wired through container.Config and cmd/archied/main.go.
Checkpoint commit covering concurrent work across several archie-core-abg
epics to avoid losing in-progress state:
- Memory manager (18.7-18.16): background sync pipeline, prefetch with
timeout, memory-write notification, threat scanning, shutdown drain
with abandoned-write tracking, frozen snapshot pattern. Wired
ScanContent and NotifyMemoryToolWrite into HandleToolCall so scanning
and notification actually apply to writes, not just exist as unused
primitives.
- Fixed a literal unresolved merge-conflict that had been committed to
internal/memory/scrubber/scrubber.go.
- Tool provider/registry, MCP client/transport (stdio, HTTP, SSE),
multimodal results, disclosure.
- Pairing device auth store, rate limiting.
- Gateway compression, session store, tasks.
- Various workflow, plugin host, and agentexec updates.
Adds internal/secret: a pluggable Engine interface (Name/Version/Resolve)
resolved through a Registry, so secrets backends (sops, Bitwarden Secrets
Manager, Vault/OpenBao) aren't hard-coded into the binary. Only the "env"
engine is compiled in; custom engines are Yaegi-interpreted .go plugins
loaded via Registry.LoadDir, mirroring internal/plugin's conventions
(secretextract provides the generated, nil-guarded symbol table for the
Yaegi/Go interface boundary).
config.Forge.TokenEnv is replaced end-to-end with config.Forge.Token
(secret.SecretRef{Engine, Key}) -- finalize() defaulting, forge token
resolution in cmd/archied/main.go, and per-identity validation that now
requires an explicit token instead of silently resolving to "". No
backwards-compat shim.
Provider.APIKeyEnv, NATSConfig.TokenEnv, and TelegramConfig.TokenEnv are
deliberately not migrated here -- they're forwarded by name to
ai-sdk/runtime and subprocess workers rather than resolved centrally,
which needs its own eager-resolve-then-inject design pass
(archie-core-xec.4). The three shipped engine plugins (sops, bws,
vault/openbao) are tracked separately as archie-core-xec.1-3.
Adversarially reviewed by a fresh agent with no implementation context;
fixed the two findings that survived (missing per-identity token
validation, underdocumented nil-wrapper Resolve edge case).
SessionStore extended with SaveMessage, RecentMessages, SearchMessages.
NellDB-backed implementation uses a separate DocDB collection for messages
keyed by session:seq. Conversation history loaded into LLM context for each
Telegram message. Responses persisted. Substring search fallback (vector
search deferred to memory provider embedding integration).
Adapter.Store() exported to share the underlying NellDB engine for session
collections without opening a second log.
Telegram LLMResponder now:
- Saves inbound messages to session store
- Loads 20 most recent messages as chat.Message history
- Sends full conversation context to llm.Chat()
- Persists the assistant response
All 38 packages pass with -race.
LLMResponder adapter wraps llm.Chat() with model from cfg.Models[chat] (falls
back to builder). Gateway-local commands (/status, /models, /model, /spawn)
still handled directly. LLM created before gateway so it's available at
router construction time. All 38 packages pass.
Memory:
- MemoryManager created in main.go with built-in file-backed provider
- SystemPromptBlock() injected into every agent stage request via ExtraRules
- memoryPrompt() helper on Daemon, threaded through TaskContext.SystemPrompt
Guardrails:
- GuardrailEngine created from DefaultGuardrailConfig in main.go
- RecordSuccess/RecordFailure called after every agent stage run
- Threaded through TaskContext.Guardrails for per-task guardrail enforcement
Tool registry:
- NewRegistry() created at startup, MCP servers started from config
- Passed to Daemon.ToolRegistry for dynamic tool discovery
Daemon changes:
- Memory, Guardrails, ToolRegistry fields added (nil-safe, backward compat)
- TaskContext gains SystemPrompt + Guardrails fields
- Agent stage injects memory context into ExtraRules
- Agent stage records guardrail state after each run
Telegram LLM routing deferred (TODO comment) — gateway commands work.
All 38 packages pass with -race.