A pending update report used to be relayed verbatim. It is entirely
self-reported: scripts/archie-update-watchdog decides "passed" from
`curl -sf $HEALTH_URL/healthz`, which only proves that *a* daemon is
answering, then copies the version the installer *intended*
(ARCHIE_UPDATE_INSTALLED_GATEWAY) into the report. If the new binary
never made it into service, the previous daemon answers the probe just
as happily, so the message read "Update complete: daemon 1.9.8 -> 1.9.0.
Health check passed - archie-core is healthy on the new version" about a
version that was not running. That shipped: /update reported success and
the next task hit the exact bug the update was meant to fix (#468).
Report.Verify now checks the claims against the versions components
report for *themselves* -- archied's compiled-in gatewayVersion, which no
installer can talk it out of -- and partitions every claimed component
into Confirmed, Drift or Unverified.
What changed in MEANING:
- A passed health check used to mean "the new version is running". It
now means only "something answered"; the version claim is a separate,
separately-checked assertion.
- "Update complete ... healthy on the new version" used to be the only
success wording. There are now three outcomes, because collapsing them
is how the false success happened: confirmed, unconfirmed ("I could
not confirm which version is actually running"), and contradicted
("Update did NOT take effect").
- An unverifiable component is NOT a failing one. Absent, empty,
"unknown" (the watchdog's own default) and "dev" (an unstamped build)
all mean "we could not check", never "it is wrong" -- treating them as
drift would turn healthy updates whose bookkeeping went missing into
reported failures.
Verification covers the daemon only, deliberately. archied's compiled-in
runtimeVersion records what its own pipeline stamped, not what the agent
container runs, so vouching for the agent would be the same kind of
guess this change exists to remove. The agent is therefore Unverified on
every successful update, and the success message names it as unchecked
rather than letting the confirmed daemon silently vouch for it.
Drift detail is attached per component: one component can sit on the
version the update meant to replace while another is on some third
version, and a single explanatory sentence would state a falsehood about
one of them.
Regression tests were confirmed to fail against the pre-fix code,
reproducing the exact false-success string, and each new guard was
mutation-tested. The drift-ordering test's component count is
load-bearing and documented: Go rotates small maps rather than permuting
them, so 8 components let an unsorted implementation pass ~12% of the
time while 9 fails it outright.
Refs #522, #468
config.docker.toml launches MCP servers with `npx -y <pkg>@<version>`,
and the container has no persistent npm cache, so every daemon restart
re-resolved and re-downloaded the package from the registry -- slow,
and it turns a registry outage or a yanked version into a daemon
outage. It directly amplified the crash loop observed on 2026-07-30,
since each restart repeated the whole download.
configuredMCPProvider now points npx-launched servers (matched by base
name, so an absolute-path npx still qualifies) at NPM_CONFIG_CACHE
under the daemon's own persistent work_dir, plus
NPM_CONFIG_PREFER_OFFLINE=true so a warm cache skips the registry
round trip entirely. Does not cover a package's own separate
downloads (e.g. Playwright/Puppeteer fetching a browser binary via
its postinstall script).
Closes archie-core-1786637490923-43-d4bb914b.
The identical, arguably worse instance in
internal/app/agentworker/mcp_providers.go (every per-task ephemeral
container, not just daemon restarts) needs a persistent Docker volume
that doesn't exist yet, so it's filed separately as
archie-core-qk8m rather than folded into this scoped fix.
The /update command went silent between "starting" and one final message,
gave no version summary, and required manual intervention on failure.
CommandInstaller now streams the installer script's stdout live instead of
buffering it, and parses a structured result (previous/installed versions,
per-component status) from a sentinel line. Because the reference install
script hands the daemon restart off to a detached systemd unit specifically
so restarting archied.service doesn't kill the process that requested the
update, the outcome is reported in two phases: the synchronous build/install
result comes back through Install() itself, and the post-restart health
check/rollback outcome is written by a new watchdog script and relayed by
whichever archied process boots next, via a small JSON handoff file cleared
once relayed.
Also fixes three defects an adversarial review pass found in the first
draft: the caller's request/handler context was passed straight into the
install child process, so a concurrent /restart or a browser disconnect
could SIGKILL it mid binary-copy; Telegram and the web dashboard each
tracked "install in progress" with their own private flag despite sharing
one Service, allowing two installs to race the same .prev backups; and the
watchdog reported rolled_back:true even when no backup existed to restore,
which would have told an operator to stand down while the daemon was still
broken.
internal/webui gains an unauthenticated /healthz the watchdog polls after
restarting archied.
CLI-based, env-configured, cache-less engines resolving SecretRef values
through the existing Yaegi plugin surface. Fresh resolve per call, so
values updated in the backend are picked up without daemon restart —
closing the gap that motivated the remote secret-input epic (#504),
whose value-entry web form duplicated the Bitwarden app for bws.
- examples/secret-engines/: sops (SOPS_FILE), vault (VAULT_ADDR/TOKEN,
key "path/field" or VAULT_SECRET_PATH prefix), age (AGE_FILE/
AGE_IDENTITY, key=value lines). //go:build ignore keeps them out of
the Go toolchain; yaegi treats the tag as a comment and loads them.
- enginehost: host-side Run helper registered as a Yaegi symbol. yaegi's
interpreted os/exec cannot pass env to child processes, so plugins
shell out through host code; bounded by a 30s timeout like the bws
engine.
- secret.LoadDir seeds the interpreter with the host environment: yaegi's
interpreted os package keeps a private env otherwise, and plugin
os.Getenv would silently see nothing.
- cmd/archied wires enginehost + unrestricted symbols into the engine
plugin loader, matching skillscript's interpretation posture.
- tests load the real shipped plugin files with fake CLIs on PATH;
added CONTEXT.md glossary for the remote secret-input vocabulary.
/update could report success at the correct target version while the
archie-agent container running it never actually changed: the update
mechanism trusted the configured installer's exit code and reported
whatever version number the release claimed, with nothing verifying
the two agreed.
The first piece of the fix: a new internal/installtype package
reports how a binary was built for distribution (Type(), defaulting
to "unknown"), stamped once per release artifact via
"-ldflags -X .../installtype.buildType=<value>" rather than guessed
at runtime by probing the environment -- restic and Tailscale both
treat "which install shape is this" as a build-time decision for the
same reason: a probed signal is guessable, a compiled-in one is not.
releaseupdate.Service.Install now refuses to run the configured
Installer at all when InstallType is unset or installtype.Unknown, so
an unstamped or misconfigured build can no longer silently attempt an
update it has no way to know is even the right kind for how this
instance was deployed. Wired through every real archied build path so
the gate doesn't just exist in principle: Taskfile.yml's build task
(binary), Dockerfile.archied (container), and install.sh (binary) all
now stamp it; cmd/archied/telegram_setup.go wires
Service.InstallType from installtype.Type().
Configuration-page display of install type/version and post-update
verification against the actually-running reference (not just the
installer's reported version) remain open -- this lands the
correctness gate, not the full observability surface.
Refs #522
A workflow run through the container/NATS path never wired
workflow.TaskContext.Bus, so every tc.Emit call (stage_start,
stage_finish, outcome, parked) was a silent no-op. archied's own
in-process path sets Bus and always worked; anything dispatched to an
archie-agent worker did not, which meant the dashboard's per-task
timeline showed "No events yet" for every task regardless of status
or stage -- confirmed live across a Working task and two differently
parked tasks.
Bridges the gap the same way system logs already cross this boundary:
ForwardTaskEvents relays a per-task in-process *events.Bus to a new
NATS subject (SubjectForEvents), and a new daemon-side subscriber
(subscribeAgentEvents) republishes decoded events on the daemon's own
Bus, landing them in the same persist-and-broadcast pipeline an
in-process workflow already used.
Closes#518
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.
cmd/archied carried a copy of the none/off/disabled predicate because the
configuration package's version was unexported. Two copies of a validation
predicate drift: a fourth disabled alias added in one place would silently
leave the other accepting it.
Export ForgeDisabled in internal/infrastructure/configuration as the single
definition, referenced by both validateIdentities and resolveForge, and
delete the duplicated copy. TestForgeDisabled pins the exact alias set
(including case-variant and empty-string guards); the resolveForge
degradation test now asserts on the warn log so the silent disabled path is
distinguishable from the token-unavailable fallback (verified to fail under
a re-inlined 'none'-only copy).
cmd/archie-agent used to own worker construction, NATS lifecycle, task execution, MCP setup, and workflow wiring. It now owns process input only and invokes internal/app/agentworker, while transport-specific NATS, boot-brief, and git-safety mechanics live under infrastructure.
Telegram streaming callbacks now enqueue cancellable rendering rather than performing network I/O while draining the authoritative model stream. Final edit failures fall back to normal split delivery.
Completed tool events now correlate inputs by call ID and expose only bounded, conservative parameter shapes. Tool-call visibility is snapshotted per reply so reloads cannot change an in-flight turn.
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
The dubious-ownership fix landed twice: markWorktreeSafe in gitsafe.go
and an inline exec.Command block in main.go, both configuring the same
safe.directory on every start. Two setup paths for one invariant means a
later change to either one silently disagrees with the other.
Keep the tested helper and drop the inline block. markWorktreeSafe also
skips the call when /data/worktree is not a mounted directory, so
running archie-agent directly on a host no longer writes to the
operator's own ~/.gitconfig for a path that was never mounted.
The new test parses main.go and fails on more than one setup path, so a
future re-addition of an inline block is caught rather than merged.
Refs #468
Agent containers bind-mount the worktree from the host at
/data/worktree, where the owning UID differs from the container
user's UID. Git refuses to operate in such directories, so every
gate command that calls the Go toolchain (go build/test/vet) fails
with 'fatal: detected dubious ownership in repository' before any
real work begins.
Add 'git config --global --add safe.directory /data/worktree' at
archie-agent startup so all subsequent git-spawned operations
(baseline gate, build gate, agent shell tool invocations) work
correctly. Logs a warning if git is unavailable rather than
failing — the agent remains usable for repos with no gate config.
gatewayVersion and runtimeVersion were reachable only through the chat
/version command, which needs a running daemon and a configured channel.
An update-check adapter has to answer "what is installed?" before it can
compare against what is available, and had no way to ask.
Prints one "name version" pair per line so a shell adapter can parse it
without a JSON dependency.
Second adversarial pass findings, fixed:
BLOCKER -- PATCH silently dropped every dotted key. The UI sends
dotted keys ('budgets.max_steps') but ApplyOverlayValues fed them
straight to yaml.Unmarshal, which cannot decode a dotted key as a
struct field and silently ignored it: 200 OK, zero effect, and the row
still persisted (poisoning later reloads with an unvalidated value).
The reload path worked only because overlay.Snapshot nests first. Fix:
applyDottedOverlay nests dotted keys via overlay.Nest before decode --
the same nesting Snapshot performs -- and is pinned by
TestApplyDottedOverlayNestsBeforeDecode, which fails against the old
behaviour.
MAJOR -- shallow copies let overlay decode mutate the published
snapshot. Holder.Get and *doc are shallow; yaml decodes maps in place,
so a crafted nested update (or a failed boot overlay apply) mutated
shared maps of the published config before validation. Fix: config.Clone
deep-copies every reference field (Models, Providers, Repos, Identities,
Dispatch.Labels, Agent.Env, Chat/Telegram slices, Tools.MCPServers,
Memory.ProviderConfig, WebFetch.Enabled pointer, Extra), used by the
PATCH path (next := d.Cfg.Get().Clone()) and by Loader.ApplyOverlay,
which now never mutates its input (clones Config and the provenance
chain internally), so boot and reload pass the base document directly
and a failed apply leaves it exactly as it was. Pinned by
TestConfigCloneDeepCopiesReferenceFields.
MAJOR -- data races on captured main.go variables. bootOverlayErr and
currentProvenance were plain values written by the SIGHUP goroutine and
the PATCH/Reset handlers and read by every GET /api/config; -race passed
only because no test exercised the composition root concurrently. Both
are now atomic.Pointer; the LastReload closure and the provenance
dedup read them atomically.
MINOR -- MaxConcurrency removed from the reloadable allowlist. The
dispatchers re-read it but the startup-built container pool captures it
(container/pool.go:94,163), so 'every consumer re-reads it' is false and
a change only partially applies. It now warns requires-restart; the
criterion comment on reloadableFields documents the pool capture.
MINOR -- ResetConfig now resolves and validates the target state BEFORE
deleting the row, so a broken file cannot leave the store and the
running config disagreeing; the provenance chain no longer grows
unboundedly (the runtime-overlay origin replaces, not appends).
Also: holder.go no longer references a file watcher that does not exist.
Verified: task check clean; -race clean on cmd/archied, webui, daemon,
config; new findings from the second adversarial pass are closed.
Three gaps closed, all in the 'your change didn't take effect and
nothing told you' family:
1. MaxRetries joins the reloadable allowlist, and the criterion is
fixed on reloadableFields: a field is reloadable when EVERY
consumer re-reads it. MaxRetries is the worked example -- its only
consumer is the webui maxRetriesFor handler, which re-reads per
request (api_tasks.go:380,383); nothing in the daemon reads it, so
warning 'requires restart' was spurious. Chat.Telegram.TokenEnv is
documented as the counter-example (webui reads it per request but a
startup-built telegram bot consumes it, so it is not reloadable).
Pinned by TestChangedNonReloadableFields alongside the comment.
2. Boot-time overlay degradation is now surfaced. config.ReloadStatus
gains OverlayUnavailable; main.go records the reason when the
overlay store cannot be opened or its values fail validation, and
/api/config carries it (merged into LastReload). Cleared by a
successful dashboard write or reset. The settings page renders a
warning banner, so a daemon running on file config alone says so
where the operator is looking, not only in logs.
3. Overlay-shadowed file edits are visible and recoverable.
ConfigView.Overridden lists the dotted keys the runtime overlay
currently sets, so the UI marks those rows (their file value is
shadowed until reset). POST /api/config/reset exposes the
store's Delete as a per-row reset: it deletes the row and
republishes file + remaining overlay, which is also the answer to
'my file edit isn't taking effect'. The dashboard can now remove
every override it can create.
Verified: task check clean; -race clean on cmd/archied, webui,
infrastructure/configuration; new handler tests cover the reset
200/400/503 paths and the overridden list.
The second half of #348's storage layer: dashboard-edited overrides
live in their own SQLite file, separate from the task and conversation
stores so each file owns its user_version and migrator with no
contention (configDBPath -> cfg.DBPath + "-config.sqlite", matching
the taskDBPath / conversationDBPath convention).
Store (internal/infrastructure/configuration/overlay):
- config_overlay(key TEXT PRIMARY KEY, value TEXT NOT NULL,
updated_at, updated_by), own migration, WAL.
- Set refuses DeniedKeys (db_path, work_dir) at write time as well as
at the API layer; the map is exported so the dashboard can show the
reason instead of silently omitting the edit affordance.
- Snapshot JSON-decodes each value and nests dotted keys
("budgets.max_steps" -> map[b][m]) ready to decode into Config.
Loader (ApplyOverlay / ApplyOverlayValues):
- Decodes a nested overlay map with the same field-level precedence as
a file overlay, records the runtime-overlay origin, then applies
defaults and validates. Used at boot, on SIGHUP reload (ReloadController
gained an optional WithOverlay source) and by the PATCH path.
Boot and reload:
- A broken overlay (unopenable store, unreadable snapshot, values that
fail validation) degrades to file config alone -- it must never brick
the daemon. --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1 skips
the store entirely; the flag is now a real gate, not a log-only stub.
PATCH /api/config (webui):
- handleConfigUpdate decodes {"updates": {dotted.key: value}}, calls
the composition-wired UpdateConfig seam, and classifies errors via
webui sentinels: ErrConfigUpdateInvalid -> 400 (denylisted key,
failed validation, unparseable value), ErrConfigUpdateUnavailable ->
503 (overlay skipped by recovery flag), anything else -> 500.
- The seam (main.go) applies updates to a COPY of the published
config, validates the materialised result, persists to the overlay,
then publishes through the same path as reload -- it never calls
Set directly from the handler, since web.Cfg is the daemon's own
Holder.
- ConfigView gains Locked (dotted key -> reason) so the UI disables
denylisted rows explicitly.
Verified: task check clean; new tests cover the store round-trip,
denied keys, loader overlay layering/validation/provenance, reload
with and without overlay, and the PATCH handler's 200/400/503 paths.
The allowlist drifted before the chunk shipped. ForTask (config.go:457-465)
is the authoritative per-dispatch snapshot and carries Models, Budgets,
Dispatch, DiffCapLines, Notify and Forge.Host -- I allowlisted only three.
And the poll path reads cfg.Label and cfg.BotUser live per cycle
(daemon.go:359,390 and :368,381) off the same per-poll config as
Dispatch.Trigger. Five fields would have reported 'requires a restart'
while actually taking effect immediately: the safe direction, but exactly
the warning-fatigue failure that kills the feature (an operator who is
told to restart for a label change that already applied learns the
warning is noise).
The fix is enforcement, not a bigger list: TestReloadableFieldsCoverForTaskSnapshot
reflects over TaskConfig and fails if any field ForTask carries is not in
the allowlist (Forge maps to the Forge.Host sub-field entry). A field
added to ForTask later now fails the test instead of silently producing a
wrong warning. Label and BotUser are not carried by ForTask -- they come
off the poll path -- so they are allowlisted by hand with a comment, and
the same test pins them explicitly.
Also documents on webui.Server.Cfg that in production it is the daemon's
OWN Holder (web.Cfg = d.Cfg), so Set publishes to the running daemon: a
config-mutating handler must apply to a copy, validate the materialised
config, persist, then Set -- never Set directly.
task check clean.
Adversarial review findings (fresh reviewer, no memory of the code):
1. (major) web.Cfg was a second Holder the reload never swapped, so
/api/config showed boot-time values forever after the first reload
while the daemon ran the new config -- the exact 'code means
something different from what it says' failure. web and d now
share one Holder (web.Cfg = d.Cfg after construction), so a reload
swaps both views atomically.
2. (minor) the model catalog merge ran once at boot; publishing the
raw reloaded document dropped catalog-discovered providers from
the running config even though the file was unchanged. The apply
closure re-runs applyModelCatalog on the reloaded document before
publishing (idempotent; a catalog that failed to load merges to
identity).
3. (minor) changedNonReloadableFields parameter 'new' shadowed the
predeclared identifier (predeclared lint finding). Renamed to
'next'; the finding is gone from the branch diff.
Also: tightened --no-config-overlay help text to state the file
-config-overlay still applies (it gates the future DB overlay only),
and documented that the controller's apply callback must be non-nil.
task check clean; -race clean on cmd/archied and internal/daemon.
The daemon can now re-read its configuration on SIGHUP (or on a
future in-process trigger) and republish it through the Holder,
closing the first half of issue #348: 'config can change at runtime,
safely, and can't brick the daemon.'
Reload path:
- cmd/archied/reload.go: ReloadController re-runs loader.Resolve on
the same paths main.go passed at startup (Resolve is pure -- no
reload state added to the loader). apply is called only with a
Document that passed validation; a failed reload records the error
and its timestamp and leaves the running config untouched. That
Set-not-called-on-error property is the safety core and is pinned
by TestReloadValidationFailureDoesNotApply.
- SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log);
the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only,
fine given the Linux target).
PollInterval is genuinely reloadable now, not just re-read:
the three ticker sites (Run, per-identity goroutine, shared
maintenance loop) re-read the interval each tick and Reset the ticker
on change. A reloaded poll_interval takes effect on the next cycle.
Diff-and-warn so an operator never has to read the source to know
whether an edit took effect: changedNonReloadableFields compares the
old and new snapshots against an allowlist of re-read fields
(PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the
Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that
changed logs Warn 'requires a restart'; a fully-applied reload logs
Info. The allowlist is deliberate: a field added to Config later
defaults to requires-restart, the safe direction.
NATS split-brain closed: containerEnv now hands containers the
endpoint the daemon's own client connected with at startup
(Daemon.ConnectedNATS, captured at construction) instead of the live
config, so a reloaded nats.url cannot point new containers at a
server the daemon is not publishing on. A nats change is therefore
classified requires-restart, and CLAUDE.md's 'hands its own nats.url
verbatim' note is updated to the meaning it now has (same today,
deliberately different after a reload).
Validation guard: poll_interval <= 0 is rejected in validate.go
beside the VolumeTTL guard. applyDefaults fills zero with 60s, so
this fires on an explicit negative -- which would panic
time.NewTicker/Reset at boot and, after the per-iteration reset,
on a SIGHUP mid-run.
Observability: config.ReloadStatus (last_error, last_error_at,
last_reload_at) is recorded by the controller and surfaced in
/api/config via Server.LastReload, so a stale running config is
visible in the dashboard, not just the logs. Rendering waits for the
UI step.
Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1
(configuration.SkipOverlay), logged at startup. No overlay source
exists yet; the flag is the documented escape hatch the DB overlay
(step 3 of #348) will consult.
webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can
swap it via SetProvenance independently of Cfg; the accepted skew
(new config alongside old provenance) is documented on the field.
Verified: task check clean; -race on daemon, webui, cmd/archied,
config, infrastructure/configuration.
Daemon.Cfg, webui.Server.Cfg, and telegramSetup.Cfg were all held by
value (or as a raw shared pointer in webui's case), so a future reload
path could not swap the running configuration -- the consumers held
frozen snapshots made at construction. This is the prerequisite for
issue #348.
Add config.Holder, a small RWMutex-backed snapshot holder:
- Get returns a value copy under RLock; the copy shares its
reference-type fields with the published snapshot, so a doc
comment pins the immutability invariant (a published Config is
immutable; reload constructs a fresh one).
- Set replaces the snapshot under WLock.
- Get is nil-safe; Set is not.
Convert every consumer to read through the accessor. The convention
'cfg := h.Get() once per logical operation' is documented on the
type so the next reader knows that inline d.Cfg.Get().Foo is a code
smell (a Set could land between two consecutive Gets).
Special cases:
- webui.Server.Cfg: was *config.Config, a raw shared pointer read
from handler goroutines. Convert to *config.Holder. The
pre-existing 'cfg := s.Cfg' aliasing bug at api_config.go:295
(which was *trying* to copy but only copied the pointer) now
becomes 'cfg := s.Cfg.Get()', which is the value copy the
read-only view always wanted.
- daemon_test.go: one test mutated d.Cfg.DiffCapLines in place,
which the Holder forbids. Replace with the documented
read-modify-write pattern (prev := d.Cfg.Get(); prev.X = Y;
d.Cfg.Set(prev)).
- telegramSetup.Cfg: matches the daemon's API for consistency
even though setup runs before the daemon is alive.
TaskContext.Cfg in internal/domain/workflow/workflow.go is
deliberately NOT converted -- a task that starts under one config
should finish under it, and a config changing between TDD and gate
stages is a bug, not a feature. Snapshotted at dispatch, as before.
Verified: go test ./... (61 packages), go vet, -race on
internal/daemon and internal/config.
Task and event persistence now uses a dedicated SQLite sidecar derived from the configured state prefix, matching the independently persisted conversation store. The configured path now means a state-path prefix rather than a database file so fresh SQLite state never attempts to interpret the previous storage format.
Remove the retired implementation and dependency completely, strengthen SQLite migrations and concurrency behavior, restore backend-neutral coverage, and align configuration, operational guidance, UI labels, and deployment documentation with the new storage and host-daemon topology.
Adds two read surfaces for per-task persisted log history so an operator
can answer "why did task N park?" without needing to watch docker ps in
real time — the deployment model documented in CLAUDE.md.
/api/tasks/{id}/logs — built on logging.Tail the same way /api/logs
already is, defaults attempt to the tasks current Attempt from the store.
task_logs chat tool — lets Archie read task logs from Telegram or webui
chat. Identity enforcement matches chatTaskListerAdapter: a model bound
to one identity cannot read another identitys logs, and forge tasks
(empty identity) are denied.
internal/logging: add TaskRegistry.Path() for read-side access without
threading baseDir separately through every caller.
Fixes from adversarial review: strict identity check (no empty-identity
bypass), non-null Entries when disabled, component doc accuracy, and
adapter tests covering the security boundary.
Ref: #455
Closes the loop #451-#453 opened. archie-agent (#453) now publishes its
own logs to agentexec.SubjectForSystem(taskID) over NATS, and a task
log sink (#452) exists to persist them, but nothing on the daemon side
subscribed, demuxed, or wrote anything -- the messages had nowhere to
land.
- agentexec: SubjectSystemWildcard + TaskIDFromSystemSubject, the
inverse of SubjectForSystem, for a daemon subscribing to every
task's system subject with one wildcard subscription.
- logging: TaskRegistry manages one open TaskSink per running task
attempt, mirroring every write onto the live dashboard Feed the same
way a locally-written log would appear. Nil-receiver-safe, matching
every other optional composition-wired Daemon field.
- daemon: Daemon.process opens a task's log sink for its own duration
(covering both the sandboxed-container and in-process dispatch
paths uniformly) and closes it on every return path.
- cmd/archied: constructs the registry, subscribes core NATS to
SubjectSystemWildcard, and wires TaskLogs into both Daemon and
webui.Server.
- webui: archiving a task now removes its log directory too, so
archived tasks' logs don't accumulate forever. Documented as a
known, accepted race: a task can reach terminal status (satisfying
ArchiveTask's precondition) before process() itself returns and
closes the sink, so a very late system-log write can race an
archive's Remove. Not corrupting -- the write lands on a
soon-to-be-unlinked inode and is discarded -- and not worth fixing
here: it would mean tying Close to the store transition instead of
to process()'s return, a larger change than this issue's scope.
Adversarial review (fresh subagent) found and fixed two real issues in
the first draft: a doc comment accidentally spliced between two
functions during an extraction meant to fix a lint regression, and a
genuine test gap on openTaskLog (added, using TaskRegistry.Write's own
true/false contract as the observable -- no Store/Forge/Trees fakes
needed, since openTaskLog only touches TaskLogs and Log).
Part of #453 (task-observability epic #450). archie-agent logged to
os.Stderr only, and its container is created with AutoRemove: true
(internal/container/pool.go), so all of it disappeared the moment a
task's container exited -- there was no way to see why, say, a gate
command failed inside one.
Adds agentexec.SystemLogHandler: a slog.Handler that tees to whatever
it wraps (kept for an operator attached to a live container) and
additionally publishes each record, JSON-encoded as a logging.Entry,
to SubjectForSystem(taskID) -- a subject that already existed,
documented for exactly this ("log dumps, health... observability"),
with zero publishers anywhere in the codebase.
cmd/archie-agent/main.go wires it in only when this container was
spawned for one specific task (bootTaskID / .git/task.json present);
shared queue-group mode serves many unrelated tasks per process, so
there's no single task subject to ship to and keeps the stderr-only
logger.
Building this surfaced a real pre-existing bug: FeedHandler's attr
flattening applied the group chain active at Handle-time to *all*
accumulated attrs, including ones added via WithAttrs before a later
WithGroup call -- nesting them under a group they were never
actually inside, contrary to slog's own documented Handler contract.
It went unnoticed because nothing in the codebase called WithGroup
until this change needed to. Extracting the shared flattening logic
into exported FlattenAttrs/PrefixAttrs (so SystemLogHandler doesn't
duplicate it) is what surfaced it; fixed in the same change since I
was the one making it public API.
Docs on the wire format's own trap for the daemon-side consumer
(#454, not yet written): the published bytes are a marshaled
logging.Entry, meant for json.Unmarshal, not logging.decode() --
decode() parses raw slog JSON *log lines* off disk, a different and
incompatible shape. See the doc comment on SystemLogHandler.
Composition root work tying the config resolver, channel manager, log
feed, and executable workflow registry into the running daemon and
dashboard server: web.Channels/LogFeed/Workflows/ConfigProvenance,
channel-reload wiring, TaskStopper for the Stop action, and
SpawnRequest.Body/WorkRequests threading dashboard "Start work" requests
through the same admission path chat uses. Touches all three features at
once because this is where they're composed, not owned by any single one.
Refs #53, #54, #55
Add cancel/stop/approve/reject/retry/abandon/archive to the dashboard task
action matrix, each guarded by an optimistic status check against the
store. Retry accounting (RetryCount, max_retries) is now atomic with the
status transition instead of a separate write. Archive removes a terminal
task's local record with a fail-safe audit event first. Add always-labelled
responsive navigation, mobile Jump-to search, and versioned Setup-complete
dismissal.
Fixes#53
Adds a human-consent gate for tools marked RequiresApproval, exposes
session management as LLM-invokable chat tools, and gives the operator
/delete to retire conversations permanently.
**Tool-approval gate (internal/tools, internal/agentexec)**
- ApprovalRequester contract lives in internal/tools (not gateway) so
agentexec can import it without pulling in the chat-adapter stack.
- ToolSetOptions.Approval wires the approver through to toolExecute.
- BuildToolSetFrom omits RequiresApproval tools when no approver is
configured; dispatch paths (invokeTool, tool_call bridge) refuse
them too, so the invariant holds at every indirection.
- The gate fails closed: only Approved/PermanentlyApproved pass;
an unknown decision value from a faulty approver does not execute.
- Tool-level timeout (2 min) returns a plain error, not a context
cancellation, so the model can report "approval timed out" instead
of the turn aborting.
- BuildApprovalDescription callback lets a tool surface the specific
resource being acted on ("Delete session \"abc123\"") rather than
showing a static tool description.
**Session tools (internal/gateware/session_tools.go)**
- session_list (idempotent), session_resume (mutating), session_title
(mutating), session_delete (mutating + RequiresApproval).
- Scoped to the current platform + channel: GetByChannel replaces
List() so a model in chat A cannot list or manipulate chat B.
- session_title validates the session belongs to this channel before
writing; session_resume/session_delete resolve refs against the
channel-scoped list.
- Shared limit helper extracted to tools.ListLimit.
**Telegram approval adapter (internal/channels/telegram/approval.go)**
- telegramApprover implements ApprovalRequester via the three-button
inline keyboard (Approve/Permanent/Deny). 2-min token expiry.
- Own map + mutex + "approval:" callback prefix — separate from the
dangerous-command system.
- Permanent approval uses exact-match (not prefix) lookup keyed by
action + resource description, so permanently approving "delete
session abc123" only covers that one session, not every call to
session_delete for 24h.
**Session lifecycle**
- /delete <session-id>: removes a session and its history. Refuses
prefixes shorter than 4 chars even when unique. Exact ID wins over
an ambiguous prefix. sessionTracker.forget sweeps every channel+
thread pointing at the deleted session.
- Extracted resolveSessionRef and shortSessionID for /resume and
/delete to share.
**Wiring**
- submitTurn builds the approver onto ctx before the LLM turn.
- chatGenerateOptions reads approver from ctx, passes it through
ToolSetOptions.
- SessionTools built per turn on the current message, combined with
taskTools into a single toolset.
Multi-identity daemon isolation:
- Split runIdentities into per-identity poll loops plus one shared
maintenance-and-drain loop, so reconcilePRs and storage cleanup run in
multi-identity mode and the global max_concurrency / per-repo
serialization holds across identities.
- Make the poll path identity-aware: each identity polls with its own
forge client, bot user, label, trigger, and ack reaction.
- Make allowConcurrentFor task-based and identity-aware via repoFor.
- Roll back storage mounts when container acquisition fails; log
Store.Update failures after branch set.
Container-mode RPC identity routing:
- forgerpc/worktreerpc gain identity-scoped subjects (SubjectFor,
RegisterFor) and identity-carrying clients.
- registerTaskRPCServers registers one server pair per identity (plus
root), so a container-mode task owned by a non-root identity is served
by its own forge client and worktree manager.
Gateway/Telegram:
- LLM-proposed session titles generated in the background after turns
(TitleGenerator + chatTitleGenerator), persisted by the gateway.
- /delete session command with prefix guard and tracker forget.
- Shared session display helpers (shortSessionID, sessionDisplayTitle,
resolveSessionRef).
- Reword docs and comments to drop vague "legacy" qualifiers where they no longer describe deprecation status
- Remove unused code: RecentEvents, MessageEvent.ToLegacy, index setState, stderr redaction tool, telegramOnlyCommands
- Delete or comment out tests covering removed or superseded behavior
A completed chat turn is published as turn_completed from the single
responder choke point shared by the telegram and web gateways
(redeliveries return earlier and never emit). The runtime wake path
forwards ONLY primary-input kinds to input-driven curators; curator-
produced activity (curator_run/action/error and any future derived
kinds) never appears on that path, so a curator that writes memories
cannot schedule itself again — the feedback-loop guard, with the
rationale recorded in the regression test so it is not removed as
redundant.
The bus subscription is bounded and dropping, so the wake path can
never backpressure the chat publisher; a dropped event only delays a
run to the next check-in.
internal/curator is a conforming engine family per the strict plugin
engine rule: typed CuratorEngine contract (Lifecycle + domain ops),
owning Registry (registration, discovery, start/health/stop with
failure isolation, reverse-order shutdown, ctx-bounded stop), and a
narrow typed Registrar — each curator receives a capability-filtered
view of the host at Bind, never the daemon.
Runtime: one loop per curator on an injectable clock (fake-clock
testable), best-effort wake nudges with the trigger decision kept in
Check (a dropped nudge only delays to the next check-in, never
corrupts accounting), per-pass timeout and a max-concurrent-passes
slot so curator bursts cannot starve chat turns, per-pass panic
recovery, and bounded shutdown even when a pass ignores cancellation.
curator_run / curator_action / curator_error ride the in-process
event bus so activity stays attributable.
Wired in cmd/archied/main.go (constructed beside memory, Start after
daemon startup, shutdown ordered before memory/LLM teardown) and
exposed as daemon.Daemon.Curators.
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.